diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/LICENSE b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/LICENSE deleted file mode 100644 index 0558c41075..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -pgAdmin 4 - -Copyright (C) 2013 - 2022, The pgAdmin Development Team - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose, without fee, and without a written agreement is -hereby granted, provided that the above copyright notice and this paragraph and -the following two paragraphs appear in all copies. - -IN NO EVENT SHALL THE PGADMIN DEVELOPMENT TEAM BE LIABLE TO ANY PARTY FOR -DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST -PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF -THE PGADMIN DEVELOPMENT TEAM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -THE PGADMIN DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, -BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND -THE PGADMIN DEVELOPMENT TEAM HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, -UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_add_acl.sql deleted file mode 100644 index 1efff0af6a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index fa0038a42a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 7ed69fc9bb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_comment.sql deleted file mode 100644 index 87306d1664..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 12c8377cb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 8e604ad5df..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_rename.sql deleted file mode 100644 index 8ed3f8cd8f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index 95f96fb41c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,21 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_comment.sql deleted file mode 100644 index 6753c2bbdf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_comment.sql +++ /dev/null @@ -1,18 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_param.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_param.sql deleted file mode 100644 index 9eca2c4c32..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_proc_param.sql +++ /dev/null @@ -1,19 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index e1cfe4ba7d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index f9ab870789..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index dda2309075..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index ed1e163d0b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 50f59804c1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_function.sql deleted file mode 100644 index 7be119d6a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_function.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 12c8377cb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index 759c632e9c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index 73040efbd0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,27 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_procedure.sql deleted file mode 100644 index 87da57550c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F11_plus%2Fcreate_procedure.sql +++ /dev/null @@ -1,15 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_add_acl.sql deleted file mode 100644 index 1efff0af6a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index fa0038a42a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 7ed69fc9bb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_comment.sql deleted file mode 100644 index 87306d1664..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 12c8377cb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 8e604ad5df..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_rename.sql deleted file mode 100644 index 8ed3f8cd8f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index 95f96fb41c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,21 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_comment.sql deleted file mode 100644 index 6753c2bbdf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_comment.sql +++ /dev/null @@ -1,18 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_param.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_param.sql deleted file mode 100644 index 9eca2c4c32..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_proc_param.sql +++ /dev/null @@ -1,19 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index e1cfe4ba7d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index f9ab870789..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index dda2309075..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index ed1e163d0b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 90a6c6db8c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - STABLE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_function.sql deleted file mode 100644 index 7be119d6a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_function.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 12c8377cb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index 759c632e9c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index b07f721c7e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,27 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - STABLE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_procedure.sql deleted file mode 100644 index 87da57550c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F12_plus%2Fcreate_procedure.sql +++ /dev/null @@ -1,15 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index d7b6550a3c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,20 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_comment.sql deleted file mode 100644 index c550c19db4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_comment.sql +++ /dev/null @@ -1,17 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_param.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_param.sql deleted file mode 100644 index 74ae1c6b95..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Falter_proc_param.sql +++ /dev/null @@ -1,18 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Fcreate_procedure.sql deleted file mode 100644 index d5dd6b3e59..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F14_plus%2Fcreate_procedure.sql +++ /dev/null @@ -1,14 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_add_acl.sql deleted file mode 100644 index 79d8a1fe07..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO postgres; - - - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index c901f8bbcb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index ead07955f7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_comment.sql deleted file mode 100644 index 71aab9c6ff..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 8f4b38ae68..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index d42da98c26..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_rename.sql deleted file mode 100644 index 8f12841a5e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index e1cfe4ba7d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index f9ab870789..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index dda2309075..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index ed1e163d0b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 50f59804c1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_function.sql deleted file mode 100644 index 2a94729d58..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_function.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 8f4b38ae68..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE WINDOW - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index 759c632e9c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index 73040efbd0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.5_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,27 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_add_acl.sql deleted file mode 100644 index 1efff0af6a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index fa0038a42a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 7ed69fc9bb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_comment.sql deleted file mode 100644 index 87306d1664..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 12c8377cb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 8e604ad5df..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_rename.sql deleted file mode 100644 index 8ed3f8cd8f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index e1cfe4ba7d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index f9ab870789..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index dda2309075..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index ed1e163d0b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 50f59804c1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_function.sql deleted file mode 100644 index 7be119d6a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_function.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO postgres; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 12c8377cb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index 759c632e9c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index 73040efbd0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2F9.6_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,27 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_comment.sql deleted file mode 100644 index 9538dde02b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_1.sql deleted file mode 100644 index 87e1f4bd16..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_2.sql deleted file mode 100644 index 351d0ba117..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_3.sql deleted file mode 100644 index fd1d62aada..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_event_trigger_full.sql deleted file mode 100644 index fdd0225b26..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger.sql deleted file mode 100644 index 435237a01c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index 5d8d930013..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,27 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO postgres WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_add_acl.sql deleted file mode 100644 index fbaab278e4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO enterprisedb; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index e68ca8a324..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 53a6d190f0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_comment.sql deleted file mode 100644 index 585fd01084..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 87c9237ddf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 31a37a1d0c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_rename.sql deleted file mode 100644 index 5da7704953..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index 41a96510a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,21 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_comment.sql deleted file mode 100644 index 52a21fbaae..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_comment.sql +++ /dev/null @@ -1,18 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_param.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_param.sql deleted file mode 100644 index 6b640a0840..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_proc_param.sql +++ /dev/null @@ -1,19 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index 1567350448..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index 1981336d0d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index b4c873f4ce..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index e5d4ae9709..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 4950ef5a61..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_function.sql deleted file mode 100644 index 1dede6255b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_function.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 87c9237ddf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index a794a288a2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index e74efbcc65..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_procedure.sql deleted file mode 100644 index 77b2a0cf02..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F11_plus%2Fcreate_procedure.sql +++ /dev/null @@ -1,15 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_add_acl.sql deleted file mode 100644 index fbaab278e4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO enterprisedb; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index e68ca8a324..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 53a6d190f0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_comment.sql deleted file mode 100644 index 585fd01084..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 87c9237ddf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 31a37a1d0c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_rename.sql deleted file mode 100644 index 5da7704953..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index 41a96510a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,21 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_comment.sql deleted file mode 100644 index 52a21fbaae..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_comment.sql +++ /dev/null @@ -1,18 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_param.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_param.sql deleted file mode 100644 index 6b640a0840..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_proc_param.sql +++ /dev/null @@ -1,19 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index 1567350448..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index 1981336d0d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index b4c873f4ce..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index e5d4ae9709..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index f10c8cc5f6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,26 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO enterprisedb WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_function.sql deleted file mode 100644 index 1dede6255b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_function.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 87c9237ddf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index a794a288a2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index b47c38bd7d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,27 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() TO enterprisedb WITH GRANT OPTION; - -REVOKE ALL ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() FROM PUBLIC; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_procedure.sql deleted file mode 100644 index 77b2a0cf02..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F12_plus%2Fcreate_procedure.sql +++ /dev/null @@ -1,15 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index 658111d4aa..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,20 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_comment.sql deleted file mode 100644 index 61485c8821..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_comment.sql +++ /dev/null @@ -1,17 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_param.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_param.sql deleted file mode 100644 index 5d7491f418..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Falter_proc_param.sql +++ /dev/null @@ -1,18 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Fcreate_procedure.sql deleted file mode 100644 index bce3f5e11a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F14_plus%2Fcreate_procedure.sql +++ /dev/null @@ -1,14 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - IN i1 integer) -LANGUAGE 'plpgsql' -AS $BODY$ -begin -select 1; -end; -$BODY$; -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_add_acl.sql deleted file mode 100644 index a11c52100f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO enterprisedb; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index 7afd695a6b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 0710dddd3f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_comment.sql deleted file mode 100644 index b38a5aef74..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index fd8f035bae..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 6790c12821..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_rename.sql deleted file mode 100644 index b86e9d559c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Fcreate_function.sql deleted file mode 100644 index 81c2f07f15..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Fcreate_function.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index fd8f035bae..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.5_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) -RETURNS character varying - LANGUAGE 'plpgsql' - VOLATILE SECURITY DEFINER WINDOW - COST 100 - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_add_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_add_acl.sql deleted file mode 100644 index fbaab278e4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_add_acl.sql +++ /dev/null @@ -1,24 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO enterprisedb; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_add_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_add_parameter.sql deleted file mode 100644 index e68ca8a324..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_add_parameter.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET application_name='appname' - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_change_grantee_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_change_grantee_acl.sql deleted file mode 100644 index 53a6d190f0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_change_grantee_acl.sql +++ /dev/null @@ -1,21 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -GRANT EXECUTE ON FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() TO PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_comment.sql deleted file mode 100644 index 585fd01084..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_comment.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - IS 'Some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_delete_acl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_delete_acl.sql deleted file mode 100644 index 87c9237ddf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_delete_acl.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_delete_parameter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_delete_parameter.sql deleted file mode 100644 index 31a37a1d0c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_delete_parameter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '2'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_rename.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_rename.sql deleted file mode 100644 index 5da7704953..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_function_rename.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function3_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function3_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function3_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_proc_change_grantee_priv.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_proc_change_grantee_priv.sql deleted file mode 100644 index dbcc463883..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_proc_change_grantee_priv.sql +++ /dev/null @@ -1,21 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE IF EXISTS public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) -LANGUAGE 'plpgsql' - SET application_name='pgadmin' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#" - OWNER TO enterprisedb; - -GRANT EXECUTE ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) TO PUBLIC; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer) - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_proc_opt_msql.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_proc_opt_msql.sql deleted file mode 100644 index c7cfe58d1a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_proc_opt_msql.sql +++ /dev/null @@ -1,15 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) - VOLATILE SECURITY DEFINER PARALLEL RESTRICTED - COST 120 - SET application_name='pgadmin' -AS begin -select 1; -end; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#" - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_comment.sql deleted file mode 100644 index 1567350448..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_1.sql deleted file mode 100644 index 1981336d0d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_2.sql deleted file mode 100644 index b4c873f4ce..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_3.sql deleted file mode 100644 index e5d4ae9709..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 4950ef5a61..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_function.sql deleted file mode 100644 index 1dede6255b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_function.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function1_$%{}[]()&*^!@"'`\/#(character varying) - --- DROP FUNCTION IF EXISTS public."Function1_$%{}[]()&*^!@""'`\/#"(character varying); - -CREATE OR REPLACE FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"( - param character varying DEFAULT '1'::character varying) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function1_$%{}[]()&*^!@""'`\/#"(character varying) - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_function_for_alter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_function_for_alter.sql deleted file mode 100644 index 87c9237ddf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_function_for_alter.sql +++ /dev/null @@ -1,19 +0,0 @@ --- FUNCTION: public.Function2_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Function2_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"( - ) - RETURNS character varying - LANGUAGE 'plpgsql' - COST 100 - VOLATILE SECURITY DEFINER PARALLEL UNSAFE - SET enable_sort='true' -AS $BODY$ -begin -select '1'; -end -$BODY$; - -ALTER FUNCTION public."Function2_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_plain_trigger.sql deleted file mode 100644 index a794a288a2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index d1bcf8b0e4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2F9.6_plus%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - STABLE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_proc_opt_msql.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_proc_opt_msql.sql deleted file mode 100644 index 147ebbe021..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_proc_opt_msql.sql +++ /dev/null @@ -1,15 +0,0 @@ --- PROCEDURE: public.Proc1_$%{}[]()&*^!@"'`\/#(integer) - --- DROP PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"(integer); - -CREATE OR REPLACE PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#"( - i1 integer) - STABLE SECURITY DEFINER - COST 120 - SET application_name='pgadmin' -AS begin -select 1; -end; - -COMMENT ON PROCEDURE public."Proc1_$%{}[]()&*^!@""'`\/#" - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_comment.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_comment.sql deleted file mode 100644 index 1567350448..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_comment.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_1.sql deleted file mode 100644 index 1981336d0d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_1.sql +++ /dev/null @@ -1,20 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - STABLE LEAKPROOF STRICT SECURITY DEFINER -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_2.sql deleted file mode 100644 index b4c873f4ce..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_2.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_3.sql deleted file mode 100644 index e5d4ae9709..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Falter_ptrig_set_3.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 123 - IMMUTABLE LEAKPROOF STRICT SECURITY DEFINER - SET application_name='appname2' - SET search_path=public, pg_catalog - SET array_nulls='true' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_event_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_event_trigger_full.sql deleted file mode 100644 index 4950ef5a61..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_event_trigger_full.sql +++ /dev/null @@ -1,22 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF event_trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger.sql deleted file mode 100644 index 2d7383c6d3..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger_full.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger_full.sql deleted file mode 100644 index e74efbcc65..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ffunctions%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger_full.sql +++ /dev/null @@ -1,23 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS SETOF trigger - LANGUAGE 'plpgsql' - COST 1234 - VOLATILE LEAKPROOF STRICT SECURITY DEFINER WINDOW - ROWS 4321 - SET application_name='appname' - SET search_path=public, pg_temp -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; - -COMMENT ON FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - IS 'some comment'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ftables%2Ftriggers%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ftables%2Ftriggers%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger_function.sql deleted file mode 100644 index 759c632e9c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ftables%2Ftriggers%2Ftests%2Fpg%2Fdefault%2Fcreate_plain_trigger_function.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO postgres; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ftables%2Ftriggers%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger_function.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ftables%2Ftriggers%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger_function.sql deleted file mode 100644 index a794a288a2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Fbrowser%2Fserver_groups%2Fservers%2Fdatabases%2Fschemas%2Ftables%2Ftriggers%2Ftests%2Fppas%2Fdefault%2Fcreate_plain_trigger_function.sql +++ /dev/null @@ -1,17 +0,0 @@ --- FUNCTION: public.Trig1_$%{}[]()&*^!@"'`\/#() - --- DROP FUNCTION IF EXISTS public."Trig1_$%{}[]()&*^!@""'`\/#"(); - -CREATE OR REPLACE FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - RETURNS trigger - LANGUAGE 'plpgsql' - COST 100 - VOLATILE NOT LEAKPROOF -AS $BODY$ -begin -select 1; -end; -$BODY$; - -ALTER FUNCTION public."Trig1_$%{}[]()&*^!@""'`\/#"() - OWNER TO enterprisedb; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F10_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F10_plus%2Fsource.sql deleted file mode 100644 index 9b54fe88e6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F10_plus%2Fsource.sql +++ /dev/null @@ -1,1160 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12272 (class 1259 OID 149205) --- Name: table_for_partition; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition ( - col1 bigint NOT NULL -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition OWNER TO postgres; - --- --- TOC entry 12273 (class 1259 OID 149208) --- Name: part1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part1 ( - col1 bigint NOT NULL -); -ALTER TABLE ONLY test_schema_diff.table_for_partition ATTACH PARTITION test_schema_diff.part1 FOR VALUES FROM ('1') TO ('23'); - - -ALTER TABLE test_schema_diff.part1 OWNER TO postgres; - --- --- TOC entry 12274 (class 1259 OID 149213) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO postgres; - --- --- TOC entry 12275 (class 1259 OID 149216) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('1') TO ('10'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO postgres; - --- --- TOC entry 12276 (class 1259 OID 149219) --- Name: part4; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part4 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part4 FOR VALUES FROM ('11') TO ('20'); - - -ALTER TABLE test_schema_diff.part4 OWNER TO postgres; - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhaspkey, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'POSIX', LC_CTYPE = 'POSIX'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO postgres; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO pg_monitor WITH GRANT OPTION; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_enum_src TO pg_monitor WITH GRANT OPTION; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO pg_monitor; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO pg_monitor WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - --- Foreign Table scripts -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_src TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.1"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO postgres; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - --- Publication Script -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table - FOR TABLE test_schema_diff.table_for_publication - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table - RENAME TO with_one_table_alter; - -ALTER PUBLICATION with_one_table_alter SET - (publish = 'insert, update'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1 - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1 - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1 - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1 - RENAME TO subscription_test; - -DROP SUBSCRIPTION subscription_test; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F10_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F10_plus%2Ftarget.sql deleted file mode 100644 index d51563d404..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F10_plus%2Ftarget.sql +++ /dev/null @@ -1,1111 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO postgres; - --- --- TOC entry 12277 (class 1259 OID 149234) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO postgres; - --- --- TOC entry 12278 (class 1259 OID 149237) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('13') TO ('56'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO postgres; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO postgres; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO postgres; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: postgres --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhaspkey, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO postgres; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO postgres; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO postgres; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO pg_monitor; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO postgres; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO postgres; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping; - --- Publication script - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE TABLE test_schema_diff.table_for_publication_in_target ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table_in_target - FOR TABLE test_schema_diff.table_for_publication_in_target - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table_in_target - RENAME TO with_one_table_in_target_alter; - -ALTER PUBLICATION with_one_table_in_target_alter SET - (publish = 'insert, update'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1_in_target" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1_in_target - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1_in_target - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1_in_target - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1_in_target - RENAME TO subscription_test_in_target; - -DROP SUBSCRIPTION subscription_test_in_target; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F11_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F11_plus%2Fsource.sql deleted file mode 100644 index d121ee5393..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F11_plus%2Fsource.sql +++ /dev/null @@ -1,1161 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12272 (class 1259 OID 149205) --- Name: table_for_partition; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition ( - col1 bigint NOT NULL -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition OWNER TO postgres; - --- --- TOC entry 12273 (class 1259 OID 149208) --- Name: part1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part1 ( - col1 bigint NOT NULL -); -ALTER TABLE ONLY test_schema_diff.table_for_partition ATTACH PARTITION test_schema_diff.part1 FOR VALUES FROM ('1') TO ('23'); - - -ALTER TABLE test_schema_diff.part1 OWNER TO postgres; - --- --- TOC entry 12274 (class 1259 OID 149213) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO postgres; - --- --- TOC entry 12275 (class 1259 OID 149216) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('1') TO ('10'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO postgres; - --- --- TOC entry 12276 (class 1259 OID 149219) --- Name: part4; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part4 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part4 FOR VALUES FROM ('11') TO ('20'); - - -ALTER TABLE test_schema_diff.part4 OWNER TO postgres; - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'POSIX', LC_CTYPE = 'POSIX'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO postgres; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO pg_monitor WITH GRANT OPTION; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_enum_src TO pg_monitor WITH GRANT OPTION; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO pg_monitor; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO pg_monitor WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - --- Foreign Table scripts -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_src TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.1"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO postgres; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - --- Publication Script - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table - FOR TABLE test_schema_diff.table_for_publication - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table - RENAME TO with_one_table_alter; - -ALTER PUBLICATION with_one_table_alter SET - (publish = 'insert, update, truncate'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1 - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1 - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1 - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1 - RENAME TO subscription_test; - -DROP SUBSCRIPTION subscription_test; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F11_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F11_plus%2Ftarget.sql deleted file mode 100644 index 479bd9b90c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F11_plus%2Ftarget.sql +++ /dev/null @@ -1,1111 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO postgres; - --- --- TOC entry 12277 (class 1259 OID 149234) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO postgres; - --- --- TOC entry 12278 (class 1259 OID 149237) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('13') TO ('56'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO postgres; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO postgres; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO postgres; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: postgres --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO postgres; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO postgres; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO postgres; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO pg_monitor; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO postgres; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO postgres; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping; - --- Publication scripts - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE TABLE test_schema_diff.table_for_publication_in_target ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table_in_target - FOR TABLE test_schema_diff.table_for_publication_in_target - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table_in_target - RENAME TO with_one_table_in_target_alter; - -ALTER PUBLICATION with_one_table_in_target_alter SET - (publish = 'insert, update, truncate'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1_in_target" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1_in_target - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1_in_target - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1_in_target - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1_in_target - RENAME TO subscription_test_in_target; - -DROP SUBSCRIPTION subscription_test_in_target; - diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F12_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F12_plus%2Fsource.sql deleted file mode 100644 index 9f1c993feb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F12_plus%2Fsource.sql +++ /dev/null @@ -1,1166 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12272 (class 1259 OID 149205) --- Name: table_for_partition; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition ( - col1 bigint NOT NULL -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition OWNER TO postgres; - --- --- TOC entry 12273 (class 1259 OID 149208) --- Name: part1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part1 ( - col1 bigint NOT NULL -); -ALTER TABLE ONLY test_schema_diff.table_for_partition ATTACH PARTITION test_schema_diff.part1 FOR VALUES FROM ('1') TO ('23'); - - -ALTER TABLE test_schema_diff.part1 OWNER TO postgres; - --- --- TOC entry 12274 (class 1259 OID 149213) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO postgres; - --- --- TOC entry 12275 (class 1259 OID 149216) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('1') TO ('10'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO postgres; - --- --- TOC entry 12276 (class 1259 OID 149219) --- Name: part4; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part4 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part4 FOR VALUES FROM ('11') TO ('20'); - - -ALTER TABLE test_schema_diff.part4 OWNER TO postgres; - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- --- TOC entry 223 (class 1255 OID 67206) --- Name: dodaj_klijenta(character varying, character varying, character varying, character varying, integer, character varying, character varying, character varying, boolean, boolean, character varying, character varying, character varying, character varying, numeric, character varying); Type: PROCEDURE; Schema: public; Owner: postgres --- - -CREATE PROCEDURE test_schema_diff.dodaj_klijenta(v_naziv character varying, v_oib character varying, v_pdv_id character varying, v_adresa character varying, v_mjesto integer, v_drzava character varying, v_tip_p_sub character varying, v_vlasnik character varying, v_pdv boolean, v_fisk boolean, v_iban character varying, v_k_osoba character varying, v_email character varying, v_br_tel character varying, v_radna_god numeric, v_schema character varying) - LANGUAGE sql - AS $$select 1;$$; - - -ALTER PROCEDURE test_schema_diff.dodaj_klijenta(v_naziv character varying, v_oib character varying, v_pdv_id character varying, v_adresa character varying, v_mjesto integer, v_drzava character varying, v_tip_p_sub character varying, v_vlasnik character varying, v_pdv boolean, v_fisk boolean, v_iban character varying, v_k_osoba character varying, v_email character varying, v_br_tel character varying, v_radna_god numeric, v_schema character varying) OWNER TO postgres; - --- --- TOC entry 220 (class 1255 OID 67205) --- Name: proc1(bigint); Type: PROCEDURE; Schema: test_schema_diff; Owner: postgres --- - -CREATE PROCEDURE test_schema_diff.proc1(arg1 bigint) - LANGUAGE sql - AS $$select 1;$$; - - -ALTER PROCEDURE test_schema_diff.proc1(arg1 bigint) OWNER TO postgres; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'POSIX', LC_CTYPE = 'POSIX'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO postgres; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO pg_monitor WITH GRANT OPTION; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_enum_src TO pg_monitor WITH GRANT OPTION; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO pg_monitor; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO pg_monitor WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - --- Foreign Table scripts -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_src TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.1"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO postgres; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - --- Publication scripts - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE TABLE test_schema_diff.table_for_publication_in_target ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table_in_target - FOR TABLE test_schema_diff.table_for_publication_in_target - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table_in_target - RENAME TO with_one_table_in_target_alter; - -ALTER PUBLICATION with_one_table_in_target_alter SET - (publish = 'insert, update, truncate'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1 - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1 - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1 - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1 - RENAME TO subscription_test; - -DROP SUBSCRIPTION subscription_test; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F12_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F12_plus%2Ftarget.sql deleted file mode 100644 index 572cd0791d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F12_plus%2Ftarget.sql +++ /dev/null @@ -1,1097 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO postgres; - --- --- TOC entry 12277 (class 1259 OID 149234) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO postgres; - --- --- TOC entry 12278 (class 1259 OID 149237) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('13') TO ('56'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO postgres; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO postgres; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO postgres; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: postgres --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages - FROM pg_catalog.pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - - --- --- TOC entry 437 (class 1255 OID 112907) --- Name: dodaj_klijenta(character varying, character varying, character varying, character varying, integer, character varying, character varying, character varying, boolean, boolean, character varying, character varying, character varying, character varying, numeric, character varying); Type: PROCEDURE; Schema: test_schema_diff schema; Owner: postgres --- - -CREATE PROCEDURE test_schema_diff.dodaj_klijenta(v_naziv character varying, v_oib character varying, v_pdv_id character varying, v_adresa character varying, v_mjesto integer, v_drzava character varying, v_tip_p_sub character varying, v_vlasnik character varying, v_pdv boolean, v_fisk boolean, v_iban character varying, v_k_osoba character varying, v_email character varying, v_br_tel character varying, v_radna_god numeric, v_schema character varying) - LANGUAGE sql - AS $$select 4;$$; - - -ALTER PROCEDURE test_schema_diff.dodaj_klijenta(v_naziv character varying, v_oib character varying, v_pdv_id character varying, v_adresa character varying, v_mjesto integer, v_drzava character varying, v_tip_p_sub character varying, v_vlasnik character varying, v_pdv boolean, v_fisk boolean, v_iban character varying, v_k_osoba character varying, v_email character varying, v_br_tel character varying, v_radna_god numeric, v_schema character varying) OWNER TO postgres; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO postgres; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO postgres; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO postgres; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO pg_monitor; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO pg_monitor; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO postgres; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO postgres; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping; - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE TABLE test_schema_diff.table_for_publication_in_target ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table_in_target - FOR TABLE test_schema_diff.table_for_publication_in_target - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table_in_target - RENAME TO with_one_table_in_target_alter; - -ALTER PUBLICATION with_one_table_in_target_alter SET - (publish = 'insert, update, truncate'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1_in_target" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1_in_target - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1_in_target - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1_in_target - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1_in_target - RENAME TO subscription_test_in_target; - -DROP SUBSCRIPTION subscription_test_in_target; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F9.2_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F9.2_plus%2Fsource.sql deleted file mode 100644 index a2e085f1ab..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F9.2_plus%2Fsource.sql +++ /dev/null @@ -1,1049 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhaspkey, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'POSIX', LC_CTYPE = 'POSIX'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO postgres; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO postgres WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO postgres; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - --- Foreign Table scripts -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_src TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO postgres; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO postgres; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F9.2_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F9.2_plus%2Ftarget.sql deleted file mode 100644 index 7c2e88a1a5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fpg%2F9.2_plus%2Ftarget.sql +++ /dev/null @@ -1,1034 +0,0 @@ --- --- PostgreSQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: postgres --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO postgres; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO postgres; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO postgres; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO postgres; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO postgres; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO postgres; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO postgres; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO postgres; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO postgres; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO postgres; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: postgres --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO postgres; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: postgres --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: postgres --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: postgres --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: postgres --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhaspkey, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO postgres; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: postgres --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO postgres; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: postgres --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO postgres; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO postgres; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO postgres; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO postgres; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO postgres; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO postgres; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO postgres; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO postgres; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO postgres; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO postgres; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO postgres; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO postgres; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO postgres; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO postgres; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO postgres; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO postgres; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO postgres; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO postgres; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO postgres; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO postgres; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO postgres; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO postgres; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO postgres; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO postgres; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO postgres WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO postgres; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO postgres; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO postgres; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO postgres; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO postgres; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO postgres; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO postgres; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO postgres; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO postgres WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO postgres; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO postgres; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO postgres; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO postgres; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO postgres; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO postgres; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR postgres SERVER test_fs_for_user_mapping; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F10_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F10_plus%2Fsource.sql deleted file mode 100644 index dc541b16ad..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F10_plus%2Fsource.sql +++ /dev/null @@ -1,1320 +0,0 @@ --- --- enterprisedbQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: enterprisedb --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO enterprisedb; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12272 (class 1259 OID 149205) --- Name: table_for_partition; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_partition ( - col1 bigint NOT NULL -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition OWNER TO enterprisedb; - --- --- TOC entry 12273 (class 1259 OID 149208) --- Name: part1; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part1 ( - col1 bigint NOT NULL -); -ALTER TABLE ONLY test_schema_diff.table_for_partition ATTACH PARTITION test_schema_diff.part1 FOR VALUES FROM ('1') TO ('23'); - - -ALTER TABLE test_schema_diff.part1 OWNER TO enterprisedb; - --- --- TOC entry 12274 (class 1259 OID 149213) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO enterprisedb; - --- --- TOC entry 12275 (class 1259 OID 149216) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('1') TO ('10'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO enterprisedb; - --- --- TOC entry 12276 (class 1259 OID 149219) --- Name: part4; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part4 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part4 FOR VALUES FROM ('11') TO ('20'); - - -ALTER TABLE test_schema_diff.part4 OWNER TO enterprisedb; - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO enterprisedb; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO enterprisedb; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO enterprisedb; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO enterprisedb; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO enterprisedb; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO enterprisedb; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO enterprisedb; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO enterprisedb; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO enterprisedb; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO enterprisedb; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'POSIX', LC_CTYPE = 'POSIX'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO enterprisedb; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO enterprisedb; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO pg_monitor WITH GRANT OPTION; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO enterprisedb; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_enum_src TO pg_monitor WITH GRANT OPTION; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO enterprisedb WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO enterprisedb; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO enterprisedb; - --- Package script (test_schema_diff only) -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_src -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_src; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_src -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_src; - -COMMENT ON PACKAGE test_schema_diff.pkg_src - IS 'Target'; - --- Package script difference in header, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_header_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_header_diff; - -COMMENT ON PACKAGE test_schema_diff.pkg_header_diff - IS 'Header Diff'; - -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_header_diff TO PUBLIC; -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_header_diff TO enterprisedb WITH GRANT OPTION; - --- Package script difference in body, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_body_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - DBMS_OUTPUT.PUT_LINE('Before Insert '); - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - DBMS_OUTPUT.PUT_LINE('After Insert '); - END; -END pkg_body_diff; - --- Synonyms Scripts --- Prerequisite for synonyms -CREATE OR REPLACE FUNCTION test_schema_diff.fun_for_syn() -RETURNS void - LANGUAGE 'plpgsql' - VOLATILE - COST 100 - -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; -ALTER FUNCTION test_schema_diff.fun_for_syn() - OWNER TO enterprisedb; - -CREATE OR REPLACE PROCEDURE test_schema_diff.proc_for_syn() - SECURITY DEFINER VOLATILE - COST 100 -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_for_syn; -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS -BEGIN - RETURN ''; -END; -END pkg_for_syn; - -CREATE TABLE test_schema_diff.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE test_schema_diff.table_for_syn - OWNER to enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_for_syn - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 100 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_for_syn - OWNER TO enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_fun_src - FOR test_schema_diff.fun_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_pkg_src - FOR test_schema_diff.pkg_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_proc_src - FOR test_schema_diff.proc_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_seq_src - FOR test_schema_diff.seq_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_table_src - FOR test_schema_diff.table_for_syn; - -CREATE TABLE public.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE public.table_for_syn - OWNER to enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_diff - FOR public.table_for_syn; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO enterprisedb; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO enterprisedb; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO enterprisedb; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO enterprisedb; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_src TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO enterprisedb; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO enterprisedb; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.1"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO enterprisedb; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO enterprisedb WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO enterprisedb; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO enterprisedb; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO enterprisedb; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO enterprisedb; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO enterprisedb; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO enterprisedb; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO enterprisedb; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO enterprisedb; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR enterprisedb SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - --- Publication Script - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table - FOR TABLE test_schema_diff.table_for_publication - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table - RENAME TO with_one_table_alter; - -ALTER PUBLICATION with_one_table_alter SET - (publish = 'insert, update'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1 - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1 - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1 - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1 - RENAME TO subscription_test; - -DROP SUBSCRIPTION subscription_test; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F10_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F10_plus%2Ftarget.sql deleted file mode 100644 index 77a22c5bf4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F10_plus%2Ftarget.sql +++ /dev/null @@ -1,1261 +0,0 @@ --- --- enterprisedbQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: enterprisedb --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO enterprisedb; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO enterprisedb; - --- --- TOC entry 12277 (class 1259 OID 149234) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO enterprisedb; - --- --- TOC entry 12278 (class 1259 OID 149237) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('13') TO ('56'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO enterprisedb; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO enterprisedb; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO enterprisedb; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO enterprisedb; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO enterprisedb; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO enterprisedb; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO enterprisedb; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO enterprisedb; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO enterprisedb; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO enterprisedb; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: enterprisedb --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO enterprisedb; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO enterprisedb; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO enterprisedb; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO enterprisedb; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO enterprisedb; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO enterprisedb; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO enterprisedb; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO enterprisedb; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO enterprisedb; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO enterprisedb; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO enterprisedb; - --- Package script (test_schema_diff only) -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_tar -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_tar; - - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_tar -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_tar; - -COMMENT ON PACKAGE test_schema_diff.pkg_tar - IS 'test_schema_diff'; - --- Package script difference in header, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_header_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; -END pkg_header_diff; - --- Package script difference in body, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_body_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - DBMS_OUTPUT.PUT_LINE('Before Insert '); - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - DBMS_OUTPUT.PUT_LINE('After Insert '); - END; -END pkg_body_diff; - -COMMENT ON PACKAGE test_schema_diff.pkg_body_diff - IS 'Header Diff'; - -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_body_diff TO PUBLIC; -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_body_diff TO enterprisedb WITH GRANT OPTION; - --- Synonyms Scripts --- Prerequisite for synonyms -CREATE OR REPLACE FUNCTION test_schema_diff.fun_for_syn() -RETURNS void - LANGUAGE 'plpgsql' - VOLATILE - COST 100 - -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; -ALTER FUNCTION test_schema_diff.fun_for_syn() - OWNER TO enterprisedb; - -CREATE OR REPLACE PROCEDURE test_schema_diff.proc_for_syn() - SECURITY DEFINER VOLATILE - COST 100 -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_for_syn; -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS -BEGIN - RETURN ''; -END; -END pkg_for_syn; - -CREATE TABLE test_schema_diff.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE test_schema_diff.table_for_syn - OWNER to enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_for_syn - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 100 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_for_syn - OWNER TO enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_fun_src - FOR test_schema_diff.fun_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_pkg_src - FOR test_schema_diff.pkg_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_proc_src - FOR test_schema_diff.proc_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_seq_src - FOR test_schema_diff.seq_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_table_src - FOR test_schema_diff.table_for_syn; - -CREATE OR REPLACE PROCEDURE public.proc_for_syn() - SECURITY DEFINER VOLATILE - COST 100 -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_diff - FOR public.proc_for_syn; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO enterprisedb; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO enterprisedb; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO enterprisedb; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO enterprisedb; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO enterprisedb; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO enterprisedb; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO enterprisedb; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO enterprisedb WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO enterprisedb; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO enterprisedb; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO enterprisedb; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO enterprisedb; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO enterprisedb; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO enterprisedb; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO enterprisedb; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR enterprisedb SERVER test_fs_for_user_mapping; - --- Publication script - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE TABLE test_schema_diff.table_for_publication_in_target ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table_in_target - FOR TABLE test_schema_diff.table_for_publication_in_target - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table_in_target - RENAME TO with_one_table_in_target_alter; - -ALTER PUBLICATION with_one_table_in_target_alter SET - (publish = 'insert, update'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1_in_target" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1_in_target - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1_in_target - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1_in_target - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1_in_target - RENAME TO subscription_test_in_target; - -DROP SUBSCRIPTION subscription_test_in_target; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F11_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F11_plus%2Fsource.sql deleted file mode 100644 index d05f1dce22..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F11_plus%2Fsource.sql +++ /dev/null @@ -1,1319 +0,0 @@ --- --- enterprisedbQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: enterprisedb --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO enterprisedb; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12272 (class 1259 OID 149205) --- Name: table_for_partition; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_partition ( - col1 bigint NOT NULL -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition OWNER TO enterprisedb; - --- --- TOC entry 12273 (class 1259 OID 149208) --- Name: part1; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part1 ( - col1 bigint NOT NULL -); -ALTER TABLE ONLY test_schema_diff.table_for_partition ATTACH PARTITION test_schema_diff.part1 FOR VALUES FROM ('1') TO ('23'); - - -ALTER TABLE test_schema_diff.part1 OWNER TO enterprisedb; - --- --- TOC entry 12274 (class 1259 OID 149213) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO enterprisedb; - --- --- TOC entry 12275 (class 1259 OID 149216) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('1') TO ('10'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO enterprisedb; - --- --- TOC entry 12276 (class 1259 OID 149219) --- Name: part4; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part4 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part4 FOR VALUES FROM ('11') TO ('20'); - - -ALTER TABLE test_schema_diff.part4 OWNER TO enterprisedb; - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO enterprisedb; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO enterprisedb; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO enterprisedb; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO enterprisedb; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO enterprisedb; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO enterprisedb; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO enterprisedb; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_catalog.pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO enterprisedb; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO enterprisedb; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO enterprisedb; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'POSIX', LC_CTYPE = 'POSIX'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO enterprisedb; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO enterprisedb; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO pg_monitor WITH GRANT OPTION; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO enterprisedb; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_enum_src TO pg_monitor WITH GRANT OPTION; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO enterprisedb WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO enterprisedb; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO enterprisedb; - --- Package script (test_schema_diff only) -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_src -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_src; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_src -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_src; - -COMMENT ON PACKAGE test_schema_diff.pkg_src - IS 'Target'; - --- Package script difference in header, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_header_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_header_diff; - -COMMENT ON PACKAGE test_schema_diff.pkg_header_diff - IS 'Header Diff'; - -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_header_diff TO PUBLIC; -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_header_diff TO enterprisedb WITH GRANT OPTION; - --- Package script difference in body, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_body_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - DBMS_OUTPUT.PUT_LINE('Before Insert '); - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - DBMS_OUTPUT.PUT_LINE('After Insert '); - END; -END pkg_body_diff; - --- Synonyms Scripts --- Prerequisite for synonyms -CREATE OR REPLACE FUNCTION test_schema_diff.fun_for_syn() -RETURNS void - LANGUAGE 'plpgsql' - VOLATILE - COST 100 - -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; -ALTER FUNCTION test_schema_diff.fun_for_syn() - OWNER TO enterprisedb; - -CREATE OR REPLACE PROCEDURE test_schema_diff.proc_for_syn() - SECURITY DEFINER VOLATILE - COST 100 -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_for_syn; -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS -BEGIN - RETURN ''; -END; -END pkg_for_syn; - -CREATE TABLE test_schema_diff.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE test_schema_diff.table_for_syn - OWNER to enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_for_syn - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 100 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_for_syn - OWNER TO enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_fun_src - FOR test_schema_diff.fun_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_pkg_src - FOR test_schema_diff.pkg_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_proc_src - FOR test_schema_diff.proc_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_seq_src - FOR test_schema_diff.seq_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_table_src - FOR test_schema_diff.table_for_syn; - -CREATE TABLE public.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE public.table_for_syn - OWNER to enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_diff - FOR public.table_for_syn; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO enterprisedb; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO enterprisedb; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO enterprisedb; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO enterprisedb; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_src TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO enterprisedb; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO enterprisedb; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.1"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO enterprisedb; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO enterprisedb WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO enterprisedb; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO enterprisedb; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO enterprisedb; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO enterprisedb; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO enterprisedb; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO enterprisedb; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO enterprisedb; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO enterprisedb; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR enterprisedb SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - --- Publication Script - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table - FOR TABLE test_schema_diff.table_for_publication - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table - RENAME TO with_one_table_alter; - -ALTER PUBLICATION with_one_table_alter SET - (publish = 'insert, update, truncate'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1 - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1 - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1 - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1 - RENAME TO subscription_test; - -DROP SUBSCRIPTION subscription_test; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F11_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F11_plus%2Ftarget.sql deleted file mode 100644 index 137eeb603f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F11_plus%2Ftarget.sql +++ /dev/null @@ -1,1261 +0,0 @@ --- --- enterprisedbQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET idle_in_transaction_session_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; -SET row_security = off; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: enterprisedb --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO enterprisedb; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO enterprisedb; - --- --- TOC entry 12277 (class 1259 OID 149234) --- Name: table_for_partition_1; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_partition_1 ( - col1 bigint -) -PARTITION BY RANGE (col1); - - -ALTER TABLE test_schema_diff.table_for_partition_1 OWNER TO enterprisedb; - --- --- TOC entry 12278 (class 1259 OID 149237) --- Name: part3; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.part3 ( - col1 bigint -); -ALTER TABLE ONLY test_schema_diff.table_for_partition_1 ATTACH PARTITION test_schema_diff.part3 FOR VALUES FROM ('13') TO ('56'); - - -ALTER TABLE test_schema_diff.part3 OWNER TO enterprisedb; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO enterprisedb; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO enterprisedb; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO enterprisedb; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO enterprisedb; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO enterprisedb; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO enterprisedb; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO enterprisedb; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO enterprisedb; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO enterprisedb; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: enterprisedb --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relispartition, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions, - pg_class.relpartbound - FROM pg_catalog.pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO enterprisedb; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO enterprisedb; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."POSIX"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO enterprisedb; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO enterprisedb; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO enterprisedb; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO enterprisedb; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO enterprisedb; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO enterprisedb; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO enterprisedb; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO enterprisedb; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO enterprisedb; - --- Package script (test_schema_diff only) -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_tar -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_tar; - - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_tar -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_tar; - -COMMENT ON PACKAGE test_schema_diff.pkg_tar - IS 'test_schema_diff'; - --- Package script difference in header, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_header_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; -END pkg_header_diff; - --- Package script difference in body, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_body_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - DBMS_OUTPUT.PUT_LINE('Before Insert '); - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - DBMS_OUTPUT.PUT_LINE('After Insert '); - END; -END pkg_body_diff; - -COMMENT ON PACKAGE test_schema_diff.pkg_body_diff - IS 'Header Diff'; - -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_body_diff TO PUBLIC; -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_body_diff TO enterprisedb WITH GRANT OPTION; - --- Synonyms Scripts --- Prerequisite for synonyms -CREATE OR REPLACE FUNCTION test_schema_diff.fun_for_syn() -RETURNS void - LANGUAGE 'plpgsql' - VOLATILE - COST 100 - -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; -ALTER FUNCTION test_schema_diff.fun_for_syn() - OWNER TO enterprisedb; - -CREATE OR REPLACE PROCEDURE test_schema_diff.proc_for_syn() - SECURITY DEFINER VOLATILE - COST 100 -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_for_syn; -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS -BEGIN - RETURN ''; -END; -END pkg_for_syn; - -CREATE TABLE test_schema_diff.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE test_schema_diff.table_for_syn - OWNER to enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_for_syn - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 100 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_for_syn - OWNER TO enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_fun_src - FOR test_schema_diff.fun_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_pkg_src - FOR test_schema_diff.pkg_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_proc_src - FOR test_schema_diff.proc_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_seq_src - FOR test_schema_diff.seq_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_table_src - FOR test_schema_diff.table_for_syn; - -CREATE OR REPLACE PROCEDURE public.proc_for_syn() - SECURITY DEFINER VOLATILE - COST 100 -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_diff - FOR public.proc_for_syn; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO enterprisedb; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO enterprisedb; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO enterprisedb; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO enterprisedb; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO enterprisedb; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO enterprisedb; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO enterprisedb; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO enterprisedb WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO enterprisedb; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO enterprisedb; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO enterprisedb; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO enterprisedb; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO enterprisedb; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO enterprisedb; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO enterprisedb; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR enterprisedb SERVER test_fs_for_user_mapping; - --- Publication script - -CREATE TABLE test_schema_diff.table_for_publication ( - col1 integer NOT NULL, - col2 text -); - -CREATE TABLE test_schema_diff.table_for_publication_in_target ( - col1 integer NOT NULL, - col2 text -); - -CREATE PUBLICATION for_all_table - FOR ALL TABLES - WITH (publish = 'insert, delete'); - -CREATE PUBLICATION with_one_table_in_target - FOR TABLE test_schema_diff.table_for_publication_in_target - WITH (publish = 'insert, delete'); - -ALTER PUBLICATION with_one_table_in_target - RENAME TO with_one_table_in_target_alter; - -ALTER PUBLICATION with_one_table_in_target_alter SET - (publish = 'insert, update, truncate'); - --- Subscription script - -CREATE SUBSCRIPTION "subscription_test1_in_target" - CONNECTION 'host=localhost port=5432 user=postgres dbname=edb password=samplepassword' - PUBLICATION sample_publication - WITH (connect = false, enabled = false, create_slot = false, slot_name = None, synchronous_commit = 'off'); - -ALTER SUBSCRIPTION subscription_test1_in_target - CONNECTION 'host=localhost port=5432 user=postgres dbname=postgres'; - -ALTER SUBSCRIPTION subscription_test1_in_target - SET (synchronous_commit = 'remote_apply'); - -ALTER SUBSCRIPTION subscription_test1_in_target - SET PUBLICATION edb WITH (refresh = false); - -ALTER SUBSCRIPTION subscription_test1_in_target - RENAME TO subscription_test_in_target; - -DROP SUBSCRIPTION subscription_test_in_target; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F9.2_plus%2Fsource.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F9.2_plus%2Fsource.sql deleted file mode 100644 index 61cb49e78c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F9.2_plus%2Fsource.sql +++ /dev/null @@ -1,1207 +0,0 @@ --- --- enterprisedbQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:54:15 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; - --- --- TOC entry 17 (class 2615 OID 139770) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: enterprisedb --- - -CREATE SCHEMA test_schema_diff; - - -ALTER SCHEMA test_schema_diff OWNER TO enterprisedb; - -SET default_tablespace = ''; - - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - - --- --- TOC entry 12258 (class 1259 OID 148963) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint NOT NULL, - col2 text, - col3 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO enterprisedb; - --- --- TOC entry 12256 (class 1259 OID 148895) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO enterprisedb; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12256 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 12262 (class 1259 OID 149004) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb; --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO enterprisedb; - --- --- TOC entry 12260 (class 1259 OID 148977) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO enterprisedb; - --- --- TOC entry 12269 (class 1259 OID 149128) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO enterprisedb; - --- --- TOC entry 12264 (class 1259 OID 149024) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO enterprisedb; - --- --- TOC entry 12266 (class 1259 OID 149048) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO enterprisedb; - --- --- TOC entry 56893 (class 2606 OID 148904) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='12') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 56893 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56891 (class 2606 OID 148911) --- Name: table_for_constraints check_con; Type: CHECK CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE test_schema_diff.table_for_constraints - ADD CONSTRAINT check_con CHECK ((col1 > 10)) NOT VALID; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56891 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 56899 (class 2606 OID 148970) --- Name: table_for_column table_for_column_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_column - ADD CONSTRAINT table_for_column_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56895 (class 2606 OID 148902) --- Name: table_for_constraints table_for_constraints_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT table_for_constraints_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 148984) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56913 (class 2606 OID 149135) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1, col2); - - --- --- TOC entry 56909 (class 2606 OID 149031) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56907 (class 2606 OID 149011) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb; --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56911 (class 2606 OID 149055) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148913) --- Name: table_for_constraints unique; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "unique" UNIQUE (col1); - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 56897 --- Name: CONSTRAINT "unique" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "unique" ON test_schema_diff.table_for_constraints IS 'cmnt'; - - --- --- TOC entry 56900 (class 1259 OID 149023) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 varchar_pattern_ops); - - --- --- TOC entry 56905 (class 1259 OID 149012) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb; --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56901 (class 1259 OID 149211) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56902 (class 1259 OID 149022) --- Name: index_source; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_source ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 61044 (class 2618 OID 149032) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61070 (class 0 OID 0) --- Dependencies: 61044 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61045 (class 2618 OID 149033) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule2 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - --- --- TOC entry 12283 (class 1259 OID 347818) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhaspkey, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO enterprisedb; - --- --- TOC entry 12286 (class 1259 OID 347832) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='false') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO enterprisedb; - --- --- TOC entry 61111 (class 0 OID 0) --- Dependencies: 12286 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_src - FROM pg_catalog."default"; - -ALTER COLLATION test_schema_diff.coll_src - OWNER TO enterprisedb; - -COMMENT ON COLLATION test_schema_diff.coll_src - IS 'Test Comment'; - -CREATE COLLATION test_schema_diff.coll_diff - FROM pg_catalog."default"; - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO enterprisedb; - -COMMENT ON COLLATION test_schema_diff.coll_diff - IS 'Test Comment'; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src OWNER TO enterprisedb; - -COMMENT ON TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_src - IS 'Test Comment'; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH german_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH dutch_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_src - IS 'Test Comment'; - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'english' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Test Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_src ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_src - IS 'Test Comment'; - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Test Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_src IS 'Test Comment'; - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Test Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_src - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_src OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_src - ADD CONSTRAINT con_src CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 50); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_src_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS character varying(40) - COLLATE pg_catalog."POSIX"; - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE::text <> 'pgAdmin3'::text); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE::text <> 'pgAdmin4'::text); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Test comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_src AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 numeric(5,2), - m3 character varying(30) COLLATE pg_catalog."C" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_comp_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_comp_diff TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO enterprisedb; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_src AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_enum_diff - IS 'Test Comment'; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_src AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_range_col_diff - IS 'Test Comment'; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO PUBLIC; -GRANT USAGE ON TYPE test_schema_diff.typ_range_col_diff TO enterprisedb WITH GRANT OPTION; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bpchar, - COLLATION = pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO enterprisedb; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_src; -ALTER TYPE test_schema_diff.typ_shell_src - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO enterprisedb; -COMMENT ON TYPE test_schema_diff.typ_shell_diff - IS 'Test Comment'; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO enterprisedb; - --- Package script (test_schema_diff only) -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_src -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_src; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_src -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_src; - -COMMENT ON PACKAGE test_schema_diff.pkg_src - IS 'Target'; - --- Package script difference in header, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_header_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_header_diff; - -COMMENT ON PACKAGE test_schema_diff.pkg_header_diff - IS 'Header Diff'; - -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_header_diff TO PUBLIC; -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_header_diff TO enterprisedb WITH GRANT OPTION; - --- Package script difference in body, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_body_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - DBMS_OUTPUT.PUT_LINE('Before Insert '); - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - DBMS_OUTPUT.PUT_LINE('After Insert '); - END; -END pkg_body_diff; - --- Synonyms Scripts --- Prerequisite for synonyms -CREATE OR REPLACE FUNCTION test_schema_diff.fun_for_syn() -RETURNS void - LANGUAGE 'plpgsql' - VOLATILE - COST 100 - -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; -ALTER FUNCTION test_schema_diff.fun_for_syn() - OWNER TO enterprisedb; - -CREATE OR REPLACE PROCEDURE test_schema_diff.proc_for_syn() -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_for_syn; -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS -BEGIN - RETURN ''; -END; -END pkg_for_syn; - -CREATE TABLE test_schema_diff.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE test_schema_diff.table_for_syn - OWNER to enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_for_syn - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 100 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_for_syn - OWNER TO enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_fun_src - FOR test_schema_diff.fun_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_pkg_src - FOR test_schema_diff.pkg_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_proc_src - FOR test_schema_diff.proc_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_seq_src - FOR test_schema_diff.seq_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_table_src - FOR test_schema_diff.table_for_syn; - -CREATE TABLE public.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE public.table_for_syn - OWNER to enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_diff - FOR public.table_for_syn; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_src - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_src - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_src - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_src TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff - CYCLE - INCREMENT 3 - START 3 - MINVALUE 3 - MAXVALUE 100 - CACHE 2; -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO enterprisedb; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO enterprisedb; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO enterprisedb; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO enterprisedb; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_src( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_src - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_src - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_src - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_src TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_src TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default", - fcity character varying(40) NULL COLLATE pg_catalog."POSIX" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Test Comment'; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO enterprisedb; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 1000)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_src CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val20', opt_src 'val_src'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (opt1 'val1'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs1 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - payment_pin integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Casts script -CREATE CAST (money AS bigint) - WITHOUT FUNCTION - AS IMPLICIT; - -COMMENT ON CAST (money AS bigint) IS 'money -> bigint'; - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_src ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_src - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_src - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON SQL_DROP - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - ENABLE REPLICA; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - ENABLE ALWAYS; -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO enterprisedb; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE src_trusted_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_trusted_language - OWNER TO enterprisedb; -COMMENT ON LANGUAGE src_trusted_language - IS 'Custom Trusted Language'; -GRANT USAGE ON LANGUAGE src_trusted_language TO PUBLIC; -GRANT USAGE ON LANGUAGE src_trusted_language TO enterprisedb WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE src_proc_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE src_proc_language - OWNER TO enterprisedb; -COMMENT ON LANGUAGE src_proc_language - IS 'Custom Procedural Language'; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE prsd_end - VALIDATOR pg_stat_reset_single_table_counters; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_src - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_src - OWNER TO enterprisedb; -COMMENT ON FOREIGN DATA WRAPPER fdw_src - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'false'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO enterprisedb; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO enterprisedb; - -CREATE SERVER fs_src - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_src - OWNER TO enterprisedb; -COMMENT ON SERVER fs_src - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_add TO enterprisedb WITH GRANT OPTION; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_add - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '192.168.1.1', port '8080'); -ALTER SERVER fs_diff_options_modify - OWNER TO enterprisedb; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO enterprisedb; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO enterprisedb; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping; - -CREATE USER MAPPING FOR enterprisedb SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F9.2_plus%2Ftarget.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F9.2_plus%2Ftarget.sql deleted file mode 100644 index a8120d8a59..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgadmin4/postgres%2Fpgadmin4%2Fmaster%2Fweb%2Fpgadmin%2Ftools%2Fschema_diff%2Ftests%2Fppas%2F9.2_plus%2Ftarget.sql +++ /dev/null @@ -1,1182 +0,0 @@ --- --- enterprisedbQL database dump --- - --- Dumped from database version 10.7 --- Dumped by pg_dump version 12beta2 - --- Started on 2019-11-01 12:55:22 IST - -SET statement_timeout = 0; -SET lock_timeout = 0; -SET client_encoding = 'UTF8'; -SET standard_conforming_strings = on; -SELECT pg_catalog.set_config('search_path', '', false); -SET check_function_bodies = false; -SET xmloption = content; -SET client_min_messages = warning; - --- --- TOC entry 18 (class 2615 OID 139771) --- Name: test_schema_diff; Type: SCHEMA; Schema: -; Owner: enterprisedb --- - -CREATE SCHEMA test_schema_diff; - -ALTER SCHEMA test_schema_diff OWNER TO enterprisedb; - -SET default_tablespace = ''; - -CREATE EXTENSION btree_gist - SCHEMA test_schema_diff; - --- --- TOC entry 12250 (class 1259 OID 139938) --- Name: MView; Type: MATERIALIZED VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE MATERIALIZED VIEW test_schema_diff."MView" AS - SELECT 'tekst'::text AS text - WITH NO DATA; - - -ALTER TABLE test_schema_diff."MView" OWNER TO enterprisedb; - --- --- TOC entry 12259 (class 1259 OID 148971) --- Name: table_for_column; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_column ( - col1 bigint, - col2 bigint, - col4 text -); - - -ALTER TABLE test_schema_diff.table_for_column OWNER TO enterprisedb; - --- --- TOC entry 12268 (class 1259 OID 149089) --- Name: table_for_constraints; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_constraints ( - col1 integer NOT NULL, - col2 text, - CONSTRAINT check_con CHECK ((col1 > 30)) -); - - -ALTER TABLE test_schema_diff.table_for_constraints OWNER TO enterprisedb; - --- --- TOC entry 61066 (class 0 OID 0) --- Dependencies: 12268 --- Name: TABLE table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON TABLE test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 61067 (class 0 OID 0) --- Dependencies: 12268 --- Name: CONSTRAINT check_con ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT check_con ON test_schema_diff.table_for_constraints IS 'coment'; - - --- --- TOC entry 12257 (class 1259 OID 148960) --- Name: table_for_del; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_del ( -); - - -ALTER TABLE test_schema_diff.table_for_del OWNER TO enterprisedb; - --- --- TOC entry 12271 (class 1259 OID 149172) --- Name: table_for_foreign_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_foreign_key ( - col1 integer NOT NULL, - col2 "char", - col3 bigint -); - - -ALTER TABLE test_schema_diff.table_for_foreign_key OWNER TO enterprisedb; - --- --- TOC entry 12263 (class 1259 OID 149013) --- Name: table_for_identical; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_identical ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_identical OWNER TO enterprisedb; - --- --- TOC entry 12261 (class 1259 OID 148986) --- Name: table_for_index; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_index ( - col1 integer NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_index OWNER TO enterprisedb; - --- --- TOC entry 12270 (class 1259 OID 149144) --- Name: table_for_primary_key; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_primary_key ( - col1 integer NOT NULL, - col2 text NOT NULL -); - - -ALTER TABLE test_schema_diff.table_for_primary_key OWNER TO enterprisedb; - --- --- TOC entry 12265 (class 1259 OID 149034) --- Name: table_for_rule; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_rule ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_rule OWNER TO enterprisedb; - --- --- TOC entry 12267 (class 1259 OID 149066) --- Name: table_for_trigger; Type: TABLE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE TABLE test_schema_diff.table_for_trigger ( - col1 bigint NOT NULL, - col2 text -); - - -ALTER TABLE test_schema_diff.table_for_trigger OWNER TO enterprisedb; - - --- --- TOC entry 56906 (class 2606 OID 149097) --- Name: table_for_constraints Exclusion; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_constraints - ADD CONSTRAINT "Exclusion" EXCLUDE USING gist (col2 WITH <>) WITH (fillfactor='15') WHERE ((col1 > 1)) DEFERRABLE INITIALLY DEFERRED; - - --- --- TOC entry 61068 (class 0 OID 0) --- Dependencies: 56906 --- Name: CONSTRAINT "Exclusion" ON table_for_constraints; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON CONSTRAINT "Exclusion" ON test_schema_diff.table_for_constraints IS 'comments'; - - --- --- TOC entry 56910 (class 2606 OID 149176) --- Name: table_for_foreign_key table_for_foreign_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_foreign_key - ADD CONSTRAINT table_for_foreign_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56897 (class 2606 OID 148993) --- Name: table_for_index table_for_index_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_index - ADD CONSTRAINT table_for_index_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56908 (class 2606 OID 149151) --- Name: table_for_primary_key table_for_primary_key_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_primary_key - ADD CONSTRAINT table_for_primary_key_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56902 (class 2606 OID 149041) --- Name: table_for_rule table_for_rule_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_rule - ADD CONSTRAINT table_for_rule_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56900 (class 2606 OID 149020) --- Name: table_for_identical table_for_table_for_identical_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_identical - ADD CONSTRAINT table_for_table_for_identical_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56904 (class 2606 OID 149073) --- Name: table_for_trigger table_for_trigger_pkey; Type: CONSTRAINT; Schema: test_schema_diff; Owner: enterprisedb --- - -ALTER TABLE ONLY test_schema_diff.table_for_trigger - ADD CONSTRAINT table_for_trigger_pkey PRIMARY KEY (col1); - - --- --- TOC entry 56893 (class 1259 OID 148994) --- Name: index1; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index1 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56894 (class 1259 OID 148995) --- Name: index2; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index2 ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56898 (class 1259 OID 149021) --- Name: index_identical; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_identical ON test_schema_diff.table_for_identical USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56895 (class 1259 OID 149212) --- Name: index_same; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX index_same ON test_schema_diff.table_for_index USING btree (col2 text_pattern_ops); - - --- --- TOC entry 56892 (class 1259 OID 139945) --- Name: mview_index; Type: INDEX; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE INDEX mview_index ON test_schema_diff."MView" USING btree (text text_pattern_ops); - - --- --- TOC entry 61045 (class 2618 OID 149042) --- Name: table_for_rule rule1; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule1 AS - ON UPDATE TO test_schema_diff.table_for_rule DO INSTEAD NOTHING; - - --- --- TOC entry 61069 (class 0 OID 0) --- Dependencies: 61045 --- Name: RULE rule1 ON table_for_rule; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON RULE rule1 ON test_schema_diff.table_for_rule IS 'comments'; - - --- --- TOC entry 61046 (class 2618 OID 149043) --- Name: table_for_rule rule2; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule2 AS - ON UPDATE TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61047 (class 2618 OID 149044) --- Name: table_for_rule rule3; Type: RULE; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE RULE rule3 AS - ON INSERT TO test_schema_diff.table_for_rule DO NOTHING; - - --- --- TOC entry 61050 (class 0 OID 139938) --- Dependencies: 12250 61062 --- Name: MView; Type: MATERIALIZED VIEW DATA; Schema: test_schema_diff; Owner: enterprisedb --- - -REFRESH MATERIALIZED VIEW test_schema_diff."MView"; - - --- --- TOC entry 12284 (class 1259 OID 347823) --- Name: test view; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view" AS - SELECT pg_class.relname, - pg_class.relnamespace, - pg_class.reltype, - pg_class.reloftype, - pg_class.relowner, - pg_class.relam, - pg_class.relfilenode, - pg_class.reltablespace, - pg_class.relpages, - pg_class.reltuples, - pg_class.relallvisible, - pg_class.reltoastrelid, - pg_class.relhasindex, - pg_class.relisshared, - pg_class.relpersistence, - pg_class.relkind, - pg_class.relnatts, - pg_class.relchecks, - pg_class.relhasoids, - pg_class.relhaspkey, - pg_class.relhasrules, - pg_class.relhastriggers, - pg_class.relhassubclass, - pg_class.relrowsecurity, - pg_class.relforcerowsecurity, - pg_class.relispopulated, - pg_class.relreplident, - pg_class.relfrozenxid, - pg_class.relminmxid, - pg_class.relacl, - pg_class.reloptions - FROM pg_class - LIMIT 10; - - -ALTER TABLE test_schema_diff."test view" OWNER TO enterprisedb; - --- --- TOC entry 12285 (class 1259 OID 347828) --- Name: test view f; Type: VIEW; Schema: test_schema_diff; Owner: enterprisedb --- - -CREATE VIEW test_schema_diff."test view f" WITH (security_barrier='true') AS - SELECT 2; - - -ALTER TABLE test_schema_diff."test view f" OWNER TO enterprisedb; - --- --- TOC entry 61105 (class 0 OID 0) --- Dependencies: 12285 --- Name: VIEW "test view f"; Type: COMMENT; Schema: test_schema_diff; Owner: enterprisedb --- - -COMMENT ON VIEW test_schema_diff."test view f" IS 'cmn'; - --- Collation scripts -CREATE COLLATION test_schema_diff.coll_tar - FROM pg_catalog."default"; - -ALTER COLLATION test_schema_diff.coll_tar - OWNER TO enterprisedb; - -CREATE COLLATION test_schema_diff.coll_diff - (LC_COLLATE = 'C', LC_CTYPE = 'C'); - -ALTER COLLATION test_schema_diff.coll_diff - OWNER TO enterprisedb; - --- FTS Configuration scripts -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar ( - COPY=german -); - -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_tar OWNER TO enterprisedb; - -CREATE TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ( - PARSER = default -); -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR asciiword WITH dutch_stem; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR email WITH simple; -ALTER TEXT SEARCH CONFIGURATION test_schema_diff.fts_con_diff ADD MAPPING FOR hword WITH german_stem; - --- FTS Dictionary scripts -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_tar ( - TEMPLATE = simple, - stopwords = 'english' -); - -CREATE TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff ( - TEMPLATE = simple, - stopwords = 'german' -); - -COMMENT ON TEXT SEARCH DICTIONARY test_schema_diff.fts_dict_diff - IS 'Comment'; - --- FTS Parser scripts -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_tar ( - START = prsd_start, - GETTOKEN = prsd_nexttoken, - END = prsd_end, - LEXTYPES = prsd_lextype); - -CREATE TEXT SEARCH PARSER test_schema_diff.fts_par_diff ( - START = int4_accum, - GETTOKEN = inet_gist_penalty, - END = btint2sortsupport, - LEXTYPES = dispell_init); - -COMMENT ON TEXT SEARCH PARSER test_schema_diff.fts_par_diff - IS 'Comment'; - --- FTS Template scripts -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_tar ( - INIT = dispell_init, - LEXIZE = dispell_lexize -); - -CREATE TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff ( - INIT = dsimple_init, - LEXIZE = dsimple_lexize -); - -COMMENT ON TEXT SEARCH TEMPLATE test_schema_diff.fts_templ_diff IS 'Comment'; - --- Domain and Domain Constraint script -CREATE DOMAIN test_schema_diff.dom_tar - AS bigint - DEFAULT 100 - NOT NULL; - -ALTER DOMAIN test_schema_diff.dom_tar OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_tar - ADD CONSTRAINT con_tar CHECK (VALUE <> 100); - -CREATE DOMAIN test_schema_diff.dom_cons_diff - AS bigint - DEFAULT 400; - -ALTER DOMAIN test_schema_diff.dom_cons_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_diff_1 CHECK (VALUE <> 40); - -ALTER DOMAIN test_schema_diff.dom_cons_diff - ADD CONSTRAINT cons_tar_only CHECK (VALUE <> 25); - -CREATE DOMAIN test_schema_diff.dom_type_diff - AS numeric(8,4); - -ALTER DOMAIN test_schema_diff.dom_type_diff OWNER TO enterprisedb; - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons1 CHECK (VALUE <> 45::numeric); - -ALTER DOMAIN test_schema_diff.dom_type_diff - ADD CONSTRAINT cons2 CHECK (VALUE <> 50::numeric); - -COMMENT ON DOMAIN test_schema_diff.dom_type_diff - IS 'Comment'; - --- Type Script composite type -CREATE TYPE test_schema_diff.typ_comp_tar AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_tar - OWNER TO enterprisedb; -CREATE TYPE test_schema_diff.typ_comp_diff AS -( - m1 bit(5), - m2 text COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_diff_no_column AS -( - a "char", - b "char" -); -ALTER TYPE test_schema_diff.typ_comp_diff_no_column - OWNER TO enterprisedb; - --- Type Script ENUM type -CREATE TYPE test_schema_diff.typ_enum_tar AS ENUM - ('test_enum'); -ALTER TYPE test_schema_diff.typ_enum_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_enum_diff - OWNER TO enterprisedb; - --- Type Script RANGE type -CREATE TYPE test_schema_diff.typ_range_tar AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_col_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."POSIX", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_range_col_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_subtype_diff AS RANGE -( - SUBTYPE=bool, - SUBTYPE_OPCLASS = bool_ops -); -ALTER TYPE test_schema_diff.typ_range_subtype_diff - OWNER TO enterprisedb; - --- Type Script SHELL type -CREATE TYPE test_schema_diff.typ_shell_tar; -ALTER TYPE test_schema_diff.typ_shell_tar - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_shell_diff; -ALTER TYPE test_schema_diff.typ_shell_diff - OWNER TO enterprisedb; - --- Type script to test when Type is different -CREATE TYPE test_schema_diff.typ_comp_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_comp_range_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_comp_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_comp_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_range_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_range_enum_diff AS ENUM - ('test_enum', 'test_enum_1'); -ALTER TYPE test_schema_diff.typ_range_enum_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_comp_diff AS -( - m1 bigint, - m2 text[] COLLATE pg_catalog."POSIX" -); -ALTER TYPE test_schema_diff.typ_enum_comp_diff - OWNER TO enterprisedb; - -CREATE TYPE test_schema_diff.typ_enum_range_diff AS RANGE -( - SUBTYPE=text, - COLLATION = pg_catalog."C", - SUBTYPE_OPCLASS = text_ops -); -ALTER TYPE test_schema_diff.typ_enum_range_diff - OWNER TO enterprisedb; - --- Package script (test_schema_diff only) -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_tar -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_tar; - - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_tar -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; - - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - END; -END pkg_tar; - -COMMENT ON PACKAGE test_schema_diff.pkg_tar - IS 'test_schema_diff'; - --- Package script difference in header, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_header_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_header_diff -IS - FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS - v_dname VARCHAR2(14); - BEGIN - SELECT dname INTO v_dname FROM dept WHERE deptno = p_deptno; - RETURN v_dname; - EXCEPTION - WHEN NO_DATA_FOUND THEN - DBMS_OUTPUT.PUT_LINE('Invalid department number ' || p_deptno); - RETURN ''; - END; -END pkg_header_diff; - --- Package script difference in body, acl and comment -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric); -END pkg_body_diff; - -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_body_diff -IS - PROCEDURE hire_emp(p_empno numeric, p_ename character varying, p_job character varying, p_sal numeric, p_hiredate timestamp without time zone, p_comm numeric, p_mgr numeric, p_deptno numeric) IS - BEGIN - DBMS_OUTPUT.PUT_LINE('Before Insert '); - INSERT INTO emp(empno, ename, job, sal, hiredate, comm, mgr, deptno) - VALUES(p_empno, p_ename, p_job, p_sal, - p_hiredate, p_comm, p_mgr, p_deptno); - DBMS_OUTPUT.PUT_LINE('After Insert '); - END; -END pkg_body_diff; - -COMMENT ON PACKAGE test_schema_diff.pkg_body_diff - IS 'Header Diff'; - -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_body_diff TO PUBLIC; -GRANT EXECUTE ON PACKAGE test_schema_diff.pkg_body_diff TO enterprisedb WITH GRANT OPTION; - --- Synonyms Scripts --- Prerequisite for synonyms -CREATE OR REPLACE FUNCTION test_schema_diff.fun_for_syn() -RETURNS void - LANGUAGE 'plpgsql' - VOLATILE - COST 100 - -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; -ALTER FUNCTION test_schema_diff.fun_for_syn() - OWNER TO enterprisedb; - -CREATE OR REPLACE PROCEDURE test_schema_diff.proc_for_syn() -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE PACKAGE test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying; -END pkg_for_syn; -CREATE OR REPLACE PACKAGE BODY test_schema_diff.pkg_for_syn -IS -FUNCTION get_dept_name(p_deptno numeric) RETURN character varying IS -BEGIN - RETURN ''; -END; -END pkg_for_syn; - -CREATE TABLE test_schema_diff.table_for_syn -( - id bigint, - name text COLLATE pg_catalog."default" -) -TABLESPACE pg_default; -ALTER TABLE test_schema_diff.table_for_syn - OWNER to enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_for_syn - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 100 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_for_syn - OWNER TO enterprisedb; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_fun_src - FOR test_schema_diff.fun_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_pkg_src - FOR test_schema_diff.pkg_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_proc_src - FOR test_schema_diff.proc_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_seq_src - FOR test_schema_diff.seq_for_syn; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_table_src - FOR test_schema_diff.table_for_syn; - -CREATE OR REPLACE PROCEDURE public.proc_for_syn() -AS $BODY$BEGIN -SELECT 1; -END;$BODY$; - -CREATE OR REPLACE SYNONYM test_schema_diff.syn_diff - FOR public.proc_for_syn; - --- Sequences Script -CREATE SEQUENCE test_schema_diff.seq_tar - CYCLE - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 3 - CACHE 6; -ALTER SEQUENCE test_schema_diff.seq_tar - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - INCREMENT 1 - START 1 - MINVALUE 1 - MAXVALUE 9223372036854775807 - CACHE 1; -ALTER SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - OWNER TO enterprisedb; -COMMENT ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove - IS 'Test Comment'; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO PUBLIC; -GRANT ALL ON SEQUENCE test_schema_diff.seq_diff_comment_acl_remove TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_diff - INCREMENT 5 - START 3 - MINVALUE 3 - MAXVALUE 80 - CACHE 1; - -ALTER SEQUENCE test_schema_diff.seq_diff - OWNER TO enterprisedb; - -CREATE SEQUENCE test_schema_diff.seq_start_diff - INCREMENT 5 - START 1 - MINVALUE 1 - MAXVALUE 20; -ALTER SEQUENCE test_schema_diff.seq_start_diff - OWNER TO enterprisedb; - --- Foreign Data Wrapper to test foreign table -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_table - OWNER TO enterprisedb; - --- Foreign Server to test foreign table -CREATE SERVER test_fs_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs_for_foreign_table - OWNER TO enterprisedb; -CREATE SERVER test_fs2_for_foreign_table - FOREIGN DATA WRAPPER test_fdw_for_foreign_table; -ALTER SERVER test_fs2_for_foreign_table - OWNER TO enterprisedb; - --- Table to test inheritance in foreign table -CREATE TABLE public.test_table_for_foreign_table -( - tid bigint NOT NULL, - tname text COLLATE pg_catalog."default", - CONSTRAINT test_table_for_foreign_table_pkey PRIMARY KEY (tid) -) -WITH ( - OIDS = FALSE -) -TABLESPACE pg_default; -ALTER TABLE public.test_table_for_foreign_table - OWNER to enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_tar( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_tar - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_tar - IS 'Test Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_tar TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_tar TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_col( - fid bigint NULL, - fname text NOT NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_col - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -COMMENT ON FOREIGN TABLE test_schema_diff.ft_diff_col - IS 'Comment'; -GRANT INSERT ON TABLE test_schema_diff.ft_diff_col TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_col TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_const( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - OWNER TO enterprisedb; - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck CHECK ((fid > 1000)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck1 CHECK ((fid > 50)) NO INHERIT NOT VALID; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck2 CHECK ((fid > 20)) NO INHERIT; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_const - ADD CONSTRAINT fcheck_tar CHECK ((fid > 50)); - -GRANT INSERT ON TABLE test_schema_diff.ft_diff_const TO PUBLIC; -GRANT ALL ON TABLE test_schema_diff.ft_diff_const TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_opt( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs_for_foreign_table - OPTIONS (debug 'true', opt2 'val30', opt_tar 'val_tar'); - -ALTER FOREIGN TABLE test_schema_diff.ft_diff_opt - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server( - fid bigint NULL, - fname text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server - OWNER TO enterprisedb; - -CREATE FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1( - fid bigint NULL, - fcity text NULL COLLATE pg_catalog."default" -) - SERVER test_fs2_for_foreign_table - OPTIONS (opt1 'val1', opt2 'val2'); -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - OWNER TO enterprisedb; -ALTER FOREIGN TABLE test_schema_diff.ft_diff_foreign_server_1 - ADD CONSTRAINT cs2 CHECK ((fid > 200)) NO INHERIT; - --- Test for RM #5350 -CREATE TABLE test_schema_diff.events_transactions -( - event_code integer, - numerator integer, - account_token text COLLATE pg_catalog."default", - transaction_dt timestamp without time zone, - payment_method integer, - approval text COLLATE pg_catalog."default", - amount integer, - file_dt timestamp without time zone DEFAULT CURRENT_TIMESTAMP, - file_name character varying(256) COLLATE pg_catalog."default", - payment_pin integer, - transfer_dt timestamp without time zone, - transaction_type integer -); - --- Event Trigger script -CREATE FUNCTION public.evt_tri_fun() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun() - OWNER TO enterprisedb; - -CREATE FUNCTION public.evt_tri_fun2() - RETURNS event_trigger - LANGUAGE 'plpgsql' - NOT LEAKPROOF -AS $BODY$ -BEGIN -PERFORM 1; -END; -$BODY$; -ALTER FUNCTION public.evt_tri_fun2() - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_tar ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -COMMENT ON EVENT TRIGGER evt_tri_tar - IS 'Event Trigger Source'; -ALTER EVENT TRIGGER evt_tri_tar - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event1 ON DDL_COMMAND_END - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_event3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_event3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status1 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status1 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status2 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - DISABLE; -ALTER EVENT TRIGGER evt_tri_diff_enable_status2 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_enable_status3 ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun(); -ALTER EVENT TRIGGER evt_tri_diff_enable_status3 - OWNER TO enterprisedb; - -CREATE EVENT TRIGGER evt_tri_diff_func ON DDL_COMMAND_START - EXECUTE PROCEDURE public.evt_tri_fun2(); -ALTER EVENT TRIGGER evt_tri_diff_func - OWNER TO enterprisedb; - --- Extension script -CREATE EXTENSION adminpack - SCHEMA pg_catalog - VERSION "1.0"; - --- Language script -CREATE TRUSTED PROCEDURAL LANGUAGE tar_language - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE tar_language - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE tar_language TO PUBLIC; -GRANT USAGE ON LANGUAGE tar_language TO enterprisedb WITH GRANT OPTION; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_add - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_add - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_acl_revoke - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON LANGUAGE lan_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE PROCEDURAL LANGUAGE lan_diff_type - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - -CREATE TRUSTED PROCEDURAL LANGUAGE lan_diff_inline_validator - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; -ALTER LANGUAGE lan_diff_type - OWNER TO enterprisedb; - --- Foreign Data Wrapper Script -CREATE FOREIGN DATA WRAPPER fdw_tar - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_tar - OWNER TO enterprisedb; -COMMENT ON FOREIGN DATA WRAPPER fdw_tar - IS 'Foreign Data Wrapper'; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_add - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_add - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_acl_revoke - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN DATA WRAPPER fdw_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_validator - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_validator - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_add_options; -ALTER FOREIGN DATA WRAPPER fdw_diff_add_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_remove_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_remove_options - OWNER TO enterprisedb; - -CREATE FOREIGN DATA WRAPPER fdw_diff_options - OPTIONS (debug 'true'); -ALTER FOREIGN DATA WRAPPER fdw_diff_options - OWNER TO enterprisedb; - --- Foreign Server Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_foreign_server - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OWNER TO enterprisedb; - -CREATE SERVER fs_tar - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_tar - OWNER TO enterprisedb; -COMMENT ON SERVER fs_tar - IS 'Foreign Server'; - -CREATE SERVER fs_diff_acl_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_acl_revoke - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_acl_revoke - OWNER TO enterprisedb; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO PUBLIC; -GRANT USAGE ON FOREIGN SERVER fs_diff_acl_revoke TO enterprisedb WITH GRANT OPTION; - -CREATE SERVER fs_diff_type_version_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_remove - TYPE 'PG' - VERSION '10' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_type_version_modify - TYPE 'EPAS' - VERSION '11' - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_type_version_modify - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_add - FOREIGN DATA WRAPPER test_fdw_for_foreign_server; -ALTER SERVER fs_diff_options_add - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_remove - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_remove - OWNER TO enterprisedb; - -CREATE SERVER fs_diff_options_modify - FOREIGN DATA WRAPPER test_fdw_for_foreign_server - OPTIONS (host '127.0.0.1', port '5432'); -ALTER SERVER fs_diff_options_modify - OWNER TO enterprisedb; - --- User Mapping Script -CREATE FOREIGN DATA WRAPPER test_fdw_for_user_mapping - VALIDATOR pg_catalog.postgresql_fdw_validator; -ALTER FOREIGN DATA WRAPPER test_fdw_for_user_mapping - OWNER TO enterprisedb; - -CREATE SERVER test_fs_for_user_mapping - FOREIGN DATA WRAPPER test_fdw_for_user_mapping; -ALTER SERVER test_fs_for_user_mapping - OWNER TO enterprisedb; - -CREATE USER MAPPING FOR public SERVER test_fs_for_user_mapping - OPTIONS (password 'admin123'); - -CREATE USER MAPPING FOR enterprisedb SERVER test_fs_for_user_mapping; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/LICENSE b/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/LICENSE deleted file mode 100644 index 7e27977d37..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -pgAgent - -Copyright (C) 2002 - 2021, The pgAdmin Development Team - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose, without fee, and without a written agreement is -hereby granted, provided that the above copyright notice and this paragraph and -the following two paragraphs appear in all copies. - -IN NO EVENT SHALL THE PGADMIN DEVELOPMENT TEAM BE LIABLE TO ANY PARTY FOR -DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST -PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF -THE PGADMIN DEVELOPMENT TEAM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -THE PGADMIN DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, -BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND -THE PGADMIN DEVELOPMENT TEAM HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, -UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--3.4--4.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--3.4--4.2.sql deleted file mode 100644 index 5e11b52e49..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--3.4--4.2.sql +++ /dev/null @@ -1,395 +0,0 @@ -/* -// pgAgent - PostgreSQL Tools -// -// Copyright (C) 2002 - 2021, The pgAdmin Development Team -// This software is released under the PostgreSQL Licence -// -// pgagent--3.4--4.2.sql - Upgrade the pgAgent schema to 4.2 -// -*/ - -\echo Use "ALTER EXTENSION pgagent UPDATE" to load this file. \quit - -CREATE OR REPLACE FUNCTION pgagent.pgagent_schema_version() RETURNS int2 AS ' -BEGIN - -- RETURNS PGAGENT MAJOR VERSION - -- WE WILL CHANGE THE MAJOR VERSION, ONLY IF THERE IS A SCHEMA CHANGE - RETURN 4; -END; -' LANGUAGE 'plpgsql' VOLATILE; - -CREATE OR REPLACE FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) RETURNS timestamptz AS ' -DECLARE - jscid ALIAS FOR $1; - jscstart ALIAS FOR $2; - jscend ALIAS FOR $3; - jscminutes ALIAS FOR $4; - jschours ALIAS FOR $5; - jscweekdays ALIAS FOR $6; - jscmonthdays ALIAS FOR $7; - jscmonths ALIAS FOR $8; - - nextrun timestamp := ''1970-01-01 00:00:00-00''; - runafter timestamp := ''1970-01-01 00:00:00-00''; - - bingo bool := FALSE; - gotit bool := FALSE; - foundval bool := FALSE; - daytweak bool := FALSE; - minutetweak bool := FALSE; - - i int2 := 0; - d int2 := 0; - - nextminute int2 := 0; - nexthour int2 := 0; - nextday int2 := 0; - nextmonth int2 := 0; - nextyear int2 := 0; - - -BEGIN - -- No valid start date has been specified - IF jscstart IS NULL THEN RETURN NULL; END IF; - - -- The schedule is past its end date - IF jscend IS NOT NULL AND jscend < now() THEN RETURN NULL; END IF; - - -- Get the time to find the next run after. It will just be the later of - -- now() + 1m and the start date for the time being, however, we might want to - -- do more complex things using this value in the future. - IF date_trunc(''MINUTE'', jscstart) > date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)) THEN - runafter := date_trunc(''MINUTE'', jscstart); - ELSE - runafter := date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)); - END IF; - - -- - -- Enter a loop, generating next run timestamps until we find one - -- that falls on the required weekday, and is not matched by an exception - -- - - WHILE bingo = FALSE LOOP - - -- - -- Get the next run year - -- - nextyear := date_part(''YEAR'', runafter); - - -- - -- Get the next run month - -- - nextmonth := date_part(''MONTH'', runafter); - gotit := FALSE; - FOR i IN (nextmonth) .. 12 LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextmonth - 1) LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - - -- Wrap into next year - nextyear := nextyear + 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - - -- - -- Get the next run day - -- - -- If the year, or month have incremented, get the lowest day, - -- otherwise look for the next day matching or after today. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter)) THEN - nextday := 1; - FOR i IN 1 .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextday := date_part(''DAY'', runafter); - gotit := FALSE; - FOR i IN nextday .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextday - 1) LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - - -- Wrap into next month - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Was the last day flag selected? - IF nextday = 32 THEN - IF nextmonth = 1 THEN - nextday := 31; - ELSIF nextmonth = 2 THEN - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - nextday := 29; - ELSE - nextday := 28; - END IF; - ELSIF nextmonth = 3 THEN - nextday := 31; - ELSIF nextmonth = 4 THEN - nextday := 30; - ELSIF nextmonth = 5 THEN - nextday := 31; - ELSIF nextmonth = 6 THEN - nextday := 30; - ELSIF nextmonth = 7 THEN - nextday := 31; - ELSIF nextmonth = 8 THEN - nextday := 31; - ELSIF nextmonth = 9 THEN - nextday := 30; - ELSIF nextmonth = 10 THEN - nextday := 31; - ELSIF nextmonth = 11 THEN - nextday := 30; - ELSIF nextmonth = 12 THEN - nextday := 31; - END IF; - END IF; - - -- - -- Get the next run hour - -- - -- If the year, month or day have incremented, get the lowest hour, - -- otherwise look for the next hour matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR daytweak = TRUE) THEN - nexthour := 0; - FOR i IN 1 .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nexthour := date_part(''HOUR'', runafter); - gotit := FALSE; - FOR i IN (nexthour + 1) .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nexthour LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - - -- Wrap into next month - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- - -- Get the next run minute - -- - -- If the year, month day or hour have incremented, get the lowest minute, - -- otherwise look for the next minute matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR nexthour > date_part(''HOUR'', runafter) OR daytweak = TRUE) THEN - nextminute := 0; - IF minutetweak = TRUE THEN - d := 1; - ELSE - d := date_part(''MINUTE'', runafter)::int2; - END IF; - FOR i IN d .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextminute := date_part(''MINUTE'', runafter); - gotit := FALSE; - FOR i IN (nextminute + 1) .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nextminute LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - - -- Wrap into next hour - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nexthour = 23 THEN - nexthour = 0; - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - ELSE - nexthour := nexthour + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Build the result, and check it is not the same as runafter - this may - -- happen if all array entries are set to false. In this case, add a minute. - - nextrun := (nextyear::varchar || ''-''::varchar || nextmonth::varchar || ''-'' || nextday::varchar || '' '' || nexthour::varchar || '':'' || nextminute::varchar)::timestamptz; - - IF nextrun = runafter AND foundval = FALSE THEN - nextrun := nextrun + INTERVAL ''1 Minute''; - END IF; - - -- If the result is past the end date, exit. - IF nextrun > jscend THEN - RETURN NULL; - END IF; - - -- Check to ensure that the nextrun time is actually still valid. Its - -- possible that wrapped values may have carried the nextrun onto an - -- invalid time or date. - IF ((jscminutes = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscminutes[date_part(''MINUTE'', nextrun) + 1] = TRUE) AND - (jschours = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jschours[date_part(''HOUR'', nextrun) + 1] = TRUE) AND - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonthdays[date_part(''DAY'', nextrun)] = TRUE OR - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,t}'' AND - ((date_part(''MONTH'', nextrun) IN (1,3,5,7,8,10,12) AND date_part(''DAY'', nextrun) = 31) OR - (date_part(''MONTH'', nextrun) IN (4,6,9,11) AND date_part(''DAY'', nextrun) = 30) OR - (date_part(''MONTH'', nextrun) = 2 AND ((pgagent.pga_is_leap_year(date_part(''YEAR'', nextrun)::int2) AND date_part(''DAY'', nextrun) = 29) OR date_part(''DAY'', nextrun) = 28))))) AND - (jscmonths = ''{f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonths[date_part(''MONTH'', nextrun)] = TRUE)) THEN - - - -- Now, check to see if the nextrun time found is a) on an acceptable - -- weekday, and b) not matched by an exception. If not, set - -- runafter = nextrun and try again. - - -- Check for a wildcard weekday - gotit := FALSE; - FOR i IN 1 .. 7 LOOP - IF jscweekdays[i] = TRUE THEN - gotit := TRUE; - EXIT; - END IF; - END LOOP; - - -- OK, is the correct weekday selected, or a wildcard? - IF (jscweekdays[date_part(''DOW'', nextrun) + 1] = TRUE OR gotit = FALSE) THEN - - -- Check for exceptions - SELECT INTO d jexid FROM pgagent.pga_exception WHERE jexscid = jscid AND ((jexdate = nextrun::date AND jextime = nextrun::time) OR (jexdate = nextrun::date AND jextime IS NULL) OR (jexdate IS NULL AND jextime = nextrun::time)); - IF FOUND THEN - -- Nuts - found an exception. Increment the time and try again - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - ELSE - bingo := TRUE; - END IF; - ELSE - -- We''re on the wrong week day - increment a day and try again. - runafter := nextrun + INTERVAL ''1 Day''; - bingo := FALSE; - minutetweak := FALSE; - daytweak := TRUE; - END IF; - - ELSE - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - END IF; - - END LOOP; - - RETURN nextrun; -END; -' LANGUAGE 'plpgsql' VOLATILE; - -COMMENT ON FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) IS 'Calculates the next runtime for a given schedule'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--4.0--4.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--4.0--4.2.sql deleted file mode 100644 index 5b805597b2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--4.0--4.2.sql +++ /dev/null @@ -1,387 +0,0 @@ -/* -// pgAgent - PostgreSQL Tools -// -// Copyright (C) 2002 - 2021, The pgAdmin Development Team -// This software is released under the PostgreSQL Licence -// -// pgagent--4.0--4.2.sql - Upgrade the pgAgent schema to 4.2 -// -*/ - -\echo Use "ALTER EXTENSION pgagent UPDATE" to load this file. \quit - -CREATE OR REPLACE FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) RETURNS timestamptz AS ' -DECLARE - jscid ALIAS FOR $1; - jscstart ALIAS FOR $2; - jscend ALIAS FOR $3; - jscminutes ALIAS FOR $4; - jschours ALIAS FOR $5; - jscweekdays ALIAS FOR $6; - jscmonthdays ALIAS FOR $7; - jscmonths ALIAS FOR $8; - - nextrun timestamp := ''1970-01-01 00:00:00-00''; - runafter timestamp := ''1970-01-01 00:00:00-00''; - - bingo bool := FALSE; - gotit bool := FALSE; - foundval bool := FALSE; - daytweak bool := FALSE; - minutetweak bool := FALSE; - - i int2 := 0; - d int2 := 0; - - nextminute int2 := 0; - nexthour int2 := 0; - nextday int2 := 0; - nextmonth int2 := 0; - nextyear int2 := 0; - - -BEGIN - -- No valid start date has been specified - IF jscstart IS NULL THEN RETURN NULL; END IF; - - -- The schedule is past its end date - IF jscend IS NOT NULL AND jscend < now() THEN RETURN NULL; END IF; - - -- Get the time to find the next run after. It will just be the later of - -- now() + 1m and the start date for the time being, however, we might want to - -- do more complex things using this value in the future. - IF date_trunc(''MINUTE'', jscstart) > date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)) THEN - runafter := date_trunc(''MINUTE'', jscstart); - ELSE - runafter := date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)); - END IF; - - -- - -- Enter a loop, generating next run timestamps until we find one - -- that falls on the required weekday, and is not matched by an exception - -- - - WHILE bingo = FALSE LOOP - - -- - -- Get the next run year - -- - nextyear := date_part(''YEAR'', runafter); - - -- - -- Get the next run month - -- - nextmonth := date_part(''MONTH'', runafter); - gotit := FALSE; - FOR i IN (nextmonth) .. 12 LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextmonth - 1) LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - - -- Wrap into next year - nextyear := nextyear + 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - - -- - -- Get the next run day - -- - -- If the year, or month have incremented, get the lowest day, - -- otherwise look for the next day matching or after today. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter)) THEN - nextday := 1; - FOR i IN 1 .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextday := date_part(''DAY'', runafter); - gotit := FALSE; - FOR i IN nextday .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextday - 1) LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - - -- Wrap into next month - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Was the last day flag selected? - IF nextday = 32 THEN - IF nextmonth = 1 THEN - nextday := 31; - ELSIF nextmonth = 2 THEN - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - nextday := 29; - ELSE - nextday := 28; - END IF; - ELSIF nextmonth = 3 THEN - nextday := 31; - ELSIF nextmonth = 4 THEN - nextday := 30; - ELSIF nextmonth = 5 THEN - nextday := 31; - ELSIF nextmonth = 6 THEN - nextday := 30; - ELSIF nextmonth = 7 THEN - nextday := 31; - ELSIF nextmonth = 8 THEN - nextday := 31; - ELSIF nextmonth = 9 THEN - nextday := 30; - ELSIF nextmonth = 10 THEN - nextday := 31; - ELSIF nextmonth = 11 THEN - nextday := 30; - ELSIF nextmonth = 12 THEN - nextday := 31; - END IF; - END IF; - - -- - -- Get the next run hour - -- - -- If the year, month or day have incremented, get the lowest hour, - -- otherwise look for the next hour matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR daytweak = TRUE) THEN - nexthour := 0; - FOR i IN 1 .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nexthour := date_part(''HOUR'', runafter); - gotit := FALSE; - FOR i IN (nexthour + 1) .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nexthour LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - - -- Wrap into next month - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- - -- Get the next run minute - -- - -- If the year, month day or hour have incremented, get the lowest minute, - -- otherwise look for the next minute matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR nexthour > date_part(''HOUR'', runafter) OR daytweak = TRUE) THEN - nextminute := 0; - IF minutetweak = TRUE THEN - d := 1; - ELSE - d := date_part(''MINUTE'', runafter)::int2; - END IF; - FOR i IN d .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextminute := date_part(''MINUTE'', runafter); - gotit := FALSE; - FOR i IN (nextminute + 1) .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nextminute LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - - -- Wrap into next hour - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nexthour = 23 THEN - nexthour = 0; - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - ELSE - nexthour := nexthour + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Build the result, and check it is not the same as runafter - this may - -- happen if all array entries are set to false. In this case, add a minute. - - nextrun := (nextyear::varchar || ''-''::varchar || nextmonth::varchar || ''-'' || nextday::varchar || '' '' || nexthour::varchar || '':'' || nextminute::varchar)::timestamptz; - - IF nextrun = runafter AND foundval = FALSE THEN - nextrun := nextrun + INTERVAL ''1 Minute''; - END IF; - - -- If the result is past the end date, exit. - IF nextrun > jscend THEN - RETURN NULL; - END IF; - - -- Check to ensure that the nextrun time is actually still valid. Its - -- possible that wrapped values may have carried the nextrun onto an - -- invalid time or date. - IF ((jscminutes = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscminutes[date_part(''MINUTE'', nextrun) + 1] = TRUE) AND - (jschours = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jschours[date_part(''HOUR'', nextrun) + 1] = TRUE) AND - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonthdays[date_part(''DAY'', nextrun)] = TRUE OR - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,t}'' AND - ((date_part(''MONTH'', nextrun) IN (1,3,5,7,8,10,12) AND date_part(''DAY'', nextrun) = 31) OR - (date_part(''MONTH'', nextrun) IN (4,6,9,11) AND date_part(''DAY'', nextrun) = 30) OR - (date_part(''MONTH'', nextrun) = 2 AND ((pgagent.pga_is_leap_year(date_part(''YEAR'', nextrun)::int2) AND date_part(''DAY'', nextrun) = 29) OR date_part(''DAY'', nextrun) = 28))))) AND - (jscmonths = ''{f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonths[date_part(''MONTH'', nextrun)] = TRUE)) THEN - - - -- Now, check to see if the nextrun time found is a) on an acceptable - -- weekday, and b) not matched by an exception. If not, set - -- runafter = nextrun and try again. - - -- Check for a wildcard weekday - gotit := FALSE; - FOR i IN 1 .. 7 LOOP - IF jscweekdays[i] = TRUE THEN - gotit := TRUE; - EXIT; - END IF; - END LOOP; - - -- OK, is the correct weekday selected, or a wildcard? - IF (jscweekdays[date_part(''DOW'', nextrun) + 1] = TRUE OR gotit = FALSE) THEN - - -- Check for exceptions - SELECT INTO d jexid FROM pgagent.pga_exception WHERE jexscid = jscid AND ((jexdate = nextrun::date AND jextime = nextrun::time) OR (jexdate = nextrun::date AND jextime IS NULL) OR (jexdate IS NULL AND jextime = nextrun::time)); - IF FOUND THEN - -- Nuts - found an exception. Increment the time and try again - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - ELSE - bingo := TRUE; - END IF; - ELSE - -- We''re on the wrong week day - increment a day and try again. - runafter := nextrun + INTERVAL ''1 Day''; - bingo := FALSE; - minutetweak := FALSE; - daytweak := TRUE; - END IF; - - ELSE - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - END IF; - - END LOOP; - - RETURN nextrun; -END; -' LANGUAGE 'plpgsql' VOLATILE; - -COMMENT ON FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) IS 'Calculates the next runtime for a given schedule'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--4.1--4.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--4.1--4.2.sql deleted file mode 100644 index e177b98017..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--4.1--4.2.sql +++ /dev/null @@ -1,387 +0,0 @@ -/* -// pgAgent - PostgreSQL Tools -// -// Copyright (C) 2002 - 2021, The pgAdmin Development Team -// This software is released under the PostgreSQL Licence -// -// pgagent--4.1--4.2.sql - Upgrade the pgAgent schema to 4.2 -// -*/ - -\echo Use "ALTER EXTENSION pgagent UPDATE" to load this file. \quit - -CREATE OR REPLACE FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) RETURNS timestamptz AS ' -DECLARE - jscid ALIAS FOR $1; - jscstart ALIAS FOR $2; - jscend ALIAS FOR $3; - jscminutes ALIAS FOR $4; - jschours ALIAS FOR $5; - jscweekdays ALIAS FOR $6; - jscmonthdays ALIAS FOR $7; - jscmonths ALIAS FOR $8; - - nextrun timestamp := ''1970-01-01 00:00:00-00''; - runafter timestamp := ''1970-01-01 00:00:00-00''; - - bingo bool := FALSE; - gotit bool := FALSE; - foundval bool := FALSE; - daytweak bool := FALSE; - minutetweak bool := FALSE; - - i int2 := 0; - d int2 := 0; - - nextminute int2 := 0; - nexthour int2 := 0; - nextday int2 := 0; - nextmonth int2 := 0; - nextyear int2 := 0; - - -BEGIN - -- No valid start date has been specified - IF jscstart IS NULL THEN RETURN NULL; END IF; - - -- The schedule is past its end date - IF jscend IS NOT NULL AND jscend < now() THEN RETURN NULL; END IF; - - -- Get the time to find the next run after. It will just be the later of - -- now() + 1m and the start date for the time being, however, we might want to - -- do more complex things using this value in the future. - IF date_trunc(''MINUTE'', jscstart) > date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)) THEN - runafter := date_trunc(''MINUTE'', jscstart); - ELSE - runafter := date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)); - END IF; - - -- - -- Enter a loop, generating next run timestamps until we find one - -- that falls on the required weekday, and is not matched by an exception - -- - - WHILE bingo = FALSE LOOP - - -- - -- Get the next run year - -- - nextyear := date_part(''YEAR'', runafter); - - -- - -- Get the next run month - -- - nextmonth := date_part(''MONTH'', runafter); - gotit := FALSE; - FOR i IN (nextmonth) .. 12 LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextmonth - 1) LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - - -- Wrap into next year - nextyear := nextyear + 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - - -- - -- Get the next run day - -- - -- If the year, or month have incremented, get the lowest day, - -- otherwise look for the next day matching or after today. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter)) THEN - nextday := 1; - FOR i IN 1 .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextday := date_part(''DAY'', runafter); - gotit := FALSE; - FOR i IN nextday .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextday - 1) LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - - -- Wrap into next month - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Was the last day flag selected? - IF nextday = 32 THEN - IF nextmonth = 1 THEN - nextday := 31; - ELSIF nextmonth = 2 THEN - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - nextday := 29; - ELSE - nextday := 28; - END IF; - ELSIF nextmonth = 3 THEN - nextday := 31; - ELSIF nextmonth = 4 THEN - nextday := 30; - ELSIF nextmonth = 5 THEN - nextday := 31; - ELSIF nextmonth = 6 THEN - nextday := 30; - ELSIF nextmonth = 7 THEN - nextday := 31; - ELSIF nextmonth = 8 THEN - nextday := 31; - ELSIF nextmonth = 9 THEN - nextday := 30; - ELSIF nextmonth = 10 THEN - nextday := 31; - ELSIF nextmonth = 11 THEN - nextday := 30; - ELSIF nextmonth = 12 THEN - nextday := 31; - END IF; - END IF; - - -- - -- Get the next run hour - -- - -- If the year, month or day have incremented, get the lowest hour, - -- otherwise look for the next hour matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR daytweak = TRUE) THEN - nexthour := 0; - FOR i IN 1 .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nexthour := date_part(''HOUR'', runafter); - gotit := FALSE; - FOR i IN (nexthour + 1) .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nexthour LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - - -- Wrap into next month - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- - -- Get the next run minute - -- - -- If the year, month day or hour have incremented, get the lowest minute, - -- otherwise look for the next minute matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR nexthour > date_part(''HOUR'', runafter) OR daytweak = TRUE) THEN - nextminute := 0; - IF minutetweak = TRUE THEN - d := 1; - ELSE - d := date_part(''MINUTE'', runafter)::int2; - END IF; - FOR i IN d .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextminute := date_part(''MINUTE'', runafter); - gotit := FALSE; - FOR i IN (nextminute + 1) .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nextminute LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - - -- Wrap into next hour - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nexthour = 23 THEN - nexthour = 0; - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - ELSE - nexthour := nexthour + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Build the result, and check it is not the same as runafter - this may - -- happen if all array entries are set to false. In this case, add a minute. - - nextrun := (nextyear::varchar || ''-''::varchar || nextmonth::varchar || ''-'' || nextday::varchar || '' '' || nexthour::varchar || '':'' || nextminute::varchar)::timestamptz; - - IF nextrun = runafter AND foundval = FALSE THEN - nextrun := nextrun + INTERVAL ''1 Minute''; - END IF; - - -- If the result is past the end date, exit. - IF nextrun > jscend THEN - RETURN NULL; - END IF; - - -- Check to ensure that the nextrun time is actually still valid. Its - -- possible that wrapped values may have carried the nextrun onto an - -- invalid time or date. - IF ((jscminutes = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscminutes[date_part(''MINUTE'', nextrun) + 1] = TRUE) AND - (jschours = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jschours[date_part(''HOUR'', nextrun) + 1] = TRUE) AND - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonthdays[date_part(''DAY'', nextrun)] = TRUE OR - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,t}'' AND - ((date_part(''MONTH'', nextrun) IN (1,3,5,7,8,10,12) AND date_part(''DAY'', nextrun) = 31) OR - (date_part(''MONTH'', nextrun) IN (4,6,9,11) AND date_part(''DAY'', nextrun) = 30) OR - (date_part(''MONTH'', nextrun) = 2 AND ((pgagent.pga_is_leap_year(date_part(''YEAR'', nextrun)::int2) AND date_part(''DAY'', nextrun) = 29) OR date_part(''DAY'', nextrun) = 28))))) AND - (jscmonths = ''{f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonths[date_part(''MONTH'', nextrun)] = TRUE)) THEN - - - -- Now, check to see if the nextrun time found is a) on an acceptable - -- weekday, and b) not matched by an exception. If not, set - -- runafter = nextrun and try again. - - -- Check for a wildcard weekday - gotit := FALSE; - FOR i IN 1 .. 7 LOOP - IF jscweekdays[i] = TRUE THEN - gotit := TRUE; - EXIT; - END IF; - END LOOP; - - -- OK, is the correct weekday selected, or a wildcard? - IF (jscweekdays[date_part(''DOW'', nextrun) + 1] = TRUE OR gotit = FALSE) THEN - - -- Check for exceptions - SELECT INTO d jexid FROM pgagent.pga_exception WHERE jexscid = jscid AND ((jexdate = nextrun::date AND jextime = nextrun::time) OR (jexdate = nextrun::date AND jextime IS NULL) OR (jexdate IS NULL AND jextime = nextrun::time)); - IF FOUND THEN - -- Nuts - found an exception. Increment the time and try again - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - ELSE - bingo := TRUE; - END IF; - ELSE - -- We''re on the wrong week day - increment a day and try again. - runafter := nextrun + INTERVAL ''1 Day''; - bingo := FALSE; - minutetweak := FALSE; - daytweak := TRUE; - END IF; - - ELSE - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - END IF; - - END LOOP; - - RETURN nextrun; -END; -' LANGUAGE 'plpgsql' VOLATILE; - -COMMENT ON FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) IS 'Calculates the next runtime for a given schedule'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--unpackaged--4.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--unpackaged--4.2.sql deleted file mode 100644 index 2c83a79b79..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent--unpackaged--4.2.sql +++ /dev/null @@ -1,428 +0,0 @@ -/* -// pgAgent - PostgreSQL Tools -// -// Copyright (C) 2002 - 2021, The pgAdmin Development Team -// This software is released under the PostgreSQL Licence -// -// pgagent--unpackaged--4.2.sql - Convert pgAgent existing tables and functions to an extension -// -*/ - -\echo Use "CREATE EXTENSION pgagent FROM unpackaged" to load this file. \quit - -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_jobagent; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_jobclass; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_job; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_jobstep; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_schedule; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_exception; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_joblog; -ALTER EXTENSION pgagent ADD TABLE pgagent.pga_jobsteplog; - -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_exception_jexid_seq; -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_job_jobid_seq; -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_jobclass_jclid_seq; -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_joblog_jlgid_seq; -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_jobstep_jstid_seq; -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_jobsteplog_jslid_seq; -ALTER EXTENSION pgagent ADD SEQUENCE pgagent.pga_schedule_jscid_seq; - -ALTER EXTENSION pgagent ADD FUNCTION pgagent.pgagent_schema_version(); -ALTER EXTENSION pgagent ADD FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool); -ALTER EXTENSION pgagent ADD FUNCTION pgagent.pga_is_leap_year(int2); -ALTER EXTENSION pgagent ADD FUNCTION pgagent.pga_job_trigger(); -ALTER EXTENSION pgagent ADD FUNCTION pgagent.pga_schedule_trigger(); -ALTER EXTENSION pgagent ADD FUNCTION pgagent.pga_exception_trigger(); - -SELECT pg_catalog.pg_extension_config_dump('pga_jobagent', ''); -SELECT pg_catalog.pg_extension_config_dump('pga_jobclass', $$WHERE jclname NOT IN ('Routine Maintenance', 'Data Import', 'Data Export', 'Data Summarisation', 'Miscellaneous')$$); -SELECT pg_catalog.pg_extension_config_dump('pga_job', ''); -SELECT pg_catalog.pg_extension_config_dump('pga_jobstep', ''); -SELECT pg_catalog.pg_extension_config_dump('pga_schedule', ''); -SELECT pg_catalog.pg_extension_config_dump('pga_exception', ''); -SELECT pg_catalog.pg_extension_config_dump('pga_joblog', ''); -SELECT pg_catalog.pg_extension_config_dump('pga_jobsteplog', ''); - -CREATE OR REPLACE FUNCTION pgagent.pgagent_schema_version() RETURNS int2 AS ' -BEGIN - -- RETURNS PGAGENT MAJOR VERSION - -- WE WILL CHANGE THE MAJOR VERSION, ONLY IF THERE IS A SCHEMA CHANGE - RETURN 4; -END; -' LANGUAGE 'plpgsql' VOLATILE; - -CREATE OR REPLACE FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) RETURNS timestamptz AS ' -DECLARE - jscid ALIAS FOR $1; - jscstart ALIAS FOR $2; - jscend ALIAS FOR $3; - jscminutes ALIAS FOR $4; - jschours ALIAS FOR $5; - jscweekdays ALIAS FOR $6; - jscmonthdays ALIAS FOR $7; - jscmonths ALIAS FOR $8; - - nextrun timestamp := ''1970-01-01 00:00:00-00''; - runafter timestamp := ''1970-01-01 00:00:00-00''; - - bingo bool := FALSE; - gotit bool := FALSE; - foundval bool := FALSE; - daytweak bool := FALSE; - minutetweak bool := FALSE; - - i int2 := 0; - d int2 := 0; - - nextminute int2 := 0; - nexthour int2 := 0; - nextday int2 := 0; - nextmonth int2 := 0; - nextyear int2 := 0; - - -BEGIN - -- No valid start date has been specified - IF jscstart IS NULL THEN RETURN NULL; END IF; - - -- The schedule is past its end date - IF jscend IS NOT NULL AND jscend < now() THEN RETURN NULL; END IF; - - -- Get the time to find the next run after. It will just be the later of - -- now() + 1m and the start date for the time being, however, we might want to - -- do more complex things using this value in the future. - IF date_trunc(''MINUTE'', jscstart) > date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)) THEN - runafter := date_trunc(''MINUTE'', jscstart); - ELSE - runafter := date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)); - END IF; - - -- - -- Enter a loop, generating next run timestamps until we find one - -- that falls on the required weekday, and is not matched by an exception - -- - - WHILE bingo = FALSE LOOP - - -- - -- Get the next run year - -- - nextyear := date_part(''YEAR'', runafter); - - -- - -- Get the next run month - -- - nextmonth := date_part(''MONTH'', runafter); - gotit := FALSE; - FOR i IN (nextmonth) .. 12 LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextmonth - 1) LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - - -- Wrap into next year - nextyear := nextyear + 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - - -- - -- Get the next run day - -- - -- If the year, or month have incremented, get the lowest day, - -- otherwise look for the next day matching or after today. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter)) THEN - nextday := 1; - FOR i IN 1 .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextday := date_part(''DAY'', runafter); - gotit := FALSE; - FOR i IN nextday .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextday - 1) LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - - -- Wrap into next month - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Was the last day flag selected? - IF nextday = 32 THEN - IF nextmonth = 1 THEN - nextday := 31; - ELSIF nextmonth = 2 THEN - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - nextday := 29; - ELSE - nextday := 28; - END IF; - ELSIF nextmonth = 3 THEN - nextday := 31; - ELSIF nextmonth = 4 THEN - nextday := 30; - ELSIF nextmonth = 5 THEN - nextday := 31; - ELSIF nextmonth = 6 THEN - nextday := 30; - ELSIF nextmonth = 7 THEN - nextday := 31; - ELSIF nextmonth = 8 THEN - nextday := 31; - ELSIF nextmonth = 9 THEN - nextday := 30; - ELSIF nextmonth = 10 THEN - nextday := 31; - ELSIF nextmonth = 11 THEN - nextday := 30; - ELSIF nextmonth = 12 THEN - nextday := 31; - END IF; - END IF; - - -- - -- Get the next run hour - -- - -- If the year, month or day have incremented, get the lowest hour, - -- otherwise look for the next hour matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR daytweak = TRUE) THEN - nexthour := 0; - FOR i IN 1 .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nexthour := date_part(''HOUR'', runafter); - gotit := FALSE; - FOR i IN (nexthour + 1) .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nexthour LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - - -- Wrap into next month - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- - -- Get the next run minute - -- - -- If the year, month day or hour have incremented, get the lowest minute, - -- otherwise look for the next minute matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR nexthour > date_part(''HOUR'', runafter) OR daytweak = TRUE) THEN - nextminute := 0; - IF minutetweak = TRUE THEN - d := 1; - ELSE - d := date_part(''MINUTE'', runafter)::int2; - END IF; - FOR i IN d .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextminute := date_part(''MINUTE'', runafter); - gotit := FALSE; - FOR i IN (nextminute + 1) .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nextminute LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - - -- Wrap into next hour - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nexthour = 23 THEN - nexthour = 0; - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - ELSE - nexthour := nexthour + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Build the result, and check it is not the same as runafter - this may - -- happen if all array entries are set to false. In this case, add a minute. - - nextrun := (nextyear::varchar || ''-''::varchar || nextmonth::varchar || ''-'' || nextday::varchar || '' '' || nexthour::varchar || '':'' || nextminute::varchar)::timestamptz; - - IF nextrun = runafter AND foundval = FALSE THEN - nextrun := nextrun + INTERVAL ''1 Minute''; - END IF; - - -- If the result is past the end date, exit. - IF nextrun > jscend THEN - RETURN NULL; - END IF; - - -- Check to ensure that the nextrun time is actually still valid. Its - -- possible that wrapped values may have carried the nextrun onto an - -- invalid time or date. - IF ((jscminutes = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscminutes[date_part(''MINUTE'', nextrun) + 1] = TRUE) AND - (jschours = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jschours[date_part(''HOUR'', nextrun) + 1] = TRUE) AND - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonthdays[date_part(''DAY'', nextrun)] = TRUE OR - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,t}'' AND - ((date_part(''MONTH'', nextrun) IN (1,3,5,7,8,10,12) AND date_part(''DAY'', nextrun) = 31) OR - (date_part(''MONTH'', nextrun) IN (4,6,9,11) AND date_part(''DAY'', nextrun) = 30) OR - (date_part(''MONTH'', nextrun) = 2 AND ((pgagent.pga_is_leap_year(date_part(''YEAR'', nextrun)::int2) AND date_part(''DAY'', nextrun) = 29) OR date_part(''DAY'', nextrun) = 28))))) AND - (jscmonths = ''{f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonths[date_part(''MONTH'', nextrun)] = TRUE)) THEN - - - -- Now, check to see if the nextrun time found is a) on an acceptable - -- weekday, and b) not matched by an exception. If not, set - -- runafter = nextrun and try again. - - -- Check for a wildcard weekday - gotit := FALSE; - FOR i IN 1 .. 7 LOOP - IF jscweekdays[i] = TRUE THEN - gotit := TRUE; - EXIT; - END IF; - END LOOP; - - -- OK, is the correct weekday selected, or a wildcard? - IF (jscweekdays[date_part(''DOW'', nextrun) + 1] = TRUE OR gotit = FALSE) THEN - - -- Check for exceptions - SELECT INTO d jexid FROM pgagent.pga_exception WHERE jexscid = jscid AND ((jexdate = nextrun::date AND jextime = nextrun::time) OR (jexdate = nextrun::date AND jextime IS NULL) OR (jexdate IS NULL AND jextime = nextrun::time)); - IF FOUND THEN - -- Nuts - found an exception. Increment the time and try again - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - ELSE - bingo := TRUE; - END IF; - ELSE - -- We''re on the wrong week day - increment a day and try again. - runafter := nextrun + INTERVAL ''1 Day''; - bingo := FALSE; - minutetweak := FALSE; - daytweak := TRUE; - END IF; - - ELSE - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - END IF; - - END LOOP; - - RETURN nextrun; -END; -' LANGUAGE 'plpgsql' VOLATILE; - -COMMENT ON FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) IS 'Calculates the next runtime for a given schedule'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent.sql deleted file mode 100644 index aef0eb64c7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgagent/postgres%2Fpgagent%2Fmaster%2Fsql%2Fpgagent.sql +++ /dev/null @@ -1,666 +0,0 @@ -/* -// pgAgent - PostgreSQL Tools -// -// Copyright (C) 2002 - 2021, The pgAdmin Development Team -// This software is released under the PostgreSQL Licence -// -// pgagent.sql - pgAgent tables and functions -// -*/ - -BEGIN TRANSACTION; - - - -CREATE SCHEMA pgagent; -COMMENT ON SCHEMA pgagent IS 'pgAgent system tables'; - - - -CREATE TABLE pgagent.pga_jobagent ( -jagpid int4 NOT NULL PRIMARY KEY, -jaglogintime timestamptz NOT NULL DEFAULT current_timestamp, -jagstation text NOT NULL -) WITHOUT OIDS; -COMMENT ON TABLE pgagent.pga_jobagent IS 'Active job agents'; - - - -CREATE TABLE pgagent.pga_jobclass ( -jclid serial NOT NULL PRIMARY KEY, -jclname text NOT NULL -) WITHOUT OIDS; -CREATE UNIQUE INDEX pga_jobclass_name ON pgagent.pga_jobclass(jclname); -COMMENT ON TABLE pgagent.pga_jobclass IS 'Job classification'; - -INSERT INTO pgagent.pga_jobclass (jclname) VALUES ('Routine Maintenance'); -INSERT INTO pgagent.pga_jobclass (jclname) VALUES ('Data Import'); -INSERT INTO pgagent.pga_jobclass (jclname) VALUES ('Data Export'); -INSERT INTO pgagent.pga_jobclass (jclname) VALUES ('Data Summarisation'); -INSERT INTO pgagent.pga_jobclass (jclname) VALUES ('Miscellaneous'); --- Be sure to update pg_extension_config_dump() below and in --- upgrade scripts etc, when adding new classes. - - -CREATE TABLE pgagent.pga_job ( -jobid serial NOT NULL PRIMARY KEY, -jobjclid int4 NOT NULL REFERENCES pgagent.pga_jobclass (jclid) ON DELETE RESTRICT ON UPDATE RESTRICT, -jobname text NOT NULL, -jobdesc text NOT NULL DEFAULT '', -jobhostagent text NOT NULL DEFAULT '', -jobenabled bool NOT NULL DEFAULT true, -jobcreated timestamptz NOT NULL DEFAULT current_timestamp, -jobchanged timestamptz NOT NULL DEFAULT current_timestamp, -jobagentid int4 NULL REFERENCES pgagent.pga_jobagent(jagpid) ON DELETE SET NULL ON UPDATE RESTRICT, -jobnextrun timestamptz NULL, -joblastrun timestamptz NULL -) WITHOUT OIDS; -COMMENT ON TABLE pgagent.pga_job IS 'Job main entry'; -COMMENT ON COLUMN pgagent.pga_job.jobagentid IS 'Agent that currently executes this job.'; - - - -CREATE TABLE pgagent.pga_jobstep ( -jstid serial NOT NULL PRIMARY KEY, -jstjobid int4 NOT NULL REFERENCES pgagent.pga_job (jobid) ON DELETE CASCADE ON UPDATE RESTRICT, -jstname text NOT NULL, -jstdesc text NOT NULL DEFAULT '', -jstenabled bool NOT NULL DEFAULT true, -jstkind char NOT NULL CHECK (jstkind IN ('b', 's')), -- batch, sql -jstcode text NOT NULL, -jstconnstr text NOT NULL DEFAULT '' CHECK ((jstconnstr != '' AND jstkind = 's' ) OR (jstconnstr = '' AND (jstkind = 'b' OR jstdbname != ''))), -jstdbname name NOT NULL DEFAULT '' CHECK ((jstdbname != '' AND jstkind = 's' ) OR (jstdbname = '' AND (jstkind = 'b' OR jstconnstr != ''))), -jstonerror char NOT NULL CHECK (jstonerror IN ('f', 's', 'i')) DEFAULT 'f', -- fail, success, ignore -jscnextrun timestamptz NULL -) WITHOUT OIDS; -CREATE INDEX pga_jobstep_jobid ON pgagent.pga_jobstep(jstjobid); -COMMENT ON TABLE pgagent.pga_jobstep IS 'Job step to be executed'; -COMMENT ON COLUMN pgagent.pga_jobstep.jstkind IS 'Kind of jobstep: s=sql, b=batch'; -COMMENT ON COLUMN pgagent.pga_jobstep.jstonerror IS 'What to do if step returns an error: f=fail the job, s=mark step as succeeded and continue, i=mark as fail but ignore it and proceed'; - - - -CREATE TABLE pgagent.pga_schedule ( -jscid serial NOT NULL PRIMARY KEY, -jscjobid int4 NOT NULL REFERENCES pgagent.pga_job (jobid) ON DELETE CASCADE ON UPDATE RESTRICT, -jscname text NOT NULL, -jscdesc text NOT NULL DEFAULT '', -jscenabled bool NOT NULL DEFAULT true, -jscstart timestamptz NOT NULL DEFAULT current_timestamp, -jscend timestamptz NULL, -jscminutes bool[60] NOT NULL DEFAULT '{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}', -jschours bool[24] NOT NULL DEFAULT '{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}', -jscweekdays bool[7] NOT NULL DEFAULT '{f,f,f,f,f,f,f}', -jscmonthdays bool[32] NOT NULL DEFAULT '{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}', -jscmonths bool[12] NOT NULL DEFAULT '{f,f,f,f,f,f,f,f,f,f,f,f}', -CONSTRAINT pga_schedule_jscminutes_size CHECK (array_upper(jscminutes, 1) = 60), -CONSTRAINT pga_schedule_jschours_size CHECK (array_upper(jschours, 1) = 24), -CONSTRAINT pga_schedule_jscweekdays_size CHECK (array_upper(jscweekdays, 1) = 7), -CONSTRAINT pga_schedule_jscmonthdays_size CHECK (array_upper(jscmonthdays, 1) = 32), -CONSTRAINT pga_schedule_jscmonths_size CHECK (array_upper(jscmonths, 1) = 12) -) WITHOUT OIDS; -CREATE INDEX pga_jobschedule_jobid ON pgagent.pga_schedule(jscjobid); -COMMENT ON TABLE pgagent.pga_schedule IS 'Schedule for a job'; - - - -CREATE TABLE pgagent.pga_exception ( -jexid serial NOT NULL PRIMARY KEY, -jexscid int4 NOT NULL REFERENCES pgagent.pga_schedule (jscid) ON DELETE CASCADE ON UPDATE RESTRICT, -jexdate date NULL, -jextime time NULL -) -WITHOUT OIDS; -CREATE INDEX pga_exception_jexscid ON pgagent.pga_exception (jexscid); -CREATE UNIQUE INDEX pga_exception_datetime ON pgagent.pga_exception (jexdate, jextime); -COMMENT ON TABLE pgagent.pga_schedule IS 'Job schedule exceptions'; - - - -CREATE TABLE pgagent.pga_joblog ( -jlgid serial NOT NULL PRIMARY KEY, -jlgjobid int4 NOT NULL REFERENCES pgagent.pga_job (jobid) ON DELETE CASCADE ON UPDATE RESTRICT, -jlgstatus char NOT NULL CHECK (jlgstatus IN ('r', 's', 'f', 'i', 'd')) DEFAULT 'r', -- running, success, failed, internal failure, aborted -jlgstart timestamptz NOT NULL DEFAULT current_timestamp, -jlgduration interval NULL -) WITHOUT OIDS; -CREATE INDEX pga_joblog_jobid ON pgagent.pga_joblog(jlgjobid); -COMMENT ON TABLE pgagent.pga_joblog IS 'Job run logs.'; -COMMENT ON COLUMN pgagent.pga_joblog.jlgstatus IS 'Status of job: r=running, s=successfully finished, f=failed, i=no steps to execute, d=aborted'; - - - -CREATE TABLE pgagent.pga_jobsteplog ( -jslid serial NOT NULL PRIMARY KEY, -jsljlgid int4 NOT NULL REFERENCES pgagent.pga_joblog (jlgid) ON DELETE CASCADE ON UPDATE RESTRICT, -jsljstid int4 NOT NULL REFERENCES pgagent.pga_jobstep (jstid) ON DELETE CASCADE ON UPDATE RESTRICT, -jslstatus char NOT NULL CHECK (jslstatus IN ('r', 's', 'i', 'f', 'd')) DEFAULT 'r', -- running, success, ignored, failed, aborted -jslresult int4 NULL, -jslstart timestamptz NOT NULL DEFAULT current_timestamp, -jslduration interval NULL, -jsloutput text -) WITHOUT OIDS; -CREATE INDEX pga_jobsteplog_jslid ON pgagent.pga_jobsteplog(jsljlgid); -COMMENT ON TABLE pgagent.pga_jobsteplog IS 'Job step run logs.'; -COMMENT ON COLUMN pgagent.pga_jobsteplog.jslstatus IS 'Status of job step: r=running, s=successfully finished, f=failed stopping job, i=ignored failure, d=aborted'; -COMMENT ON COLUMN pgagent.pga_jobsteplog.jslresult IS 'Return code of job step'; - -CREATE OR REPLACE FUNCTION pgagent.pgagent_schema_version() RETURNS int2 AS ' -BEGIN - -- RETURNS PGAGENT MAJOR VERSION - -- WE WILL CHANGE THE MAJOR VERSION, ONLY IF THERE IS A SCHEMA CHANGE - RETURN 4; -END; -' LANGUAGE 'plpgsql' VOLATILE; - - -CREATE OR REPLACE FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) RETURNS timestamptz AS ' -DECLARE - jscid ALIAS FOR $1; - jscstart ALIAS FOR $2; - jscend ALIAS FOR $3; - jscminutes ALIAS FOR $4; - jschours ALIAS FOR $5; - jscweekdays ALIAS FOR $6; - jscmonthdays ALIAS FOR $7; - jscmonths ALIAS FOR $8; - - nextrun timestamp := ''1970-01-01 00:00:00-00''; - runafter timestamp := ''1970-01-01 00:00:00-00''; - - bingo bool := FALSE; - gotit bool := FALSE; - foundval bool := FALSE; - daytweak bool := FALSE; - minutetweak bool := FALSE; - - i int2 := 0; - d int2 := 0; - - nextminute int2 := 0; - nexthour int2 := 0; - nextday int2 := 0; - nextmonth int2 := 0; - nextyear int2 := 0; - - -BEGIN - -- No valid start date has been specified - IF jscstart IS NULL THEN RETURN NULL; END IF; - - -- The schedule is past its end date - IF jscend IS NOT NULL AND jscend < now() THEN RETURN NULL; END IF; - - -- Get the time to find the next run after. It will just be the later of - -- now() + 1m and the start date for the time being, however, we might want to - -- do more complex things using this value in the future. - IF date_trunc(''MINUTE'', jscstart) > date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)) THEN - runafter := date_trunc(''MINUTE'', jscstart); - ELSE - runafter := date_trunc(''MINUTE'', (now() + ''1 Minute''::interval)); - END IF; - - -- - -- Enter a loop, generating next run timestamps until we find one - -- that falls on the required weekday, and is not matched by an exception - -- - - WHILE bingo = FALSE LOOP - - -- - -- Get the next run year - -- - nextyear := date_part(''YEAR'', runafter); - - -- - -- Get the next run month - -- - nextmonth := date_part(''MONTH'', runafter); - gotit := FALSE; - FOR i IN (nextmonth) .. 12 LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextmonth - 1) LOOP - IF jscmonths[i] = TRUE THEN - nextmonth := i; - - -- Wrap into next year - nextyear := nextyear + 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - - -- - -- Get the next run day - -- - -- If the year, or month have incremented, get the lowest day, - -- otherwise look for the next day matching or after today. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter)) THEN - nextday := 1; - FOR i IN 1 .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextday := date_part(''DAY'', runafter); - gotit := FALSE; - FOR i IN nextday .. 32 LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. (nextday - 1) LOOP - IF jscmonthdays[i] = TRUE THEN - nextday := i; - - -- Wrap into next month - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Was the last day flag selected? - IF nextday = 32 THEN - IF nextmonth = 1 THEN - nextday := 31; - ELSIF nextmonth = 2 THEN - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - nextday := 29; - ELSE - nextday := 28; - END IF; - ELSIF nextmonth = 3 THEN - nextday := 31; - ELSIF nextmonth = 4 THEN - nextday := 30; - ELSIF nextmonth = 5 THEN - nextday := 31; - ELSIF nextmonth = 6 THEN - nextday := 30; - ELSIF nextmonth = 7 THEN - nextday := 31; - ELSIF nextmonth = 8 THEN - nextday := 31; - ELSIF nextmonth = 9 THEN - nextday := 30; - ELSIF nextmonth = 10 THEN - nextday := 31; - ELSIF nextmonth = 11 THEN - nextday := 30; - ELSIF nextmonth = 12 THEN - nextday := 31; - END IF; - END IF; - - -- - -- Get the next run hour - -- - -- If the year, month or day have incremented, get the lowest hour, - -- otherwise look for the next hour matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR daytweak = TRUE) THEN - nexthour := 0; - FOR i IN 1 .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nexthour := date_part(''HOUR'', runafter); - gotit := FALSE; - FOR i IN (nexthour + 1) .. 24 LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nexthour LOOP - IF jschours[i] = TRUE THEN - nexthour := i - 1; - - -- Wrap into next month - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- - -- Get the next run minute - -- - -- If the year, month day or hour have incremented, get the lowest minute, - -- otherwise look for the next minute matching or after the current one. - IF (nextyear > date_part(''YEAR'', runafter) OR nextmonth > date_part(''MONTH'', runafter) OR nextday > date_part(''DAY'', runafter) OR nexthour > date_part(''HOUR'', runafter) OR daytweak = TRUE) THEN - nextminute := 0; - IF minutetweak = TRUE THEN - d := 1; - ELSE - d := date_part(''MINUTE'', runafter)::int2; - END IF; - FOR i IN d .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - ELSE - nextminute := date_part(''MINUTE'', runafter); - gotit := FALSE; - FOR i IN (nextminute + 1) .. 60 LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - IF gotit = FALSE THEN - FOR i IN 1 .. nextminute LOOP - IF jscminutes[i] = TRUE THEN - nextminute := i - 1; - - -- Wrap into next hour - IF (nextmonth = 1 OR nextmonth = 3 OR nextmonth = 5 OR nextmonth = 7 OR nextmonth = 8 OR nextmonth = 10 OR nextmonth = 12) THEN - d = 31; - ELSIF (nextmonth = 4 OR nextmonth = 6 OR nextmonth = 9 OR nextmonth = 11) THEN - d = 30; - ELSE - IF pgagent.pga_is_leap_year(nextyear) = TRUE THEN - d := 29; - ELSE - d := 28; - END IF; - END IF; - - IF nexthour = 23 THEN - nexthour = 0; - IF nextday = d THEN - nextday := 1; - IF nextmonth = 12 THEN - nextyear := nextyear + 1; - nextmonth := 1; - ELSE - nextmonth := nextmonth + 1; - END IF; - ELSE - nextday := nextday + 1; - END IF; - ELSE - nexthour := nexthour + 1; - END IF; - - gotit := TRUE; - foundval := TRUE; - EXIT; - END IF; - END LOOP; - END IF; - END IF; - - -- Build the result, and check it is not the same as runafter - this may - -- happen if all array entries are set to false. In this case, add a minute. - - nextrun := (nextyear::varchar || ''-''::varchar || nextmonth::varchar || ''-'' || nextday::varchar || '' '' || nexthour::varchar || '':'' || nextminute::varchar)::timestamptz; - - IF nextrun = runafter AND foundval = FALSE THEN - nextrun := nextrun + INTERVAL ''1 Minute''; - END IF; - - -- If the result is past the end date, exit. - IF nextrun > jscend THEN - RETURN NULL; - END IF; - - -- Check to ensure that the nextrun time is actually still valid. Its - -- possible that wrapped values may have carried the nextrun onto an - -- invalid time or date. - IF ((jscminutes = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscminutes[date_part(''MINUTE'', nextrun) + 1] = TRUE) AND - (jschours = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jschours[date_part(''HOUR'', nextrun) + 1] = TRUE) AND - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonthdays[date_part(''DAY'', nextrun)] = TRUE OR - (jscmonthdays = ''{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,t}'' AND - ((date_part(''MONTH'', nextrun) IN (1,3,5,7,8,10,12) AND date_part(''DAY'', nextrun) = 31) OR - (date_part(''MONTH'', nextrun) IN (4,6,9,11) AND date_part(''DAY'', nextrun) = 30) OR - (date_part(''MONTH'', nextrun) = 2 AND ((pgagent.pga_is_leap_year(date_part(''YEAR'', nextrun)::int2) AND date_part(''DAY'', nextrun) = 29) OR date_part(''DAY'', nextrun) = 28))))) AND - (jscmonths = ''{f,f,f,f,f,f,f,f,f,f,f,f}'' OR jscmonths[date_part(''MONTH'', nextrun)] = TRUE)) THEN - - - -- Now, check to see if the nextrun time found is a) on an acceptable - -- weekday, and b) not matched by an exception. If not, set - -- runafter = nextrun and try again. - - -- Check for a wildcard weekday - gotit := FALSE; - FOR i IN 1 .. 7 LOOP - IF jscweekdays[i] = TRUE THEN - gotit := TRUE; - EXIT; - END IF; - END LOOP; - - -- OK, is the correct weekday selected, or a wildcard? - IF (jscweekdays[date_part(''DOW'', nextrun) + 1] = TRUE OR gotit = FALSE) THEN - - -- Check for exceptions - SELECT INTO d jexid FROM pgagent.pga_exception WHERE jexscid = jscid AND ((jexdate = nextrun::date AND jextime = nextrun::time) OR (jexdate = nextrun::date AND jextime IS NULL) OR (jexdate IS NULL AND jextime = nextrun::time)); - IF FOUND THEN - -- Nuts - found an exception. Increment the time and try again - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - ELSE - bingo := TRUE; - END IF; - ELSE - -- We''re on the wrong week day - increment a day and try again. - runafter := nextrun + INTERVAL ''1 Day''; - bingo := FALSE; - minutetweak := FALSE; - daytweak := TRUE; - END IF; - - ELSE - runafter := nextrun + INTERVAL ''1 Minute''; - bingo := FALSE; - minutetweak := TRUE; - daytweak := FALSE; - END IF; - - END LOOP; - - RETURN nextrun; -END; -' LANGUAGE 'plpgsql' VOLATILE; -COMMENT ON FUNCTION pgagent.pga_next_schedule(int4, timestamptz, timestamptz, _bool, _bool, _bool, _bool, _bool) IS 'Calculates the next runtime for a given schedule'; - - - --- --- Test code --- --- SELECT pgagent.pga_next_schedule( --- 2, -- Schedule ID --- '2005-01-01 00:00:00', -- Start date --- '2006-10-01 00:00:00', -- End date --- '{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}', -- Minutes --- '{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}', -- Hours --- '{f,f,f,f,f,f,f}', -- Weekdays --- '{f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f}', -- Monthdays --- '{f,f,f,f,f,f,f,f,f,f,f,f}' -- Months --- ); - - - -CREATE OR REPLACE FUNCTION pgagent.pga_is_leap_year(int2) RETURNS bool AS ' -BEGIN - IF $1 % 4 != 0 THEN - RETURN FALSE; - END IF; - - IF $1 % 100 != 0 THEN - RETURN TRUE; - END IF; - - RETURN $1 % 400 = 0; -END; -' LANGUAGE 'plpgsql' IMMUTABLE; -COMMENT ON FUNCTION pgagent.pga_is_leap_year(int2) IS 'Returns TRUE if $1 is a leap year'; - - -CREATE OR REPLACE FUNCTION pgagent.pga_job_trigger() - RETURNS "trigger" AS -' -BEGIN - IF NEW.jobenabled THEN - IF NEW.jobnextrun IS NULL THEN - SELECT INTO NEW.jobnextrun - MIN(pgagent.pga_next_schedule(jscid, jscstart, jscend, jscminutes, jschours, jscweekdays, jscmonthdays, jscmonths)) - FROM pgagent.pga_schedule - WHERE jscenabled AND jscjobid=OLD.jobid; - END IF; - ELSE - NEW.jobnextrun := NULL; - END IF; - RETURN NEW; -END; -' - LANGUAGE 'plpgsql' VOLATILE; -COMMENT ON FUNCTION pgagent.pga_job_trigger() IS 'Update the job''s next run time.'; - -CREATE TRIGGER pga_job_trigger BEFORE UPDATE - ON pgagent.pga_job FOR EACH ROW - EXECUTE PROCEDURE pgagent.pga_job_trigger(); -COMMENT ON TRIGGER pga_job_trigger ON pgagent.pga_job IS 'Update the job''s next run time.'; - - -CREATE OR REPLACE FUNCTION pgagent.pga_schedule_trigger() RETURNS trigger AS ' -BEGIN - IF TG_OP = ''DELETE'' THEN - -- update pga_job from remaining schedules - -- the actual calculation of jobnextrun will be performed in the trigger - UPDATE pgagent.pga_job - SET jobnextrun = NULL - WHERE jobenabled AND jobid=OLD.jscjobid; - RETURN OLD; - ELSE - UPDATE pgagent.pga_job - SET jobnextrun = NULL - WHERE jobenabled AND jobid=NEW.jscjobid; - RETURN NEW; - END IF; -END; -' LANGUAGE 'plpgsql'; -COMMENT ON FUNCTION pgagent.pga_schedule_trigger() IS 'Update the job''s next run time whenever a schedule changes'; - - - -CREATE TRIGGER pga_schedule_trigger AFTER INSERT OR UPDATE OR DELETE - ON pgagent.pga_schedule FOR EACH ROW - EXECUTE PROCEDURE pgagent.pga_schedule_trigger(); -COMMENT ON TRIGGER pga_schedule_trigger ON pgagent.pga_schedule IS 'Update the job''s next run time whenever a schedule changes'; - - -CREATE OR REPLACE FUNCTION pgagent.pga_exception_trigger() RETURNS "trigger" AS ' -DECLARE - - v_jobid int4 := 0; - -BEGIN - - IF TG_OP = ''DELETE'' THEN - - SELECT INTO v_jobid jscjobid FROM pgagent.pga_schedule WHERE jscid = OLD.jexscid; - - -- update pga_job from remaining schedules - -- the actual calculation of jobnextrun will be performed in the trigger - UPDATE pgagent.pga_job - SET jobnextrun = NULL - WHERE jobenabled AND jobid = v_jobid; - RETURN OLD; - ELSE - - SELECT INTO v_jobid jscjobid FROM pgagent.pga_schedule WHERE jscid = NEW.jexscid; - - UPDATE pgagent.pga_job - SET jobnextrun = NULL - WHERE jobenabled AND jobid = v_jobid; - RETURN NEW; - END IF; -END; -' LANGUAGE 'plpgsql' VOLATILE; -COMMENT ON FUNCTION pgagent.pga_exception_trigger() IS 'Update the job''s next run time whenever an exception changes'; - - - -CREATE TRIGGER pga_exception_trigger AFTER INSERT OR UPDATE OR DELETE - ON pgagent.pga_exception FOR EACH ROW - EXECUTE PROCEDURE pgagent.pga_exception_trigger(); -COMMENT ON TRIGGER pga_exception_trigger ON pgagent.pga_exception IS 'Update the job''s next run time whenever an exception changes'; - --- Extension dump support. --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_jobagent', ''); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_jobclass', $$WHERE jclname NOT IN ('Routine Maintenance', 'Data Import', 'Data Export', 'Data Summarisation', 'Miscellaneous')$$); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_job', ''); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_jobstep', ''); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_schedule', ''); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_exception', ''); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_joblog', ''); --- EXT SELECT pg_catalog.pg_extension_config_dump('pga_jobsteplog', ''); - -COMMIT TRANSACTION; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/LICENSE b/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/LICENSE deleted file mode 100644 index 9d65dbea7e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -PostgreSQL Database Management System -(formerly known as Postgres, then as Postgres95) - -Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group - -Portions Copyright (c) 1994, The Regents of the University of California - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose, without fee, and without a written agreement -is hereby granted, provided that the above copyright notice and this -paragraph and the following two paragraphs appear in all copies. - -IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR -DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING -LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS -DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS -ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO -PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Fsql%2Fvarnish.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Fsql%2Fvarnish.sql deleted file mode 100644 index d78138fd42..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Fsql%2Fvarnish.sql +++ /dev/null @@ -1,37 +0,0 @@ -BEGIN; - --- --- Create a function to purge from varnish cache --- By default this adds the object to a local queue, --- but this function can be replaced with a void one --- when running a development version. --- - -CREATE SCHEMA IF NOT EXISTS varnishqueue; -CREATE TABLE IF NOT EXISTS varnishqueue.queue (id bigserial primary key, mode char NOT NULL, consumerid int NOT NULL, expr text NOT NULL, added timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, completed timestamptz NULL); -CREATE TABLE IF NOT EXISTS varnishqueue.consumers (consumerid serial PRIMARY KEY, consumer text NOT NULL); - -DROP FUNCTION IF EXISTS varnish_purge(url text); -CREATE OR REPLACE FUNCTION varnish_purge(url text) -RETURNS void -AS $$ - INSERT INTO varnishqueue.queue (mode, consumerid, expr) SELECT 'P', consumerid, $1 FROM varnishqueue.consumers; - NOTIFY varnishqueue; -$$ LANGUAGE 'sql'; - -DROP FUNCTION IF EXISTS varnish_purge_expr(expr text); -CREATE OR REPLACE FUNCTION varnish_purge_expr(expr text) -RETURNS void -AS $$ - INSERT INTO varnishqueue.queue (mode, consumerid, expr) SELECT 'X', consumerid, $1 FROM varnishqueue.consumers; - NOTIFY varnishqueue; -$$ LANGUAGE 'sql'; - -DROP FUNCTION IF EXISTS varnish_purge_xkey(key text); -CREATE OR REPLACE FUNCTION varnish_purge_xkey(key text) -RETURNS void -AS $$ - INSERT INTO varnishqueue.queue (mode, consumerid, expr) SELECT 'K', consumerid, $1 FROM varnishqueue.consumers; - NOTIFY varnishqueue; -$$ LANGUAGE 'sql'; -COMMIT; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Fsql%2Fvarnish_local.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Fsql%2Fvarnish_local.sql deleted file mode 100644 index 926eb14269..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Fsql%2Fvarnish_local.sql +++ /dev/null @@ -1,24 +0,0 @@ -BEGIN; - --- --- "cheating" version of the varnish_purge() function --- that can be used on a local installation that doesn't --- have any frontends. --- - -CREATE OR REPLACE FUNCTION varnish_purge(url text) -RETURNS void -AS $$ -$$ LANGUAGE 'sql'; - -CREATE OR REPLACE FUNCTION varnish_purge_expr(expr text) -RETURNS void -AS $$ -$$ LANGUAGE 'sql'; - -CREATE OR REPLACE FUNCTION varnish_purge_xkey(key text) -RETURNS void -AS $$ -$$ LANGUAGE 'sql'; - -COMMIT; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fscrub%2Fscrub.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fscrub%2Fscrub.sql deleted file mode 100644 index 165f896303..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fscrub%2Fscrub.sql +++ /dev/null @@ -1,58 +0,0 @@ --- --- scrub.sql --- --- Scrub the contents of the pgweb database, so the data can be reasonably shared --- by updating and deleting anything sensitive --- --- WARNING! DO NOT RUN IN PRODUCTION! --- --- NOTE! BEFORE USE, ALWAYS VALIDATE THAT THE SCRIPT IS UP TO DATE! --- --- --- Always runs as a transaction, just in case... - -\set ON_ERROR_STOP 1 -BEGIN; - --- Commnity auth sites need reset crypto keys --- The actual sites and id's are not secret. -UPDATE account_communityauthsite SET cryptkey='XXX'; - --- Any outstanding email tokens need to just be removed -DELETE FROM account_emailchangetoken; - --- As this is the master database, we need to massage the user table since it has a lot --- of sensitive data in it. We need to clear out names and emails, as well as passwords. --- The user is expected to manually set up new users as needed, but we need these --- links to remain in the system. -UPDATE auth_user SET username='id' || id, - first_name='F' || id, - last_name='L' || id, - email='e' || id || '@scrubbed.postgresql.org', - password='NOTAVALIDHASHSETBYSCRUBBINGSCRIPT', - is_staff='f', is_superuser='f'; - -UPDATE contributors_contributor SET email='e'||id||'@scrubbed.postgresql.org'; - -DELETE FROM core_moderationnotification; - -UPDATE core_organisation SET email='e'||id||'@scrubbed.postgresql.org', phone='1-555-'||id, - name='O'||id, address='scrubbedaddress', url='http://scrubbed.url'; -DELETE FROM core_organisation_managers; -UPDATE core_userprofile SET sshkey='SSHKEYSCRUBBED'; - -TRUNCATE TABLE django_admin_log; -TRUNCATE TABLE django_session; - --- Just in case we snapshotted with something in the queue -DELETE FROM mailqueue_queuedmail; - -UPDATE profserv_professionalservice SET contact='scrubbedcontact'; - -TRUNCATE TABLE survey_surveylock; - --- We still have a lot of migration data, so lose it. -DROP TABLE IF EXISTS users_old; -DROP TABLE IF EXISTS docs_doccomment_saved; - -\echo NOTE! Transaction has not been committed. Verify manually and then commit! diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fsearch%2Fsql%2Ffunctions.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fsearch%2Fsql%2Ffunctions.sql deleted file mode 100644 index 9ee5c4a51c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fsearch%2Fsql%2Ffunctions.sql +++ /dev/null @@ -1,42 +0,0 @@ -CREATE OR REPLACE FUNCTION site_search(query text, startofs int, hitsperpage int, _suburl text, includeinternal boolean DEFAULT False) -RETURNS TABLE (siteid int, baseurl text, suburl text, title text, headline text, rank float) -AS $$ -DECLARE - tsq tsquery; - qry text; - hits int; - hit RECORD; - curs refcursor; - pagecount int; -BEGIN - tsq := plainto_tsquery('public.pg', query); - IF numnode(tsq) = 0 THEN - siteid = 0;baseurl=NULL;suburl=NULL;title=NULL;headline=NULL;rank=0; - RETURN NEXT; - RETURN; - END IF; - - hits := 0; - - SELECT INTO pagecount sites.pagecount FROM sites WHERE id=1; - IF _suburl IS NULL THEN - OPEN curs FOR SELECT sites.id AS siteid, sites.baseurl, webpages.suburl, ts_rank_cd(fti,tsq) * relprio AS ts_rank_cd FROM webpages INNER JOIN sites ON webpages.site=sites.id WHERE fti @@ tsq AND site=1 AND (includeinternal OR NOT isinternal) ORDER BY ts_rank_cd(fti,tsq) * relprio DESC LIMIT 1000; - ELSE - OPEN curs FOR SELECT sites.id AS siteid, sites.baseurl, webpages.suburl, ts_rank_cd(fti,tsq) * relprio AS ts_rank_cd FROM webpages INNER JOIN sites ON webpages.site=sites.id WHERE fti @@ tsq AND site=1 AND webpages.suburl LIKE _suburl||'%' AND (includeinternal OR NOT isinternal) ORDER BY ts_rank_cd(fti,tsq) * relprio DESC LIMIT 1000; - END IF; - LOOP - FETCH curs INTO hit; - IF NOT FOUND THEN - EXIT; - END IF; - hits := hits+1; - IF (hits < startofs+1) OR (hits > startofs+hitsperpage) THEN - CONTINUE; - END IF; - RETURN QUERY SELECT hit.siteid, hit.baseurl::text, hit.suburl::text, webpages.title::text, ts_headline(webpages.txt,tsq,'StartSel="[[[[[[",StopSel="]]]]]]"'), hit.ts_rank_cd::float * relprio FROM webpages WHERE webpages.site=hit.siteid AND webpages.suburl=hit.suburl; - END LOOP; - RETURN QUERY SELECT pagecount, NULL::text, NULL::text, NULL::text, NULL::text, hits::float; -END; -$$ -LANGUAGE 'plpgsql'; -ALTER FUNCTION site_search(text, int, int, text, bool) SET default_text_search_config = 'public.pg'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fsearch%2Fsql%2Ftsearch.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fsearch%2Fsql%2Ftsearch.sql deleted file mode 100644 index 6db3a555b2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/pgweb/postgres%2Fpgweb%2Fmaster%2Ftools%2Fsearch%2Fsql%2Ftsearch.sql +++ /dev/null @@ -1,33 +0,0 @@ --- Creates configuration 'pg' - -BEGIN; - --- create our configuration to work from -CREATE TEXT SEARCH CONFIGURATION pg (COPY = pg_catalog.english ); - --- create english ispell dictionary -CREATE TEXT SEARCH DICTIONARY english_ispell ( - TEMPLATE = ispell, - DictFile = en_us, - AffFile = en_us, - StopWords = english -); --- create our dictionary -CREATE TEXT SEARCH DICTIONARY pg_dict ( - TEMPLATE = synonym, - SYNONYMS = pg_dict -); - --- activate the dictionaries -ALTER TEXT SEARCH CONFIGURATION pg - ALTER MAPPING FOR asciiword, asciihword, hword_asciipart, - word, hword, hword_part - WITH pg_dict, english_ispell, english_stem; - --- parts we don't want to index at all -ALTER TEXT SEARCH CONFIGURATION pg - DROP MAPPING FOR email, url, url_path, sfloat, float; - --- All done - -COMMIT; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/LICENSE b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/LICENSE deleted file mode 100644 index 9d65dbea7e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -PostgreSQL Database Management System -(formerly known as Postgres, then as Postgres95) - -Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group - -Portions Copyright (c) 1994, The Regents of the University of California - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose, without fee, and without a written agreement -is hereby granted, provided that the above copyright notice and this -paragraph and the following two paragraphs appear in all copies. - -IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR -DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING -LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS -DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. - -THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, -INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS -ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO -PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Famcheck%2Fsql%2Fcheck_btree.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Famcheck%2Fsql%2Fcheck_btree.sql deleted file mode 100644 index 033c04b4d0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Famcheck%2Fsql%2Fcheck_btree.sql +++ /dev/null @@ -1,146 +0,0 @@ -CREATE TABLE bttest_a(id int8); -CREATE TABLE bttest_b(id int8); -CREATE TABLE bttest_multi(id int8, data int8); -CREATE TABLE delete_test_table (a bigint, b bigint, c bigint, d bigint); - --- Stabalize tests -ALTER TABLE bttest_a SET (autovacuum_enabled = false); -ALTER TABLE bttest_b SET (autovacuum_enabled = false); -ALTER TABLE bttest_multi SET (autovacuum_enabled = false); -ALTER TABLE delete_test_table SET (autovacuum_enabled = false); - -INSERT INTO bttest_a SELECT * FROM generate_series(1, 100000); -INSERT INTO bttest_b SELECT * FROM generate_series(100000, 1, -1); -INSERT INTO bttest_multi SELECT i, i%2 FROM generate_series(1, 100000) as i; - -CREATE INDEX bttest_a_idx ON bttest_a USING btree (id) WITH (deduplicate_items = ON); -CREATE INDEX bttest_b_idx ON bttest_b USING btree (id); -CREATE UNIQUE INDEX bttest_multi_idx ON bttest_multi -USING btree (id) INCLUDE (data); - -CREATE ROLE regress_bttest_role; - --- verify permissions are checked (error due to function not callable) -SET ROLE regress_bttest_role; -SELECT bt_index_check('bttest_a_idx'::regclass); -SELECT bt_index_parent_check('bttest_a_idx'::regclass); -RESET ROLE; - --- we, intentionally, don't check relation permissions - it's useful --- to run this cluster-wide with a restricted account, and as tested --- above explicit permission has to be granted for that. -GRANT EXECUTE ON FUNCTION bt_index_check(regclass) TO regress_bttest_role; -GRANT EXECUTE ON FUNCTION bt_index_parent_check(regclass) TO regress_bttest_role; -GRANT EXECUTE ON FUNCTION bt_index_check(regclass, boolean) TO regress_bttest_role; -GRANT EXECUTE ON FUNCTION bt_index_parent_check(regclass, boolean) TO regress_bttest_role; -SET ROLE regress_bttest_role; -SELECT bt_index_check('bttest_a_idx'); -SELECT bt_index_parent_check('bttest_a_idx'); -RESET ROLE; - --- verify plain tables are rejected (error) -SELECT bt_index_check('bttest_a'); -SELECT bt_index_parent_check('bttest_a'); - --- verify non-existing indexes are rejected (error) -SELECT bt_index_check(17); -SELECT bt_index_parent_check(17); - --- verify wrong index types are rejected (error) -BEGIN; -CREATE INDEX bttest_a_brin_idx ON bttest_a USING brin(id); -SELECT bt_index_parent_check('bttest_a_brin_idx'); -ROLLBACK; - --- normal check outside of xact -SELECT bt_index_check('bttest_a_idx'); --- more expansive tests -SELECT bt_index_check('bttest_a_idx', true); -SELECT bt_index_parent_check('bttest_b_idx', true); - -BEGIN; -SELECT bt_index_check('bttest_a_idx'); -SELECT bt_index_parent_check('bttest_b_idx'); --- make sure we don't have any leftover locks -SELECT * FROM pg_locks -WHERE relation = ANY(ARRAY['bttest_a', 'bttest_a_idx', 'bttest_b', 'bttest_b_idx']::regclass[]) - AND pid = pg_backend_pid(); -COMMIT; - --- Deduplication -TRUNCATE bttest_a; -INSERT INTO bttest_a SELECT 42 FROM generate_series(1, 2000); -SELECT bt_index_check('bttest_a_idx', true); - --- normal check outside of xact for index with included columns -SELECT bt_index_check('bttest_multi_idx'); --- more expansive tests for index with included columns -SELECT bt_index_parent_check('bttest_multi_idx', true, true); - --- repeat expansive tests for index built using insertions -TRUNCATE bttest_multi; -INSERT INTO bttest_multi SELECT i, i%2 FROM generate_series(1, 100000) as i; -SELECT bt_index_parent_check('bttest_multi_idx', true, true); - --- --- Test for multilevel page deletion/downlink present checks, and rootdescend --- checks --- -INSERT INTO delete_test_table SELECT i, 1, 2, 3 FROM generate_series(1,80000) i; -ALTER TABLE delete_test_table ADD PRIMARY KEY (a,b,c,d); --- Delete most entries, and vacuum, deleting internal pages and creating "fast --- root" -DELETE FROM delete_test_table WHERE a < 79990; -VACUUM delete_test_table; -SELECT bt_index_parent_check('delete_test_table_pkey', true); - --- --- BUG #15597: must not assume consistent input toasting state when forming --- tuple. Bloom filter must fingerprint normalized index tuple representation. --- -CREATE TABLE toast_bug(buggy text); -ALTER TABLE toast_bug ALTER COLUMN buggy SET STORAGE extended; -CREATE INDEX toasty ON toast_bug(buggy); - --- pg_attribute entry for toasty.buggy (the index) will have plain storage: -UPDATE pg_attribute SET attstorage = 'p' -WHERE attrelid = 'toasty'::regclass AND attname = 'buggy'; - --- Whereas pg_attribute entry for toast_bug.buggy (the table) still has extended storage: -SELECT attstorage FROM pg_attribute -WHERE attrelid = 'toast_bug'::regclass AND attname = 'buggy'; - --- Insert compressible heap tuple (comfortably exceeds TOAST_TUPLE_THRESHOLD): -INSERT INTO toast_bug SELECT repeat('a', 2200); --- Should not get false positive report of corruption: -SELECT bt_index_check('toasty', true); - --- --- Check that index expressions and predicates are run as the table's owner --- -TRUNCATE bttest_a; -INSERT INTO bttest_a SELECT * FROM generate_series(1, 1000); -ALTER TABLE bttest_a OWNER TO regress_bttest_role; --- A dummy index function checking current_user -CREATE FUNCTION ifun(int8) RETURNS int8 AS $$ -BEGIN - ASSERT current_user = 'regress_bttest_role', - format('ifun(%s) called by %s', $1, current_user); - RETURN $1; -END; -$$ LANGUAGE plpgsql IMMUTABLE; - -CREATE INDEX bttest_a_expr_idx ON bttest_a ((ifun(id) + ifun(0))) - WHERE ifun(id + 10) > ifun(10); - -SELECT bt_index_check('bttest_a_expr_idx', true); - --- cleanup -DROP TABLE bttest_a; -DROP TABLE bttest_b; -DROP TABLE bttest_multi; -DROP TABLE delete_test_table; -DROP TABLE toast_bug; -DROP FUNCTION ifun(int8); -DROP OWNED BY regress_bttest_role; -- permissions -DROP ROLE regress_bttest_role; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Famcheck%2Fsql%2Fcheck_heap.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Famcheck%2Fsql%2Fcheck_heap.sql deleted file mode 100644 index 298de6886a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Famcheck%2Fsql%2Fcheck_heap.sql +++ /dev/null @@ -1,116 +0,0 @@ -CREATE TABLE heaptest (a integer, b text); -REVOKE ALL ON heaptest FROM PUBLIC; - --- Check that invalid skip option is rejected -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'rope'); - --- Check specifying invalid block ranges when verifying an empty table -SELECT * FROM verify_heapam(relation := 'heaptest', startblock := 0, endblock := 0); -SELECT * FROM verify_heapam(relation := 'heaptest', startblock := 5, endblock := 8); - --- Check that valid options are not rejected nor corruption reported --- for an empty table, and that skip enum-like parameter is case-insensitive -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'none'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'all-frozen'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'all-visible'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'None'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'All-Frozen'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'All-Visible'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'NONE'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'ALL-FROZEN'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'ALL-VISIBLE'); - --- Add some data so subsequent tests are not entirely trivial -INSERT INTO heaptest (a, b) - (SELECT gs, repeat('x', gs) - FROM generate_series(1,50) gs); - --- Check that valid options are not rejected nor corruption reported --- for a non-empty table -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'none'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'all-frozen'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'all-visible'); -SELECT * FROM verify_heapam(relation := 'heaptest', startblock := 0, endblock := 0); - -CREATE ROLE regress_heaptest_role; - --- verify permissions are checked (error due to function not callable) -SET ROLE regress_heaptest_role; -SELECT * FROM verify_heapam(relation := 'heaptest'); -RESET ROLE; - -GRANT EXECUTE ON FUNCTION verify_heapam(regclass, boolean, boolean, text, bigint, bigint) TO regress_heaptest_role; - --- verify permissions are now sufficient -SET ROLE regress_heaptest_role; -SELECT * FROM verify_heapam(relation := 'heaptest'); -RESET ROLE; - --- Check specifying invalid block ranges when verifying a non-empty table. -SELECT * FROM verify_heapam(relation := 'heaptest', startblock := 0, endblock := 10000); -SELECT * FROM verify_heapam(relation := 'heaptest', startblock := 10000, endblock := 11000); - --- Vacuum freeze to change the xids encountered in subsequent tests -VACUUM (FREEZE, DISABLE_PAGE_SKIPPING) heaptest; - --- Check that valid options are not rejected nor corruption reported --- for a non-empty frozen table -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'none'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'all-frozen'); -SELECT * FROM verify_heapam(relation := 'heaptest', skip := 'all-visible'); -SELECT * FROM verify_heapam(relation := 'heaptest', startblock := 0, endblock := 0); - --- Check that partitioned tables (the parent ones) which don't have visibility --- maps are rejected -CREATE TABLE test_partitioned (a int, b text default repeat('x', 5000)) - PARTITION BY list (a); -SELECT * FROM verify_heapam('test_partitioned', - startblock := NULL, - endblock := NULL); - --- Check that valid options are not rejected nor corruption reported --- for an empty partition table (the child one) -CREATE TABLE test_partition partition OF test_partitioned FOR VALUES IN (1); -SELECT * FROM verify_heapam('test_partition', - startblock := NULL, - endblock := NULL); - --- Check that valid options are not rejected nor corruption reported --- for a non-empty partition table (the child one) -INSERT INTO test_partitioned (a) (SELECT 1 FROM generate_series(1,1000) gs); -SELECT * FROM verify_heapam('test_partition', - startblock := NULL, - endblock := NULL); - --- Check that indexes are rejected -CREATE INDEX test_index ON test_partition (a); -SELECT * FROM verify_heapam('test_index', - startblock := NULL, - endblock := NULL); - --- Check that views are rejected -CREATE VIEW test_view AS SELECT 1; -SELECT * FROM verify_heapam('test_view', - startblock := NULL, - endblock := NULL); - --- Check that sequences are rejected -CREATE SEQUENCE test_sequence; -SELECT * FROM verify_heapam('test_sequence', - startblock := NULL, - endblock := NULL); - --- Check that foreign tables are rejected -CREATE FOREIGN DATA WRAPPER dummy; -CREATE SERVER dummy_server FOREIGN DATA WRAPPER dummy; -CREATE FOREIGN TABLE test_foreign_table () SERVER dummy_server; -SELECT * FROM verify_heapam('test_foreign_table', - startblock := NULL, - endblock := NULL); - --- cleanup -DROP TABLE heaptest; -DROP TABLE test_partition; -DROP TABLE test_partitioned; -DROP OWNED BY regress_heaptest_role; -- permissions -DROP ROLE regress_heaptest_role; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbool_plperl%2Fsql%2Fbool_plperl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbool_plperl%2Fsql%2Fbool_plperl.sql deleted file mode 100644 index b7f570862c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbool_plperl%2Fsql%2Fbool_plperl.sql +++ /dev/null @@ -1,70 +0,0 @@ -CREATE EXTENSION bool_plperl CASCADE; - ---- test transforming from perl - -CREATE FUNCTION perl2int(int) RETURNS bool -LANGUAGE plperl -TRANSFORM FOR TYPE bool -AS $$ -return shift; -$$; - -CREATE FUNCTION perl2text(text) RETURNS bool -LANGUAGE plperl -TRANSFORM FOR TYPE bool -AS $$ -return shift; -$$; - -CREATE FUNCTION perl2undef() RETURNS bool -LANGUAGE plperl -TRANSFORM FOR TYPE bool -AS $$ -return undef; -$$; - -SELECT perl2int(1); -SELECT perl2int(0); -SELECT perl2text('foo'); -SELECT perl2text(''); -SELECT perl2undef() IS NULL AS p; - ---- test transforming to perl - -CREATE FUNCTION bool2perl(bool, bool, bool) RETURNS void -LANGUAGE plperl -TRANSFORM FOR TYPE bool, for type boolean -- duplicate to test ruleutils -AS $$ -my ($x, $y, $z) = @_; - -die("NULL mistransformed") if (defined($z)); -die("TRUE mistransformed to UNDEF") if (!defined($x)); -die("FALSE mistransformed to UNDEF") if (!defined($y)); -die("TRUE mistransformed") if (!$x); -die("FALSE mistransformed") if ($y); -$$; - -SELECT bool2perl (true, false, NULL); - ---- test ruleutils - -\sf bool2perl - ---- test selecting bool through SPI - -CREATE FUNCTION spi_test() RETURNS void -LANGUAGE plperl -TRANSFORM FOR TYPE bool -AS $$ -my $rv = spi_exec_query('SELECT true t, false f, NULL n')->{rows}->[0]; - -die("TRUE mistransformed to UNDEF in SPI") if (!defined ($rv->{t})); -die("FALSE mistransformed to UNDEF in SPI") if (!defined ($rv->{f})); -die("NULL mistransformed in SPI") if (defined ($rv->{n})); -die("TRUE mistransformed in SPI") if (!$rv->{t}); -die("FALSE mistransformed in SPI") if ($rv->{f}); -$$; - -SELECT spi_test(); - -DROP EXTENSION plperl CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbool_plperl%2Fsql%2Fbool_plperlu.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbool_plperl%2Fsql%2Fbool_plperlu.sql deleted file mode 100644 index 1480a04330..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbool_plperl%2Fsql%2Fbool_plperlu.sql +++ /dev/null @@ -1,70 +0,0 @@ -CREATE EXTENSION bool_plperlu CASCADE; - ---- test transforming from perl - -CREATE FUNCTION perl2int(int) RETURNS bool -LANGUAGE plperlu -TRANSFORM FOR TYPE bool -AS $$ -return shift; -$$; - -CREATE FUNCTION perl2text(text) RETURNS bool -LANGUAGE plperlu -TRANSFORM FOR TYPE bool -AS $$ -return shift; -$$; - -CREATE FUNCTION perl2undef() RETURNS bool -LANGUAGE plperlu -TRANSFORM FOR TYPE bool -AS $$ -return undef; -$$; - -SELECT perl2int(1); -SELECT perl2int(0); -SELECT perl2text('foo'); -SELECT perl2text(''); -SELECT perl2undef() IS NULL AS p; - ---- test transforming to perl - -CREATE FUNCTION bool2perl(bool, bool, bool) RETURNS void -LANGUAGE plperlu -TRANSFORM FOR TYPE bool, for type boolean -- duplicate to test ruleutils -AS $$ -my ($x, $y, $z) = @_; - -die("NULL mistransformed") if (defined($z)); -die("TRUE mistransformed to UNDEF") if (!defined($x)); -die("FALSE mistransformed to UNDEF") if (!defined($y)); -die("TRUE mistransformed") if (!$x); -die("FALSE mistransformed") if ($y); -$$; - -SELECT bool2perl (true, false, NULL); - ---- test ruleutils - -\sf bool2perl - ---- test selecting bool through SPI - -CREATE FUNCTION spi_test() RETURNS void -LANGUAGE plperlu -TRANSFORM FOR TYPE bool -AS $$ -my $rv = spi_exec_query('SELECT true t, false f, NULL n')->{rows}->[0]; - -die("TRUE mistransformed to UNDEF in SPI") if (!defined ($rv->{t})); -die("FALSE mistransformed to UNDEF in SPI") if (!defined ($rv->{f})); -die("NULL mistransformed in SPI") if (defined ($rv->{n})); -die("TRUE mistransformed in SPI") if (!$rv->{t}); -die("FALSE mistransformed in SPI") if ($rv->{f}); -$$; - -SELECT spi_test(); - -DROP EXTENSION plperlu CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbtree_gin%2Fsql%2Fbool.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbtree_gin%2Fsql%2Fbool.sql deleted file mode 100644 index dad2ff32b8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbtree_gin%2Fsql%2Fbool.sql +++ /dev/null @@ -1,27 +0,0 @@ -set enable_seqscan=off; - -CREATE TABLE test_bool ( - i boolean -); - -INSERT INTO test_bool VALUES (false),(true),(null); - -CREATE INDEX idx_bool ON test_bool USING gin (i); - -SELECT * FROM test_bool WHERE i=true ORDER BY i; -SELECT * FROM test_bool WHERE i>true ORDER BY i; - -SELECT * FROM test_bool WHERE i=false ORDER BY i; -SELECT * FROM test_bool WHERE i>false ORDER BY i; - -EXPLAIN (COSTS OFF) SELECT * FROM test_bool WHERE i=true ORDER BY i; -EXPLAIN (COSTS OFF) SELECT * FROM test_bool WHERE i>true ORDER BY i; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbtree_gist%2Fbtree_gist--1.1--1.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbtree_gist%2Fbtree_gist--1.1--1.2.sql deleted file mode 100644 index d5a8c6cf90..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fbtree_gist%2Fbtree_gist--1.1--1.2.sql +++ /dev/null @@ -1,79 +0,0 @@ -/* contrib/btree_gist/btree_gist--1.1--1.2.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION btree_gist UPDATE TO '1.2'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. - -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('gbt_oid_distance(internal,oid,int2,oid)', '{internal,oid,int2,oid,internal}'), -('gbt_oid_union(bytea,internal)', '{internal,internal}'), -('gbt_oid_same(internal,internal,internal)', '{SCH.gbtreekey8,SCH.gbtreekey8,internal}'), -('gbt_int2_distance(internal,int2,int2,oid)', '{internal,int2,int2,oid,internal}'), -('gbt_int2_union(bytea,internal)', '{internal,internal}'), -('gbt_int2_same(internal,internal,internal)', '{SCH.gbtreekey4,SCH.gbtreekey4,internal}'), -('gbt_int4_distance(internal,int4,int2,oid)', '{internal,int4,int2,oid,internal}'), -('gbt_int4_union(bytea,internal)', '{internal,internal}'), -('gbt_int4_same(internal,internal,internal)', '{SCH.gbtreekey8,SCH.gbtreekey8,internal}'), -('gbt_int8_distance(internal,int8,int2,oid)', '{internal,int8,int2,oid,internal}'), -('gbt_int8_union(bytea,internal)', '{internal,internal}'), -('gbt_int8_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}'), -('gbt_float4_distance(internal,float4,int2,oid)', '{internal,float4,int2,oid,internal}'), -('gbt_float4_union(bytea,internal)', '{internal,internal}'), -('gbt_float4_same(internal,internal,internal)', '{SCH.gbtreekey8,SCH.gbtreekey8,internal}'), -('gbt_float8_distance(internal,float8,int2,oid)', '{internal,float8,int2,oid,internal}'), -('gbt_float8_union(bytea,internal)', '{internal,internal}'), -('gbt_float8_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}'), -('gbt_ts_distance(internal,timestamp,int2,oid)', '{internal,timestamp,int2,oid,internal}'), -('gbt_tstz_distance(internal,timestamptz,int2,oid)', '{internal,timestamptz,int2,oid,internal}'), -('gbt_ts_union(bytea,internal)', '{internal,internal}'), -('gbt_ts_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}'), -('gbt_time_distance(internal,time,int2,oid)', '{internal,time,int2,oid,internal}'), -('gbt_time_union(bytea,internal)', '{internal,internal}'), -('gbt_time_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}'), -('gbt_date_distance(internal,date,int2,oid)', '{internal,date,int2,oid,internal}'), -('gbt_date_union(bytea,internal)', '{internal,internal}'), -('gbt_date_same(internal,internal,internal)', '{SCH.gbtreekey8,SCH.gbtreekey8,internal}'), -('gbt_intv_distance(internal,interval,int2,oid)', '{internal,interval,int2,oid,internal}'), -('gbt_intv_union(bytea,internal)', '{internal,internal}'), -('gbt_intv_same(internal,internal,internal)', '{SCH.gbtreekey32,SCH.gbtreekey32,internal}'), -('gbt_cash_distance(internal,money,int2,oid)', '{internal,money,int2,oid,internal}'), -('gbt_cash_union(bytea,internal)', '{internal,internal}'), -('gbt_cash_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}'), -('gbt_macad_union(bytea,internal)', '{internal,internal}'), -('gbt_macad_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}'), -('gbt_text_union(bytea,internal)', '{internal,internal}'), -('gbt_text_same(internal,internal,internal)', '{SCH.gbtreekey_var,SCH.gbtreekey_var,internal}'), -('gbt_bytea_union(bytea,internal)', '{internal,internal}'), -('gbt_bytea_same(internal,internal,internal)', '{SCH.gbtreekey_var,SCH.gbtreekey_var,internal}'), -('gbt_numeric_union(bytea,internal)', '{internal,internal}'), -('gbt_numeric_same(internal,internal,internal)', '{SCH.gbtreekey_var,SCH.gbtreekey_var,internal}'), -('gbt_bit_union(bytea,internal)', '{internal,internal}'), -('gbt_bit_same(internal,internal,internal)', '{SCH.gbtreekey_var,SCH.gbtreekey_var,internal}'), -('gbt_inet_union(bytea,internal)', '{internal,internal}'), -('gbt_inet_same(internal,internal,internal)', '{SCH.gbtreekey16,SCH.gbtreekey16,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.0--1.1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.0--1.1.sql deleted file mode 100644 index e06627e025..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.0--1.1.sql +++ /dev/null @@ -1,21 +0,0 @@ -/* contrib/citext/citext--1.0--1.1.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION citext UPDATE TO '1.1'" to load this file. \quit - -/* First we have to remove them from the extension */ -ALTER EXTENSION citext DROP FUNCTION regexp_matches( citext, citext ); -ALTER EXTENSION citext DROP FUNCTION regexp_matches( citext, citext, text ); - -/* Then we can drop them */ -DROP FUNCTION regexp_matches( citext, citext ); -DROP FUNCTION regexp_matches( citext, citext, text ); - -/* Now redefine */ -CREATE FUNCTION regexp_matches( citext, citext ) RETURNS SETOF TEXT[] AS $$ - SELECT pg_catalog.regexp_matches( $1::pg_catalog.text, $2::pg_catalog.text, 'i' ); -$$ LANGUAGE SQL IMMUTABLE STRICT ROWS 1; - -CREATE FUNCTION regexp_matches( citext, citext, text ) RETURNS SETOF TEXT[] AS $$ - SELECT pg_catalog.regexp_matches( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN $3 || 'i' ELSE $3 END ); -$$ LANGUAGE SQL IMMUTABLE STRICT ROWS 10; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.1--1.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.1--1.2.sql deleted file mode 100644 index a8bba860a1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.1--1.2.sql +++ /dev/null @@ -1,68 +0,0 @@ -/* contrib/citext/citext--1.1--1.2.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION citext UPDATE TO '1.2'" to load this file. \quit - -ALTER FUNCTION citextin(cstring) PARALLEL SAFE; -ALTER FUNCTION citextout(citext) PARALLEL SAFE; -ALTER FUNCTION citextrecv(internal) PARALLEL SAFE; -ALTER FUNCTION citextsend(citext) PARALLEL SAFE; -ALTER FUNCTION citext(bpchar) PARALLEL SAFE; -ALTER FUNCTION citext(boolean) PARALLEL SAFE; -ALTER FUNCTION citext(inet) PARALLEL SAFE; -ALTER FUNCTION citext_eq(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_ne(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_lt(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_le(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_gt(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_ge(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_cmp(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_hash(citext) PARALLEL SAFE; -ALTER FUNCTION citext_smaller(citext, citext) PARALLEL SAFE; -ALTER FUNCTION citext_larger(citext, citext) PARALLEL SAFE; -ALTER FUNCTION texticlike(citext, citext) PARALLEL SAFE; -ALTER FUNCTION texticnlike(citext, citext) PARALLEL SAFE; -ALTER FUNCTION texticregexeq(citext, citext) PARALLEL SAFE; -ALTER FUNCTION texticregexne(citext, citext) PARALLEL SAFE; -ALTER FUNCTION texticlike(citext, text) PARALLEL SAFE; -ALTER FUNCTION texticnlike(citext, text) PARALLEL SAFE; -ALTER FUNCTION texticregexeq(citext, text) PARALLEL SAFE; -ALTER FUNCTION texticregexne(citext, text) PARALLEL SAFE; -ALTER FUNCTION regexp_matches(citext, citext) PARALLEL SAFE; -ALTER FUNCTION regexp_matches(citext, citext, text) PARALLEL SAFE; -ALTER FUNCTION regexp_replace(citext, citext, text) PARALLEL SAFE; -ALTER FUNCTION regexp_replace(citext, citext, text, text) PARALLEL SAFE; -ALTER FUNCTION regexp_split_to_array(citext, citext) PARALLEL SAFE; -ALTER FUNCTION regexp_split_to_array(citext, citext, text) PARALLEL SAFE; -ALTER FUNCTION regexp_split_to_table(citext, citext) PARALLEL SAFE; -ALTER FUNCTION regexp_split_to_table(citext, citext, text) PARALLEL SAFE; -ALTER FUNCTION strpos(citext, citext) PARALLEL SAFE; -ALTER FUNCTION replace(citext, citext, citext) PARALLEL SAFE; -ALTER FUNCTION split_part(citext, citext, int) PARALLEL SAFE; -ALTER FUNCTION translate(citext, citext, text) PARALLEL SAFE; - --- We have to update aggregates the hard way for lack of ALTER support -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_proc SET proparallel = 's' -WHERE oid = (my_schema || '.min(' || my_schema || '.citext)')::pg_catalog.regprocedure; - -UPDATE pg_proc SET proparallel = 's' -WHERE oid = (my_schema || '.max(' || my_schema || '.citext)')::pg_catalog.regprocedure; - -UPDATE pg_aggregate SET aggcombinefn = (my_schema || '.citext_smaller')::regproc -WHERE aggfnoid = (my_schema || '.max(' || my_schema || '.citext)')::pg_catalog.regprocedure; - -UPDATE pg_aggregate SET aggcombinefn = (my_schema || '.citext_larger')::regproc -WHERE aggfnoid = (my_schema || '.max(' || my_schema || '.citext)')::pg_catalog.regprocedure; - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.2--1.3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.2--1.3.sql deleted file mode 100644 index 24a71452c6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.2--1.3.sql +++ /dev/null @@ -1,21 +0,0 @@ -/* contrib/citext/citext--1.2--1.3.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION citext UPDATE TO '1.3'" to load this file. \quit - --- We have to update aggregates the hard way for lack of ALTER support -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_aggregate SET aggcombinefn = (my_schema || '.citext_smaller')::regproc -WHERE aggfnoid = (my_schema || '.min(' || my_schema || '.citext)')::pg_catalog.regprocedure; - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.3--1.4.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.3--1.4.sql deleted file mode 100644 index 7b36651186..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.3--1.4.sql +++ /dev/null @@ -1,12 +0,0 @@ -/* contrib/citext/citext--1.3--1.4.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION citext UPDATE TO '1.4'" to load this file. \quit - -CREATE FUNCTION regexp_match( citext, citext ) RETURNS TEXT[] AS $$ - SELECT pg_catalog.regexp_match( $1::pg_catalog.text, $2::pg_catalog.text, 'i' ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_match( citext, citext, text ) RETURNS TEXT[] AS $$ - SELECT pg_catalog.regexp_match( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN $3 || 'i' ELSE $3 END ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.4.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.4.sql deleted file mode 100644 index 7b06198935..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcitext%2Fcitext--1.4.sql +++ /dev/null @@ -1,501 +0,0 @@ -/* contrib/citext/citext--1.4.sql */ - --- complain if script is sourced in psql, rather than via CREATE EXTENSION -\echo Use "CREATE EXTENSION citext" to load this file. \quit - --- --- PostgreSQL code for CITEXT. --- --- Most I/O functions, and a few others, piggyback on the "text" type --- functions via the implicit cast to text. --- - --- --- Shell type to keep things a bit quieter. --- - -CREATE TYPE citext; - --- --- Input and output functions. --- -CREATE FUNCTION citextin(cstring) -RETURNS citext -AS 'textin' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citextout(citext) -RETURNS cstring -AS 'textout' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citextrecv(internal) -RETURNS citext -AS 'textrecv' -LANGUAGE internal STABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citextsend(citext) -RETURNS bytea -AS 'textsend' -LANGUAGE internal STABLE STRICT PARALLEL SAFE; - --- --- The type itself. --- - -CREATE TYPE citext ( - INPUT = citextin, - OUTPUT = citextout, - RECEIVE = citextrecv, - SEND = citextsend, - INTERNALLENGTH = VARIABLE, - STORAGE = extended, - -- make it a non-preferred member of string type category - CATEGORY = 'S', - PREFERRED = false, - COLLATABLE = true -); - --- --- Type casting functions for those situations where the I/O casts don't --- automatically kick in. --- - -CREATE FUNCTION citext(bpchar) -RETURNS citext -AS 'rtrim1' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext(boolean) -RETURNS citext -AS 'booltext' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext(inet) -RETURNS citext -AS 'network_show' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - --- --- Implicit and assignment type casts. --- - -CREATE CAST (citext AS text) WITHOUT FUNCTION AS IMPLICIT; -CREATE CAST (citext AS varchar) WITHOUT FUNCTION AS IMPLICIT; -CREATE CAST (citext AS bpchar) WITHOUT FUNCTION AS ASSIGNMENT; -CREATE CAST (text AS citext) WITHOUT FUNCTION AS ASSIGNMENT; -CREATE CAST (varchar AS citext) WITHOUT FUNCTION AS ASSIGNMENT; -CREATE CAST (bpchar AS citext) WITH FUNCTION citext(bpchar) AS ASSIGNMENT; -CREATE CAST (boolean AS citext) WITH FUNCTION citext(boolean) AS ASSIGNMENT; -CREATE CAST (inet AS citext) WITH FUNCTION citext(inet) AS ASSIGNMENT; - --- --- Operator Functions. --- - -CREATE FUNCTION citext_eq( citext, citext ) -RETURNS bool -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext_ne( citext, citext ) -RETURNS bool -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext_lt( citext, citext ) -RETURNS bool -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext_le( citext, citext ) -RETURNS bool -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext_gt( citext, citext ) -RETURNS bool -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext_ge( citext, citext ) -RETURNS bool -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - --- --- Operators. --- - -CREATE OPERATOR = ( - LEFTARG = CITEXT, - RIGHTARG = CITEXT, - COMMUTATOR = =, - NEGATOR = <>, - PROCEDURE = citext_eq, - RESTRICT = eqsel, - JOIN = eqjoinsel, - HASHES, - MERGES -); - -CREATE OPERATOR <> ( - LEFTARG = CITEXT, - RIGHTARG = CITEXT, - NEGATOR = =, - COMMUTATOR = <>, - PROCEDURE = citext_ne, - RESTRICT = neqsel, - JOIN = neqjoinsel -); - -CREATE OPERATOR < ( - LEFTARG = CITEXT, - RIGHTARG = CITEXT, - NEGATOR = >=, - COMMUTATOR = >, - PROCEDURE = citext_lt, - RESTRICT = scalarltsel, - JOIN = scalarltjoinsel -); - -CREATE OPERATOR <= ( - LEFTARG = CITEXT, - RIGHTARG = CITEXT, - NEGATOR = >, - COMMUTATOR = >=, - PROCEDURE = citext_le, - RESTRICT = scalarltsel, - JOIN = scalarltjoinsel -); - -CREATE OPERATOR >= ( - LEFTARG = CITEXT, - RIGHTARG = CITEXT, - NEGATOR = <, - COMMUTATOR = <=, - PROCEDURE = citext_ge, - RESTRICT = scalargtsel, - JOIN = scalargtjoinsel -); - -CREATE OPERATOR > ( - LEFTARG = CITEXT, - RIGHTARG = CITEXT, - NEGATOR = <=, - COMMUTATOR = <, - PROCEDURE = citext_gt, - RESTRICT = scalargtsel, - JOIN = scalargtjoinsel -); - --- --- Support functions for indexing. --- - -CREATE FUNCTION citext_cmp(citext, citext) -RETURNS int4 -AS 'MODULE_PATHNAME' -LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE; - -CREATE FUNCTION citext_hash(citext) -RETURNS int4 -AS 'MODULE_PATHNAME' -LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE; - --- --- The btree indexing operator class. --- - -CREATE OPERATOR CLASS citext_ops -DEFAULT FOR TYPE CITEXT USING btree AS - OPERATOR 1 < (citext, citext), - OPERATOR 2 <= (citext, citext), - OPERATOR 3 = (citext, citext), - OPERATOR 4 >= (citext, citext), - OPERATOR 5 > (citext, citext), - FUNCTION 1 citext_cmp(citext, citext); - --- --- The hash indexing operator class. --- - -CREATE OPERATOR CLASS citext_ops -DEFAULT FOR TYPE citext USING hash AS - OPERATOR 1 = (citext, citext), - FUNCTION 1 citext_hash(citext); - --- --- Aggregates. --- - -CREATE FUNCTION citext_smaller(citext, citext) -RETURNS citext -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION citext_larger(citext, citext) -RETURNS citext -AS 'MODULE_PATHNAME' -LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE; - -CREATE AGGREGATE min(citext) ( - SFUNC = citext_smaller, - STYPE = citext, - SORTOP = <, - PARALLEL = SAFE, - COMBINEFUNC = citext_smaller -); - -CREATE AGGREGATE max(citext) ( - SFUNC = citext_larger, - STYPE = citext, - SORTOP = >, - PARALLEL = SAFE, - COMBINEFUNC = citext_larger -); - --- --- CITEXT pattern matching. --- - -CREATE FUNCTION texticlike(citext, citext) -RETURNS bool AS 'texticlike' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION texticnlike(citext, citext) -RETURNS bool AS 'texticnlike' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION texticregexeq(citext, citext) -RETURNS bool AS 'texticregexeq' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION texticregexne(citext, citext) -RETURNS bool AS 'texticregexne' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE OPERATOR ~ ( - PROCEDURE = texticregexeq, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = !~, - RESTRICT = icregexeqsel, - JOIN = icregexeqjoinsel -); - -CREATE OPERATOR ~* ( - PROCEDURE = texticregexeq, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = !~*, - RESTRICT = icregexeqsel, - JOIN = icregexeqjoinsel -); - -CREATE OPERATOR !~ ( - PROCEDURE = texticregexne, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = ~, - RESTRICT = icregexnesel, - JOIN = icregexnejoinsel -); - -CREATE OPERATOR !~* ( - PROCEDURE = texticregexne, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = ~*, - RESTRICT = icregexnesel, - JOIN = icregexnejoinsel -); - -CREATE OPERATOR ~~ ( - PROCEDURE = texticlike, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = !~~, - RESTRICT = iclikesel, - JOIN = iclikejoinsel -); - -CREATE OPERATOR ~~* ( - PROCEDURE = texticlike, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = !~~*, - RESTRICT = iclikesel, - JOIN = iclikejoinsel -); - -CREATE OPERATOR !~~ ( - PROCEDURE = texticnlike, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = ~~, - RESTRICT = icnlikesel, - JOIN = icnlikejoinsel -); - -CREATE OPERATOR !~~* ( - PROCEDURE = texticnlike, - LEFTARG = citext, - RIGHTARG = citext, - NEGATOR = ~~*, - RESTRICT = icnlikesel, - JOIN = icnlikejoinsel -); - --- --- Matching citext to text. --- - -CREATE FUNCTION texticlike(citext, text) -RETURNS bool AS 'texticlike' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION texticnlike(citext, text) -RETURNS bool AS 'texticnlike' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION texticregexeq(citext, text) -RETURNS bool AS 'texticregexeq' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION texticregexne(citext, text) -RETURNS bool AS 'texticregexne' -LANGUAGE internal IMMUTABLE STRICT PARALLEL SAFE; - -CREATE OPERATOR ~ ( - PROCEDURE = texticregexeq, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = !~, - RESTRICT = icregexeqsel, - JOIN = icregexeqjoinsel -); - -CREATE OPERATOR ~* ( - PROCEDURE = texticregexeq, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = !~*, - RESTRICT = icregexeqsel, - JOIN = icregexeqjoinsel -); - -CREATE OPERATOR !~ ( - PROCEDURE = texticregexne, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = ~, - RESTRICT = icregexnesel, - JOIN = icregexnejoinsel -); - -CREATE OPERATOR !~* ( - PROCEDURE = texticregexne, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = ~*, - RESTRICT = icregexnesel, - JOIN = icregexnejoinsel -); - -CREATE OPERATOR ~~ ( - PROCEDURE = texticlike, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = !~~, - RESTRICT = iclikesel, - JOIN = iclikejoinsel -); - -CREATE OPERATOR ~~* ( - PROCEDURE = texticlike, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = !~~*, - RESTRICT = iclikesel, - JOIN = iclikejoinsel -); - -CREATE OPERATOR !~~ ( - PROCEDURE = texticnlike, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = ~~, - RESTRICT = icnlikesel, - JOIN = icnlikejoinsel -); - -CREATE OPERATOR !~~* ( - PROCEDURE = texticnlike, - LEFTARG = citext, - RIGHTARG = text, - NEGATOR = ~~*, - RESTRICT = icnlikesel, - JOIN = icnlikejoinsel -); - --- --- Matching citext in string comparison functions. --- XXX TODO Ideally these would be implemented in C. --- - -CREATE FUNCTION regexp_match( citext, citext ) RETURNS TEXT[] AS $$ - SELECT pg_catalog.regexp_match( $1::pg_catalog.text, $2::pg_catalog.text, 'i' ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_match( citext, citext, text ) RETURNS TEXT[] AS $$ - SELECT pg_catalog.regexp_match( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN $3 || 'i' ELSE $3 END ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_matches( citext, citext ) RETURNS SETOF TEXT[] AS $$ - SELECT pg_catalog.regexp_matches( $1::pg_catalog.text, $2::pg_catalog.text, 'i' ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE ROWS 1; - -CREATE FUNCTION regexp_matches( citext, citext, text ) RETURNS SETOF TEXT[] AS $$ - SELECT pg_catalog.regexp_matches( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN $3 || 'i' ELSE $3 END ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE ROWS 10; - -CREATE FUNCTION regexp_replace( citext, citext, text ) returns TEXT AS $$ - SELECT pg_catalog.regexp_replace( $1::pg_catalog.text, $2::pg_catalog.text, $3, 'i'); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_replace( citext, citext, text, text ) returns TEXT AS $$ - SELECT pg_catalog.regexp_replace( $1::pg_catalog.text, $2::pg_catalog.text, $3, CASE WHEN pg_catalog.strpos($4, 'c') = 0 THEN $4 || 'i' ELSE $4 END); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_split_to_array( citext, citext ) RETURNS TEXT[] AS $$ - SELECT pg_catalog.regexp_split_to_array( $1::pg_catalog.text, $2::pg_catalog.text, 'i' ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_split_to_array( citext, citext, text ) RETURNS TEXT[] AS $$ - SELECT pg_catalog.regexp_split_to_array( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN $3 || 'i' ELSE $3 END ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_split_to_table( citext, citext ) RETURNS SETOF TEXT AS $$ - SELECT pg_catalog.regexp_split_to_table( $1::pg_catalog.text, $2::pg_catalog.text, 'i' ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION regexp_split_to_table( citext, citext, text ) RETURNS SETOF TEXT AS $$ - SELECT pg_catalog.regexp_split_to_table( $1::pg_catalog.text, $2::pg_catalog.text, CASE WHEN pg_catalog.strpos($3, 'c') = 0 THEN $3 || 'i' ELSE $3 END ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION strpos( citext, citext ) RETURNS INT AS $$ - SELECT pg_catalog.strpos( pg_catalog.lower( $1::pg_catalog.text ), pg_catalog.lower( $2::pg_catalog.text ) ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION replace( citext, citext, citext ) RETURNS TEXT AS $$ - SELECT pg_catalog.regexp_replace( $1::pg_catalog.text, pg_catalog.regexp_replace($2::pg_catalog.text, '([^a-zA-Z_0-9])', E'\\\\\\1', 'g'), $3::pg_catalog.text, 'gi' ); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION split_part( citext, citext, int ) RETURNS TEXT AS $$ - SELECT (pg_catalog.regexp_split_to_array( $1::pg_catalog.text, pg_catalog.regexp_replace($2::pg_catalog.text, '([^a-zA-Z_0-9])', E'\\\\\\1', 'g'), 'i'))[$3]; -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; - -CREATE FUNCTION translate( citext, citext, text ) RETURNS TEXT AS $$ - SELECT pg_catalog.translate( pg_catalog.translate( $1::pg_catalog.text, pg_catalog.lower($2::pg_catalog.text), $3), pg_catalog.upper($2::pg_catalog.text), $3); -$$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcube%2Fcube--1.1--1.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcube%2Fcube--1.1--1.2.sql deleted file mode 100644 index 76aba239e5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcube%2Fcube--1.1--1.2.sql +++ /dev/null @@ -1,75 +0,0 @@ -/* contrib/cube/cube--1.1--1.2.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION cube UPDATE TO '1.2'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('g_cube_consistent(internal,SCH.cube,int4,oid,internal)', '{internal,SCH.cube,int2,oid,internal}'), -('g_cube_distance(internal,SCH.cube,smallint,oid)', '{internal,SCH.cube,smallint,oid,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER FUNCTION cube_in(cstring) PARALLEL SAFE; -ALTER FUNCTION cube(float8[], float8[]) PARALLEL SAFE; -ALTER FUNCTION cube(float8[]) PARALLEL SAFE; -ALTER FUNCTION cube_out(cube) PARALLEL SAFE; -ALTER FUNCTION cube_eq(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_ne(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_lt(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_gt(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_le(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_ge(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_cmp(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_contains(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_contained(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_overlap(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_union(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_inter(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_size(cube) PARALLEL SAFE; -ALTER FUNCTION cube_subset(cube, int4[]) PARALLEL SAFE; -ALTER FUNCTION cube_distance(cube, cube) PARALLEL SAFE; -ALTER FUNCTION distance_chebyshev(cube, cube) PARALLEL SAFE; -ALTER FUNCTION distance_taxicab(cube, cube) PARALLEL SAFE; -ALTER FUNCTION cube_dim(cube) PARALLEL SAFE; -ALTER FUNCTION cube_ll_coord(cube, int4) PARALLEL SAFE; -ALTER FUNCTION cube_ur_coord(cube, int4) PARALLEL SAFE; -ALTER FUNCTION cube_coord(cube, int4) PARALLEL SAFE; -ALTER FUNCTION cube_coord_llur(cube, int4) PARALLEL SAFE; -ALTER FUNCTION cube(float8) PARALLEL SAFE; -ALTER FUNCTION cube(float8, float8) PARALLEL SAFE; -ALTER FUNCTION cube(cube, float8) PARALLEL SAFE; -ALTER FUNCTION cube(cube, float8, float8) PARALLEL SAFE; -ALTER FUNCTION cube_is_point(cube) PARALLEL SAFE; -ALTER FUNCTION cube_enlarge(cube, float8, int4) PARALLEL SAFE; -ALTER FUNCTION g_cube_consistent(internal, cube, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_compress(internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_same(cube, cube, internal) PARALLEL SAFE; -ALTER FUNCTION g_cube_distance(internal, cube, smallint, oid, internal) PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcube%2Fcube--1.3--1.4.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcube%2Fcube--1.3--1.4.sql deleted file mode 100644 index 41629395df..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fcube%2Fcube--1.3--1.4.sql +++ /dev/null @@ -1,58 +0,0 @@ -/* contrib/cube/cube--1.3--1.4.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION cube UPDATE TO '1.4'" to load this file. \quit - --- --- Get rid of unnecessary compress and decompress support functions. --- --- To be allowed to drop the opclass entry for a support function, --- we must change the entry's dependency type from 'internal' to 'auto', --- as though it were a loose member of the opfamily rather than being --- bound into a particular opclass. There's no SQL command for that, --- so fake it with a manual update on pg_depend. --- -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_depend -SET deptype = 'a' -WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND objid = - (SELECT objid - FROM pg_catalog.pg_depend - WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass - AND (refobjid = (my_schema || '.g_cube_compress(pg_catalog.internal)')::pg_catalog.regprocedure)) - AND refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass - AND deptype = 'i'; - -UPDATE pg_catalog.pg_depend -SET deptype = 'a' -WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND objid = - (SELECT objid - FROM pg_catalog.pg_depend - WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass - AND (refobjid = (my_schema || '.g_cube_decompress(pg_catalog.internal)')::pg_catalog.regprocedure)) - AND refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass - AND deptype = 'i'; - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER OPERATOR FAMILY gist_cube_ops USING gist drop function 3 (cube); -ALTER EXTENSION cube DROP function g_cube_compress(pg_catalog.internal); -DROP FUNCTION g_cube_compress(pg_catalog.internal); - -ALTER OPERATOR FAMILY gist_cube_ops USING gist drop function 4 (cube); -ALTER EXTENSION cube DROP function g_cube_decompress(pg_catalog.internal); -DROP FUNCTION g_cube_decompress(pg_catalog.internal); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fdblink%2Fdblink--1.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fdblink%2Fdblink--1.2.sql deleted file mode 100644 index 405eccb0ff..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fdblink%2Fdblink--1.2.sql +++ /dev/null @@ -1,235 +0,0 @@ -/* contrib/dblink/dblink--1.2.sql */ - --- complain if script is sourced in psql, rather than via CREATE EXTENSION -\echo Use "CREATE EXTENSION dblink" to load this file. \quit - --- dblink_connect now restricts non-superusers to password --- authenticated connections -CREATE FUNCTION dblink_connect (text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_connect' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_connect (text, text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_connect' -LANGUAGE C STRICT PARALLEL RESTRICTED; - --- dblink_connect_u allows non-superusers to use --- non-password authenticated connections, but initially --- privileges are revoked from public -CREATE FUNCTION dblink_connect_u (text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_connect' -LANGUAGE C STRICT PARALLEL RESTRICTED SECURITY DEFINER; - -CREATE FUNCTION dblink_connect_u (text, text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_connect' -LANGUAGE C STRICT PARALLEL RESTRICTED SECURITY DEFINER; - -REVOKE ALL ON FUNCTION dblink_connect_u (text) FROM public; -REVOKE ALL ON FUNCTION dblink_connect_u (text, text) FROM public; - -CREATE FUNCTION dblink_disconnect () -RETURNS text -AS 'MODULE_PATHNAME','dblink_disconnect' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_disconnect (text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_disconnect' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_open (text, text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_open' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_open (text, text, boolean) -RETURNS text -AS 'MODULE_PATHNAME','dblink_open' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_open (text, text, text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_open' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_open (text, text, text, boolean) -RETURNS text -AS 'MODULE_PATHNAME','dblink_open' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_fetch (text, int) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_fetch' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_fetch (text, int, boolean) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_fetch' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_fetch (text, text, int) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_fetch' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_fetch (text, text, int, boolean) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_fetch' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_close (text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_close' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_close (text, boolean) -RETURNS text -AS 'MODULE_PATHNAME','dblink_close' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_close (text, text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_close' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_close (text, text, boolean) -RETURNS text -AS 'MODULE_PATHNAME','dblink_close' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink (text, text) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_record' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink (text, text, boolean) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_record' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink (text) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_record' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink (text, boolean) -RETURNS setof record -AS 'MODULE_PATHNAME','dblink_record' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_exec (text, text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_exec' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_exec (text, text, boolean) -RETURNS text -AS 'MODULE_PATHNAME','dblink_exec' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_exec (text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_exec' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_exec (text,boolean) -RETURNS text -AS 'MODULE_PATHNAME','dblink_exec' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE TYPE dblink_pkey_results AS (position int, colname text); - -CREATE FUNCTION dblink_get_pkey (text) -RETURNS setof dblink_pkey_results -AS 'MODULE_PATHNAME','dblink_get_pkey' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_build_sql_insert (text, int2vector, int, _text, _text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_build_sql_insert' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_build_sql_delete (text, int2vector, int, _text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_build_sql_delete' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_build_sql_update (text, int2vector, int, _text, _text) -RETURNS text -AS 'MODULE_PATHNAME','dblink_build_sql_update' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_current_query () -RETURNS text -AS 'MODULE_PATHNAME','dblink_current_query' -LANGUAGE C PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_send_query(text, text) -RETURNS int4 -AS 'MODULE_PATHNAME', 'dblink_send_query' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_is_busy(text) -RETURNS int4 -AS 'MODULE_PATHNAME', 'dblink_is_busy' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_get_result(text) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'dblink_get_result' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_get_result(text, bool) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'dblink_get_result' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_get_connections() -RETURNS text[] -AS 'MODULE_PATHNAME', 'dblink_get_connections' -LANGUAGE C PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_cancel_query(text) -RETURNS text -AS 'MODULE_PATHNAME', 'dblink_cancel_query' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_error_message(text) -RETURNS text -AS 'MODULE_PATHNAME', 'dblink_error_message' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_get_notify( - OUT notify_name TEXT, - OUT be_pid INT4, - OUT extra TEXT -) -RETURNS setof record -AS 'MODULE_PATHNAME', 'dblink_get_notify' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -CREATE FUNCTION dblink_get_notify( - conname TEXT, - OUT notify_name TEXT, - OUT be_pid INT4, - OUT extra TEXT -) -RETURNS setof record -AS 'MODULE_PATHNAME', 'dblink_get_notify' -LANGUAGE C STRICT PARALLEL RESTRICTED; - -/* New stuff in 1.1 begins here */ - -CREATE FUNCTION dblink_fdw_validator( - options text[], - catalog oid -) -RETURNS void -AS 'MODULE_PATHNAME', 'dblink_fdw_validator' -LANGUAGE C STRICT PARALLEL SAFE; - -CREATE FOREIGN DATA WRAPPER dblink_fdw VALIDATOR dblink_fdw_validator; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fdblink%2Fsql%2Fdblink.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fdblink%2Fsql%2Fdblink.sql deleted file mode 100644 index e560260bfc..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fdblink%2Fsql%2Fdblink.sql +++ /dev/null @@ -1,629 +0,0 @@ -CREATE EXTENSION dblink; - --- directory paths and dlsuffix are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - --- create some functions needed for tests -CREATE FUNCTION setenv(text, text) - RETURNS void - AS :'regresslib', 'regress_setenv' - LANGUAGE C STRICT; - -CREATE FUNCTION wait_pid(int) - RETURNS void - AS :'regresslib' - LANGUAGE C STRICT; - -\set path :abs_srcdir '/' -\set fnbody 'SELECT setenv(''PGSERVICEFILE'', ' :'path' ' || $1)' -CREATE FUNCTION set_pgservicefile(text) RETURNS void LANGUAGE SQL - AS :'fnbody'; - --- want context for notices -\set SHOW_CONTEXT always - -CREATE TABLE foo(f1 int, f2 text, f3 text[], primary key (f1,f2)); -INSERT INTO foo VALUES (0,'a','{"a0","b0","c0"}'); -INSERT INTO foo VALUES (1,'b','{"a1","b1","c1"}'); -INSERT INTO foo VALUES (2,'c','{"a2","b2","c2"}'); -INSERT INTO foo VALUES (3,'d','{"a3","b3","c3"}'); -INSERT INTO foo VALUES (4,'e','{"a4","b4","c4"}'); -INSERT INTO foo VALUES (5,'f','{"a5","b5","c5"}'); -INSERT INTO foo VALUES (6,'g','{"a6","b6","c6"}'); -INSERT INTO foo VALUES (7,'h','{"a7","b7","c7"}'); -INSERT INTO foo VALUES (8,'i','{"a8","b8","c8"}'); -INSERT INTO foo VALUES (9,'j','{"a9","b9","c9"}'); - --- misc utilities - --- list the primary key fields -SELECT * -FROM dblink_get_pkey('foo'); - --- build an insert statement based on a local tuple, --- replacing the primary key values with new ones -SELECT dblink_build_sql_insert('foo','1 2',2,'{"0", "a"}','{"99", "xyz"}'); --- too many pk fields, should fail -SELECT dblink_build_sql_insert('foo','1 2 3 4',4,'{"0", "a", "{a0,b0,c0}"}','{"99", "xyz", "{za0,zb0,zc0}"}'); - --- build an update statement based on a local tuple, --- replacing the primary key values with new ones -SELECT dblink_build_sql_update('foo','1 2',2,'{"0", "a"}','{"99", "xyz"}'); --- too many pk fields, should fail -SELECT dblink_build_sql_update('foo','1 2 3 4',4,'{"0", "a", "{a0,b0,c0}"}','{"99", "xyz", "{za0,zb0,zc0}"}'); - --- build a delete statement based on a local tuple, -SELECT dblink_build_sql_delete('foo','1 2',2,'{"0", "a"}'); --- too many pk fields, should fail -SELECT dblink_build_sql_delete('foo','1 2 3 4',4,'{"0", "a", "{a0,b0,c0}"}'); - --- repeat the test for table with primary key index with included columns -CREATE TABLE foo_1(f1 int, f2 text, f3 text[], primary key (f1,f2) include (f3)); -INSERT INTO foo_1 VALUES (0,'a','{"a0","b0","c0"}'); -INSERT INTO foo_1 VALUES (1,'b','{"a1","b1","c1"}'); -INSERT INTO foo_1 VALUES (2,'c','{"a2","b2","c2"}'); -INSERT INTO foo_1 VALUES (3,'d','{"a3","b3","c3"}'); -INSERT INTO foo_1 VALUES (4,'e','{"a4","b4","c4"}'); -INSERT INTO foo_1 VALUES (5,'f','{"a5","b5","c5"}'); -INSERT INTO foo_1 VALUES (6,'g','{"a6","b6","c6"}'); -INSERT INTO foo_1 VALUES (7,'h','{"a7","b7","c7"}'); -INSERT INTO foo_1 VALUES (8,'i','{"a8","b8","c8"}'); -INSERT INTO foo_1 VALUES (9,'j','{"a9","b9","c9"}'); - --- misc utilities - --- list the primary key fields -SELECT * -FROM dblink_get_pkey('foo_1'); - --- build an insert statement based on a local tuple, --- replacing the primary key values with new ones -SELECT dblink_build_sql_insert('foo_1','1 2',2,'{"0", "a"}','{"99", "xyz"}'); --- too many pk fields, should fail -SELECT dblink_build_sql_insert('foo_1','1 2 3 4',4,'{"0", "a", "{a0,b0,c0}"}','{"99", "xyz", "{za0,zb0,zc0}"}'); - --- build an update statement based on a local tuple, --- replacing the primary key values with new ones -SELECT dblink_build_sql_update('foo_1','1 2',2,'{"0", "a"}','{"99", "xyz"}'); --- too many pk fields, should fail -SELECT dblink_build_sql_update('foo_1','1 2 3 4',4,'{"0", "a", "{a0,b0,c0}"}','{"99", "xyz", "{za0,zb0,zc0}"}'); - --- build a delete statement based on a local tuple, -SELECT dblink_build_sql_delete('foo_1','1 2',2,'{"0", "a"}'); --- too many pk fields, should fail -SELECT dblink_build_sql_delete('foo_1','1 2 3 4',4,'{"0", "a", "{a0,b0,c0}"}'); - -DROP TABLE foo_1; - --- retest using a quoted and schema qualified table -CREATE SCHEMA "MySchema"; -CREATE TABLE "MySchema"."Foo"(f1 int, f2 text, f3 text[], primary key (f1,f2)); -INSERT INTO "MySchema"."Foo" VALUES (0,'a','{"a0","b0","c0"}'); - --- list the primary key fields -SELECT * -FROM dblink_get_pkey('"MySchema"."Foo"'); - --- build an insert statement based on a local tuple, --- replacing the primary key values with new ones -SELECT dblink_build_sql_insert('"MySchema"."Foo"','1 2',2,'{"0", "a"}','{"99", "xyz"}'); - --- build an update statement based on a local tuple, --- replacing the primary key values with new ones -SELECT dblink_build_sql_update('"MySchema"."Foo"','1 2',2,'{"0", "a"}','{"99", "xyz"}'); - --- build a delete statement based on a local tuple, -SELECT dblink_build_sql_delete('"MySchema"."Foo"','1 2',2,'{"0", "a"}'); - -CREATE FUNCTION connection_parameters() RETURNS text LANGUAGE SQL AS $f$ - SELECT $$dbname='$$||current_database()||$$' port=$$||current_setting('port'); -$f$; - --- regular old dblink -SELECT * -FROM dblink(connection_parameters(),'SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- should generate "connection not available" error -SELECT * -FROM dblink('SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- The first-level connection's backend will crash on exit given OpenLDAP --- [2.4.24, 2.4.31]. We won't see evidence of any crash until the victim --- process terminates and the postmaster responds. If process termination --- entails writing a core dump, that can take awhile. Wait for the process to --- vanish. At that point, the postmaster has called waitpid() on the crashed --- process, and it will accept no new connections until it has reinitialized --- the cluster. (We can't exploit pg_stat_activity, because the crash happens --- after the backend updates shared memory to reflect its impending exit.) -DO $pl$ -DECLARE - detail text; -BEGIN - PERFORM wait_pid(crash_pid) - FROM dblink(connection_parameters(), $$ - SELECT pg_backend_pid() FROM dblink( - 'service=test_ldap '||connection_parameters(), - -- This string concatenation is a hack to shoehorn a - -- set_pgservicefile call into the SQL statement. - 'SELECT 1' || set_pgservicefile('pg_service.conf') - ) t(c int) - $$) AS t(crash_pid int); -EXCEPTION WHEN OTHERS THEN - GET STACKED DIAGNOSTICS detail = PG_EXCEPTION_DETAIL; - -- Expected error in a non-LDAP build. - IF NOT detail LIKE 'syntax error in service file%' THEN RAISE; END IF; -END -$pl$; - --- create a persistent connection -SELECT dblink_connect(connection_parameters()); - --- use the persistent connection -SELECT * -FROM dblink('SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- open a cursor with bad SQL and fail_on_error set to false -SELECT dblink_open('rmt_foo_cursor','SELECT * FROM foobar',false); - --- reset remote transaction state -SELECT dblink_exec('ABORT'); - --- open a cursor -SELECT dblink_open('rmt_foo_cursor','SELECT * FROM foo'); - --- close the cursor -SELECT dblink_close('rmt_foo_cursor',false); - --- open the cursor again -SELECT dblink_open('rmt_foo_cursor','SELECT * FROM foo'); - --- fetch some data -SELECT * -FROM dblink_fetch('rmt_foo_cursor',4) AS t(a int, b text, c text[]); - -SELECT * -FROM dblink_fetch('rmt_foo_cursor',4) AS t(a int, b text, c text[]); - --- this one only finds two rows left -SELECT * -FROM dblink_fetch('rmt_foo_cursor',4) AS t(a int, b text, c text[]); - --- intentionally botch a fetch -SELECT * -FROM dblink_fetch('rmt_foobar_cursor',4,false) AS t(a int, b text, c text[]); - --- reset remote transaction state -SELECT dblink_exec('ABORT'); - --- close the wrong cursor -SELECT dblink_close('rmt_foobar_cursor',false); - --- should generate 'cursor "rmt_foo_cursor" not found' error -SELECT * -FROM dblink_fetch('rmt_foo_cursor',4) AS t(a int, b text, c text[]); - --- this time, 'cursor "rmt_foo_cursor" not found' as a notice -SELECT * -FROM dblink_fetch('rmt_foo_cursor',4,false) AS t(a int, b text, c text[]); - --- close the persistent connection -SELECT dblink_disconnect(); - --- should generate "connection not available" error -SELECT * -FROM dblink('SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- put more data into our table, first using arbitrary connection syntax --- but truncate the actual return value so we can use diff to check for success -SELECT substr(dblink_exec(connection_parameters(),'INSERT INTO foo VALUES(10,''k'',''{"a10","b10","c10"}'')'),1,6); - --- create a persistent connection -SELECT dblink_connect(connection_parameters()); - --- put more data into our table, using persistent connection syntax --- but truncate the actual return value so we can use diff to check for success -SELECT substr(dblink_exec('INSERT INTO foo VALUES(11,''l'',''{"a11","b11","c11"}'')'),1,6); - --- let's see it -SELECT * -FROM dblink('SELECT * FROM foo') AS t(a int, b text, c text[]); - --- bad remote select -SELECT * -FROM dblink('SELECT * FROM foobar',false) AS t(a int, b text, c text[]); - --- change some data -SELECT dblink_exec('UPDATE foo SET f3[2] = ''b99'' WHERE f1 = 11'); - --- let's see it -SELECT * -FROM dblink('SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE a = 11; - --- botch a change to some other data -SELECT dblink_exec('UPDATE foobar SET f3[2] = ''b99'' WHERE f1 = 11',false); - --- delete some data -SELECT dblink_exec('DELETE FROM foo WHERE f1 = 11'); - --- let's see it -SELECT * -FROM dblink('SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE a = 11; - --- close the persistent connection -SELECT dblink_disconnect(); - --- --- tests for the new named persistent connection syntax --- - --- should generate "missing "=" after "myconn" in connection info string" error -SELECT * -FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- create a named persistent connection -SELECT dblink_connect('myconn',connection_parameters()); - --- use the named persistent connection -SELECT * -FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- use the named persistent connection, but get it wrong -SELECT * -FROM dblink('myconn','SELECT * FROM foobar',false) AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- create a second named persistent connection --- should error with "duplicate connection name" -SELECT dblink_connect('myconn',connection_parameters()); - --- create a second named persistent connection with a new name -SELECT dblink_connect('myconn2',connection_parameters()); - --- use the second named persistent connection -SELECT * -FROM dblink('myconn2','SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- close the second named persistent connection -SELECT dblink_disconnect('myconn2'); - --- open a cursor incorrectly -SELECT dblink_open('myconn','rmt_foo_cursor','SELECT * FROM foobar',false); - --- reset remote transaction state -SELECT dblink_exec('myconn','ABORT'); - --- test opening cursor in a transaction -SELECT dblink_exec('myconn','BEGIN'); - --- an open transaction will prevent dblink_open() from opening its own -SELECT dblink_open('myconn','rmt_foo_cursor','SELECT * FROM foo'); - --- this should not commit the transaction because the client opened it -SELECT dblink_close('myconn','rmt_foo_cursor'); - --- this should succeed because we have an open transaction -SELECT dblink_exec('myconn','DECLARE xact_test CURSOR FOR SELECT * FROM foo'); - --- commit remote transaction -SELECT dblink_exec('myconn','COMMIT'); - --- test automatic transactions for multiple cursor opens -SELECT dblink_open('myconn','rmt_foo_cursor','SELECT * FROM foo'); - --- the second cursor -SELECT dblink_open('myconn','rmt_foo_cursor2','SELECT * FROM foo'); - --- this should not commit the transaction -SELECT dblink_close('myconn','rmt_foo_cursor2'); - --- this should succeed because we have an open transaction -SELECT dblink_exec('myconn','DECLARE xact_test CURSOR FOR SELECT * FROM foo'); - --- this should commit the transaction -SELECT dblink_close('myconn','rmt_foo_cursor'); - --- this should fail because there is no open transaction -SELECT dblink_exec('myconn','DECLARE xact_test CURSOR FOR SELECT * FROM foo'); - --- reset remote transaction state -SELECT dblink_exec('myconn','ABORT'); - --- open a cursor -SELECT dblink_open('myconn','rmt_foo_cursor','SELECT * FROM foo'); - --- fetch some data -SELECT * -FROM dblink_fetch('myconn','rmt_foo_cursor',4) AS t(a int, b text, c text[]); - -SELECT * -FROM dblink_fetch('myconn','rmt_foo_cursor',4) AS t(a int, b text, c text[]); - --- this one only finds three rows left -SELECT * -FROM dblink_fetch('myconn','rmt_foo_cursor',4) AS t(a int, b text, c text[]); - --- fetch some data incorrectly -SELECT * -FROM dblink_fetch('myconn','rmt_foobar_cursor',4,false) AS t(a int, b text, c text[]); - --- reset remote transaction state -SELECT dblink_exec('myconn','ABORT'); - --- should generate 'cursor "rmt_foo_cursor" not found' error -SELECT * -FROM dblink_fetch('myconn','rmt_foo_cursor',4) AS t(a int, b text, c text[]); - --- close the named persistent connection -SELECT dblink_disconnect('myconn'); - --- should generate "missing "=" after "myconn" in connection info string" error -SELECT * -FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE t.a > 7; - --- create a named persistent connection -SELECT dblink_connect('myconn',connection_parameters()); - --- put more data into our table, using named persistent connection syntax --- but truncate the actual return value so we can use diff to check for success -SELECT substr(dblink_exec('myconn','INSERT INTO foo VALUES(11,''l'',''{"a11","b11","c11"}'')'),1,6); - --- let's see it -SELECT * -FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]); - --- change some data -SELECT dblink_exec('myconn','UPDATE foo SET f3[2] = ''b99'' WHERE f1 = 11'); - --- let's see it -SELECT * -FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE a = 11; - --- delete some data -SELECT dblink_exec('myconn','DELETE FROM foo WHERE f1 = 11'); - --- let's see it -SELECT * -FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]) -WHERE a = 11; - --- close the named persistent connection -SELECT dblink_disconnect('myconn'); - --- close the named persistent connection again --- should get 'connection "myconn" not available' error -SELECT dblink_disconnect('myconn'); - --- test asynchronous queries -SELECT dblink_connect('dtest1', connection_parameters()); -SELECT * from - dblink_send_query('dtest1', 'select * from foo where f1 < 3') as t1; - -SELECT dblink_connect('dtest2', connection_parameters()); -SELECT * from - dblink_send_query('dtest2', 'select * from foo where f1 > 2 and f1 < 7') as t1; - -SELECT dblink_connect('dtest3', connection_parameters()); -SELECT * from - dblink_send_query('dtest3', 'select * from foo where f1 > 6') as t1; - -CREATE TEMPORARY TABLE result AS -(SELECT * from dblink_get_result('dtest1') as t1(f1 int, f2 text, f3 text[])) -UNION -(SELECT * from dblink_get_result('dtest2') as t2(f1 int, f2 text, f3 text[])) -UNION -(SELECT * from dblink_get_result('dtest3') as t3(f1 int, f2 text, f3 text[])) -ORDER by f1; - --- dblink_get_connections returns an array with elements in a machine-dependent --- ordering, so we must resort to unnesting and sorting for a stable result -create function unnest(anyarray) returns setof anyelement -language sql strict immutable as $$ -select $1[i] from generate_series(array_lower($1,1), array_upper($1,1)) as i -$$; - -SELECT * FROM unnest(dblink_get_connections()) ORDER BY 1; - -SELECT dblink_is_busy('dtest1'); - -SELECT dblink_disconnect('dtest1'); -SELECT dblink_disconnect('dtest2'); -SELECT dblink_disconnect('dtest3'); - -SELECT * from result; - -SELECT dblink_connect('dtest1', connection_parameters()); -SELECT * from - dblink_send_query('dtest1', 'select * from foo where f1 < 3') as t1; - -SELECT dblink_cancel_query('dtest1'); -SELECT dblink_error_message('dtest1'); -SELECT dblink_disconnect('dtest1'); - --- test foreign data wrapper functionality -CREATE ROLE regress_dblink_user; -DO $d$ - BEGIN - EXECUTE $$CREATE SERVER fdtest FOREIGN DATA WRAPPER dblink_fdw - OPTIONS (dbname '$$||current_database()||$$', - port '$$||current_setting('port')||$$' - )$$; - END; -$d$; - -CREATE USER MAPPING FOR public SERVER fdtest - OPTIONS (server 'localhost'); -- fail, can't specify server here -CREATE USER MAPPING FOR public SERVER fdtest OPTIONS (user :'USER'); - -GRANT USAGE ON FOREIGN SERVER fdtest TO regress_dblink_user; -GRANT EXECUTE ON FUNCTION dblink_connect_u(text, text) TO regress_dblink_user; - -SET SESSION AUTHORIZATION regress_dblink_user; --- should fail -SELECT dblink_connect('myconn', 'fdtest'); --- should succeed -SELECT dblink_connect_u('myconn', 'fdtest'); -SELECT * FROM dblink('myconn','SELECT * FROM foo') AS t(a int, b text, c text[]); - -\c - - -REVOKE USAGE ON FOREIGN SERVER fdtest FROM regress_dblink_user; -REVOKE EXECUTE ON FUNCTION dblink_connect_u(text, text) FROM regress_dblink_user; -DROP USER regress_dblink_user; -DROP USER MAPPING FOR public SERVER fdtest; -DROP SERVER fdtest; - --- should fail -ALTER FOREIGN DATA WRAPPER dblink_fdw OPTIONS (nonexistent 'fdw'); - --- test asynchronous notifications -SELECT dblink_connect(connection_parameters()); - ---should return listen -SELECT dblink_exec('LISTEN regression'); ---should return listen -SELECT dblink_exec('LISTEN foobar'); - -SELECT dblink_exec('NOTIFY regression'); -SELECT dblink_exec('NOTIFY foobar'); - -SELECT notify_name, be_pid = (select t.be_pid from dblink('select pg_backend_pid()') as t(be_pid int)) AS is_self_notify, extra from dblink_get_notify(); - -SELECT * from dblink_get_notify(); - -SELECT dblink_disconnect(); - --- test dropped columns in dblink_build_sql_insert, dblink_build_sql_update -CREATE TEMP TABLE test_dropped -( - col1 INT NOT NULL DEFAULT 111, - id SERIAL PRIMARY KEY, - col2 INT NOT NULL DEFAULT 112, - col2b INT NOT NULL DEFAULT 113 -); - -INSERT INTO test_dropped VALUES(default); - -ALTER TABLE test_dropped - DROP COLUMN col1, - DROP COLUMN col2, - ADD COLUMN col3 VARCHAR(10) NOT NULL DEFAULT 'foo', - ADD COLUMN col4 INT NOT NULL DEFAULT 42; - -SELECT dblink_build_sql_insert('test_dropped', '1', 1, - ARRAY['1'::TEXT], ARRAY['2'::TEXT]); - -SELECT dblink_build_sql_update('test_dropped', '1', 1, - ARRAY['1'::TEXT], ARRAY['2'::TEXT]); - -SELECT dblink_build_sql_delete('test_dropped', '1', 1, - ARRAY['2'::TEXT]); - --- test local mimicry of remote GUC values that affect datatype I/O -SET datestyle = ISO, MDY; -SET intervalstyle = postgres; -SET timezone = UTC; -SELECT dblink_connect('myconn',connection_parameters()); -SELECT dblink_exec('myconn', 'SET datestyle = GERMAN, DMY;'); - --- single row synchronous case -SELECT * -FROM dblink('myconn', - 'SELECT * FROM (VALUES (''12.03.2013 00:00:00+00'')) t') - AS t(a timestamptz); - --- multi-row synchronous case -SELECT * -FROM dblink('myconn', - 'SELECT * FROM - (VALUES (''12.03.2013 00:00:00+00''), - (''12.03.2013 00:00:00+00'')) t') - AS t(a timestamptz); - --- single-row asynchronous case -SELECT * -FROM dblink_send_query('myconn', - 'SELECT * FROM - (VALUES (''12.03.2013 00:00:00+00'')) t'); -CREATE TEMPORARY TABLE result AS -(SELECT * from dblink_get_result('myconn') as t(t timestamptz)) -UNION ALL -(SELECT * from dblink_get_result('myconn') as t(t timestamptz)); -SELECT * FROM result; -DROP TABLE result; - --- multi-row asynchronous case -SELECT * -FROM dblink_send_query('myconn', - 'SELECT * FROM - (VALUES (''12.03.2013 00:00:00+00''), - (''12.03.2013 00:00:00+00'')) t'); -CREATE TEMPORARY TABLE result AS -(SELECT * from dblink_get_result('myconn') as t(t timestamptz)) -UNION ALL -(SELECT * from dblink_get_result('myconn') as t(t timestamptz)) -UNION ALL -(SELECT * from dblink_get_result('myconn') as t(t timestamptz)); -SELECT * FROM result; -DROP TABLE result; - --- Try an ambiguous interval -SELECT dblink_exec('myconn', 'SET intervalstyle = sql_standard;'); -SELECT * -FROM dblink('myconn', - 'SELECT * FROM (VALUES (''-1 2:03:04'')) i') - AS i(i interval); - --- Try swapping to another format to ensure the GUCs are tracked --- properly through a change. -CREATE TEMPORARY TABLE result (t timestamptz); - -SELECT dblink_exec('myconn', 'SET datestyle = ISO, MDY;'); -INSERT INTO result - SELECT * - FROM dblink('myconn', - 'SELECT * FROM (VALUES (''03.12.2013 00:00:00+00'')) t') - AS t(a timestamptz); - -SELECT dblink_exec('myconn', 'SET datestyle = GERMAN, DMY;'); -INSERT INTO result - SELECT * - FROM dblink('myconn', - 'SELECT * FROM (VALUES (''12.03.2013 00:00:00+00'')) t') - AS t(a timestamptz); - -SELECT * FROM result; - -DROP TABLE result; - --- Check error throwing in dblink_fetch -SELECT dblink_open('myconn','error_cursor', - 'SELECT * FROM (VALUES (''1''), (''not an int'')) AS t(text);'); -SELECT * -FROM dblink_fetch('myconn','error_cursor', 1) AS t(i int); -SELECT * -FROM dblink_fetch('myconn','error_cursor', 1) AS t(i int); - --- Make sure that the local settings have retained their values in spite --- of shenanigans on the connection. -SHOW datestyle; -SHOW intervalstyle; - --- Clean up GUC-setting tests -SELECT dblink_disconnect('myconn'); -RESET datestyle; -RESET intervalstyle; -RESET timezone; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ffile_fdw%2Fsql%2Ffile_fdw.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ffile_fdw%2Fsql%2Ffile_fdw.sql deleted file mode 100644 index 563d824ccc..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ffile_fdw%2Fsql%2Ffile_fdw.sql +++ /dev/null @@ -1,261 +0,0 @@ --- --- Test foreign-data wrapper file_fdw. --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - --- Clean up in case a prior regression run failed -SET client_min_messages TO 'warning'; -DROP ROLE IF EXISTS regress_file_fdw_superuser, regress_file_fdw_user, regress_no_priv_user; -RESET client_min_messages; - -CREATE ROLE regress_file_fdw_superuser LOGIN SUPERUSER; -- is a superuser -CREATE ROLE regress_file_fdw_user LOGIN; -- has priv and user mapping -CREATE ROLE regress_no_priv_user LOGIN; -- has priv but no user mapping - --- Install file_fdw -CREATE EXTENSION file_fdw; - --- create function to filter unstable results of EXPLAIN -CREATE FUNCTION explain_filter(text) RETURNS setof text -LANGUAGE plpgsql AS -$$ -declare - ln text; -begin - for ln in execute $1 - loop - -- Remove the path portion of foreign file names - ln := regexp_replace(ln, 'Foreign File: .*/([a-z.]+)$', 'Foreign File: .../\1'); - return next ln; - end loop; -end; -$$; - --- regress_file_fdw_superuser owns fdw-related objects -SET ROLE regress_file_fdw_superuser; -CREATE SERVER file_server FOREIGN DATA WRAPPER file_fdw; - --- privilege tests -SET ROLE regress_file_fdw_user; -CREATE FOREIGN DATA WRAPPER file_fdw2 HANDLER file_fdw_handler VALIDATOR file_fdw_validator; -- ERROR -CREATE SERVER file_server2 FOREIGN DATA WRAPPER file_fdw; -- ERROR -CREATE USER MAPPING FOR regress_file_fdw_user SERVER file_server; -- ERROR - -SET ROLE regress_file_fdw_superuser; -GRANT USAGE ON FOREIGN SERVER file_server TO regress_file_fdw_user; - -SET ROLE regress_file_fdw_user; -CREATE USER MAPPING FOR regress_file_fdw_user SERVER file_server; - --- create user mappings and grant privilege to test users -SET ROLE regress_file_fdw_superuser; -CREATE USER MAPPING FOR regress_file_fdw_superuser SERVER file_server; -CREATE USER MAPPING FOR regress_no_priv_user SERVER file_server; - --- validator tests -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'xml'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', quote ':'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', escape ':'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', header 'true'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', quote ':'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'binary', escape ':'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter 'a'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', escape '-'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', quote '-', null '=-='); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter '-', null '=-='); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter '-', quote '-'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter '---'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', quote '---'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', escape '---'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter '\'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter '.'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter '1'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'text', delimiter 'a'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', delimiter ' -'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (format 'csv', null ' -'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server; -- ERROR - -\set filename :abs_srcdir '/data/agg.data' -CREATE FOREIGN TABLE agg_text ( - a int2 CHECK (a >= 0), - b float4 -) SERVER file_server -OPTIONS (format 'text', filename :'filename', delimiter ' ', null '\N'); -GRANT SELECT ON agg_text TO regress_file_fdw_user; - -\set filename :abs_srcdir '/data/agg.csv' -CREATE FOREIGN TABLE agg_csv ( - a int2, - b float4 -) SERVER file_server -OPTIONS (format 'csv', filename :'filename', header 'true', delimiter ';', quote '@', escape '"', null ''); -ALTER FOREIGN TABLE agg_csv ADD CHECK (a >= 0); - -\set filename :abs_srcdir '/data/agg.bad' -CREATE FOREIGN TABLE agg_bad ( - a int2, - b float4 -) SERVER file_server -OPTIONS (format 'csv', filename :'filename', header 'true', delimiter ';', quote '@', escape '"', null ''); -ALTER FOREIGN TABLE agg_bad ADD CHECK (a >= 0); - --- test header matching -\set filename :abs_srcdir '/data/list1.csv' -CREATE FOREIGN TABLE header_match ("1" int, foo text) SERVER file_server -OPTIONS (format 'csv', filename :'filename', delimiter ',', header 'match'); -SELECT * FROM header_match; -CREATE FOREIGN TABLE header_doesnt_match (a int, foo text) SERVER file_server -OPTIONS (format 'csv', filename :'filename', delimiter ',', header 'match'); -SELECT * FROM header_doesnt_match; -- ERROR - --- per-column options tests -\set filename :abs_srcdir '/data/text.csv' -CREATE FOREIGN TABLE text_csv ( - word1 text OPTIONS (force_not_null 'true'), - word2 text OPTIONS (force_not_null 'off'), - word3 text OPTIONS (force_null 'true'), - word4 text OPTIONS (force_null 'off') -) SERVER file_server -OPTIONS (format 'text', filename :'filename', null 'NULL'); -SELECT * FROM text_csv; -- ERROR -ALTER FOREIGN TABLE text_csv OPTIONS (SET format 'csv'); -\pset null _null_ -SELECT * FROM text_csv; - --- force_not_null and force_null can be used together on the same column -ALTER FOREIGN TABLE text_csv ALTER COLUMN word1 OPTIONS (force_null 'true'); -ALTER FOREIGN TABLE text_csv ALTER COLUMN word3 OPTIONS (force_not_null 'true'); - --- force_not_null is not allowed to be specified at any foreign object level: -ALTER FOREIGN DATA WRAPPER file_fdw OPTIONS (ADD force_not_null '*'); -- ERROR -ALTER SERVER file_server OPTIONS (ADD force_not_null '*'); -- ERROR -CREATE USER MAPPING FOR public SERVER file_server OPTIONS (force_not_null '*'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (force_not_null '*'); -- ERROR - --- force_null is not allowed to be specified at any foreign object level: -ALTER FOREIGN DATA WRAPPER file_fdw OPTIONS (ADD force_null '*'); -- ERROR -ALTER SERVER file_server OPTIONS (ADD force_null '*'); -- ERROR -CREATE USER MAPPING FOR public SERVER file_server OPTIONS (force_null '*'); -- ERROR -CREATE FOREIGN TABLE tbl () SERVER file_server OPTIONS (force_null '*'); -- ERROR - --- basic query tests -SELECT * FROM agg_text WHERE b > 10.0 ORDER BY a; -SELECT * FROM agg_csv ORDER BY a; -SELECT * FROM agg_csv c JOIN agg_text t ON (t.a = c.a) ORDER BY c.a; - --- error context report tests -SELECT * FROM agg_bad; -- ERROR - --- misc query tests -\t on -SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_csv'); -\t off -PREPARE st(int) AS SELECT * FROM agg_csv WHERE a = $1; -EXECUTE st(100); -EXECUTE st(100); -DEALLOCATE st; - --- tableoid -SELECT tableoid::regclass, b FROM agg_csv; - --- updates aren't supported -INSERT INTO agg_csv VALUES(1,2.0); -UPDATE agg_csv SET a = 1; -DELETE FROM agg_csv WHERE a = 100; --- but this should be allowed -SELECT * FROM agg_csv FOR UPDATE; - --- copy from isn't supported either -COPY agg_csv FROM STDIN; -12 3.4 -\. - --- constraint exclusion tests -\t on -SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_csv WHERE a < 0'); -\t off -SELECT * FROM agg_csv WHERE a < 0; -SET constraint_exclusion = 'on'; -\t on -SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_csv WHERE a < 0'); -\t off -SELECT * FROM agg_csv WHERE a < 0; -RESET constraint_exclusion; - --- table inheritance tests -CREATE TABLE agg (a int2, b float4); -ALTER FOREIGN TABLE agg_csv INHERIT agg; -SELECT tableoid::regclass, * FROM agg; -SELECT tableoid::regclass, * FROM agg_csv; -SELECT tableoid::regclass, * FROM ONLY agg; --- updates aren't supported -UPDATE agg SET a = 1; -DELETE FROM agg WHERE a = 100; --- but this should be allowed -SELECT tableoid::regclass, * FROM agg FOR UPDATE; -ALTER FOREIGN TABLE agg_csv NO INHERIT agg; -DROP TABLE agg; - --- declarative partitioning tests -SET ROLE regress_file_fdw_superuser; -CREATE TABLE pt (a int, b text) partition by list (a); -\set filename :abs_srcdir '/data/list1.csv' -CREATE FOREIGN TABLE p1 partition of pt for values in (1) SERVER file_server -OPTIONS (format 'csv', filename :'filename', delimiter ','); -CREATE TABLE p2 partition of pt for values in (2); -SELECT tableoid::regclass, * FROM pt; -SELECT tableoid::regclass, * FROM p1; -SELECT tableoid::regclass, * FROM p2; -\set filename :abs_srcdir '/data/list2.bad' -COPY pt FROM :'filename' with (format 'csv', delimiter ','); -- ERROR -\set filename :abs_srcdir '/data/list2.csv' -COPY pt FROM :'filename' with (format 'csv', delimiter ','); -SELECT tableoid::regclass, * FROM pt; -SELECT tableoid::regclass, * FROM p1; -SELECT tableoid::regclass, * FROM p2; -INSERT INTO pt VALUES (1, 'xyzzy'); -- ERROR -INSERT INTO pt VALUES (2, 'xyzzy'); -UPDATE pt set a = 1 where a = 2; -- ERROR -SELECT tableoid::regclass, * FROM pt; -SELECT tableoid::regclass, * FROM p1; -SELECT tableoid::regclass, * FROM p2; -DROP TABLE pt; - --- generated column tests -\set filename :abs_srcdir '/data/list1.csv' -CREATE FOREIGN TABLE gft1 (a int, b text, c text GENERATED ALWAYS AS ('foo') STORED) SERVER file_server -OPTIONS (format 'csv', filename :'filename', delimiter ','); -SELECT a, c FROM gft1; -DROP FOREIGN TABLE gft1; - --- privilege tests -SET ROLE regress_file_fdw_superuser; -SELECT * FROM agg_text ORDER BY a; -SET ROLE regress_file_fdw_user; -SELECT * FROM agg_text ORDER BY a; -SET ROLE regress_no_priv_user; -SELECT * FROM agg_text ORDER BY a; -- ERROR -SET ROLE regress_file_fdw_user; -\t on -SELECT explain_filter('EXPLAIN (VERBOSE, COSTS FALSE) SELECT * FROM agg_text WHERE a > 0'); -\t off --- file FDW allows foreign tables to be accessed without user mapping -DROP USER MAPPING FOR regress_file_fdw_user SERVER file_server; -SELECT * FROM agg_text ORDER BY a; - --- privilege tests for object -SET ROLE regress_file_fdw_superuser; -ALTER FOREIGN TABLE agg_text OWNER TO regress_file_fdw_user; -ALTER FOREIGN TABLE agg_text OPTIONS (SET format 'text'); -SET ROLE regress_file_fdw_user; -ALTER FOREIGN TABLE agg_text OPTIONS (SET format 'text'); -SET ROLE regress_file_fdw_superuser; - --- cleanup -RESET ROLE; -DROP EXTENSION file_fdw CASCADE; -DROP ROLE regress_file_fdw_superuser, regress_file_fdw_user, regress_no_priv_user; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore%2Fhstore--1.1--1.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore%2Fhstore--1.1--1.2.sql deleted file mode 100644 index cc69fc7f80..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore%2Fhstore--1.1--1.2.sql +++ /dev/null @@ -1,53 +0,0 @@ -/* contrib/hstore/hstore--1.1--1.2.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION hstore UPDATE TO '1.2'" to load this file. \quit - - --- A version of 1.1 was shipped with these objects mistakenly in 9.3.0. --- Therefore we only add them if we detect that they aren't already there and --- dependent on the extension. - -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - - PERFORM 1 - FROM pg_proc p - JOIN pg_depend d - ON p.proname = 'hstore_to_json_loose' - AND d.classid = 'pg_proc'::regclass - AND d.objid = p.oid - AND d.refclassid = 'pg_extension'::regclass - JOIN pg_extension x - ON d.refobjid = x.oid - AND x.extname = 'hstore'; - - IF NOT FOUND - THEN - PERFORM pg_catalog.set_config('search_path', old_path, true); - - CREATE FUNCTION hstore_to_json(hstore) - RETURNS json - AS 'MODULE_PATHNAME', 'hstore_to_json' - LANGUAGE C IMMUTABLE STRICT; - - CREATE CAST (hstore AS json) - WITH FUNCTION hstore_to_json(hstore); - - CREATE FUNCTION hstore_to_json_loose(hstore) - RETURNS json - AS 'MODULE_PATHNAME', 'hstore_to_json_loose' - LANGUAGE C IMMUTABLE STRICT; - - END IF; - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END; - -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore%2Fhstore--1.3--1.4.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore%2Fhstore--1.3--1.4.sql deleted file mode 100644 index 53f26f9fb8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore%2Fhstore--1.3--1.4.sql +++ /dev/null @@ -1,99 +0,0 @@ -/* contrib/hstore/hstore--1.3--1.4.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION hstore UPDATE TO '1.4'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('ghstore_same(internal,internal,internal)', '{SCH.ghstore,SCH.ghstore,internal}'), -('ghstore_consistent(internal,internal,int4,oid,internal)', '{internal,SCH.hstore,int2,oid,internal}'), -('gin_extract_hstore(internal,internal)', '{SCH.hstore,internal}'), -('gin_extract_hstore_query(internal,internal,int2,internal,internal)', '{SCH.hstore,internal,int2,internal,internal}'), -('gin_consistent_hstore(internal,int2,internal,int4,internal,internal)', '{internal,int2,SCH.hstore,int4,internal,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -UPDATE pg_catalog.pg_proc SET - prorettype = (my_schema || '.ghstore')::pg_catalog.regtype -WHERE oid = pg_catalog.to_regprocedure((my_schema || '.ghstore_union(internal,internal)')); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER FUNCTION hstore_in(cstring) PARALLEL SAFE; -ALTER FUNCTION hstore_out(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_recv(internal) PARALLEL SAFE; -ALTER FUNCTION hstore_send(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_version_diag(hstore) PARALLEL SAFE; -ALTER FUNCTION fetchval(hstore, text) PARALLEL SAFE; -ALTER FUNCTION slice_array(hstore, text[]) PARALLEL SAFE; -ALTER FUNCTION slice(hstore, text[]) PARALLEL SAFE; -ALTER FUNCTION isexists(hstore, text) PARALLEL SAFE; -ALTER FUNCTION exist(hstore, text) PARALLEL SAFE; -ALTER FUNCTION exists_any(hstore, text[]) PARALLEL SAFE; -ALTER FUNCTION exists_all(hstore, text[]) PARALLEL SAFE; -ALTER FUNCTION isdefined(hstore, text) PARALLEL SAFE; -ALTER FUNCTION defined(hstore, text) PARALLEL SAFE; -ALTER FUNCTION delete(hstore, text) PARALLEL SAFE; -ALTER FUNCTION delete(hstore, text[]) PARALLEL SAFE; -ALTER FUNCTION delete(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hs_concat(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hs_contains(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hs_contained(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION tconvert(text, text) PARALLEL SAFE; -ALTER FUNCTION hstore(text, text) PARALLEL SAFE; -ALTER FUNCTION hstore(text[], text[]) PARALLEL SAFE; -ALTER FUNCTION hstore(text[]) PARALLEL SAFE; -ALTER FUNCTION hstore_to_json(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_to_json_loose(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_to_jsonb(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_to_jsonb_loose(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore(record) PARALLEL SAFE; -ALTER FUNCTION hstore_to_array(hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_to_matrix(hstore) PARALLEL SAFE; -ALTER FUNCTION akeys(hstore) PARALLEL SAFE; -ALTER FUNCTION avals(hstore) PARALLEL SAFE; -ALTER FUNCTION skeys(hstore) PARALLEL SAFE; -ALTER FUNCTION svals(hstore) PARALLEL SAFE; -ALTER FUNCTION each(hstore) PARALLEL SAFE; -ALTER FUNCTION populate_record(anyelement, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_eq(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_ne(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_gt(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_ge(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_lt(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_le(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_cmp(hstore, hstore) PARALLEL SAFE; -ALTER FUNCTION hstore_hash(hstore) PARALLEL SAFE; -ALTER FUNCTION ghstore_in(cstring) PARALLEL SAFE; -ALTER FUNCTION ghstore_out(ghstore) PARALLEL SAFE; -ALTER FUNCTION ghstore_compress(internal) PARALLEL SAFE; -ALTER FUNCTION ghstore_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION ghstore_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION ghstore_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION ghstore_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION ghstore_same(ghstore, ghstore, internal) PARALLEL SAFE; -ALTER FUNCTION ghstore_consistent(internal, hstore, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION gin_extract_hstore(hstore, internal) PARALLEL SAFE; -ALTER FUNCTION gin_extract_hstore_query(hstore, internal, int2, internal, internal) PARALLEL SAFE; -ALTER FUNCTION gin_consistent_hstore(internal, int2, hstore, int4, internal, internal) PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plperl%2Fsql%2Fhstore_plperl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plperl%2Fsql%2Fhstore_plperl.sql deleted file mode 100644 index ad1db7eae1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plperl%2Fsql%2Fhstore_plperl.sql +++ /dev/null @@ -1,60 +0,0 @@ -CREATE EXTENSION hstore_plperl CASCADE; - -SELECT transforms.udt_schema, transforms.udt_name, - routine_schema, routine_name, - group_name, transform_type -FROM information_schema.transforms JOIN information_schema.routines - USING (specific_catalog, specific_schema, specific_name) -ORDER BY 1, 2, 5, 6; - - --- test perl -> hstore -CREATE FUNCTION test2() RETURNS hstore -LANGUAGE plperl -TRANSFORM FOR TYPE hstore -AS $$ -$val = {a => 1, b => 'boo', c => undef}; -return $val; -$$; - -SELECT test2(); - - --- test perl -> hstore[] -CREATE FUNCTION test2arr() RETURNS hstore[] -LANGUAGE plperl -TRANSFORM FOR TYPE hstore -AS $$ -$val = [{a => 1, b => 'boo', c => undef}, {d => 2}]; -return $val; -$$; - -SELECT test2arr(); - --- check error cases -CREATE OR REPLACE FUNCTION test2() RETURNS hstore -LANGUAGE plperl -TRANSFORM FOR TYPE hstore -AS $$ -return 42; -$$; - -SELECT test2(); - -CREATE OR REPLACE FUNCTION test2() RETURNS hstore -LANGUAGE plperl -TRANSFORM FOR TYPE hstore -AS $$ -return [1, 2]; -$$; - -SELECT test2(); - - -DROP FUNCTION test2(); -DROP FUNCTION test2arr(); - - -DROP EXTENSION hstore_plperl; -DROP EXTENSION hstore; -DROP EXTENSION plperl; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plperl%2Fsql%2Fhstore_plperlu.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plperl%2Fsql%2Fhstore_plperlu.sql deleted file mode 100644 index c714b35322..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plperl%2Fsql%2Fhstore_plperlu.sql +++ /dev/null @@ -1,125 +0,0 @@ -CREATE EXTENSION hstore_plperlu CASCADE; - -SELECT transforms.udt_schema, transforms.udt_name, - routine_schema, routine_name, - group_name, transform_type -FROM information_schema.transforms JOIN information_schema.routines - USING (specific_catalog, specific_schema, specific_name) -ORDER BY 1, 2, 5, 6; - - --- test hstore -> perl -CREATE FUNCTION test1(val hstore) RETURNS int -LANGUAGE plperlu -TRANSFORM FOR TYPE hstore -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; -elog(INFO, Dumper($_[0])); -return scalar(keys %{$_[0]}); -$$; - -SELECT test1('aa=>bb, cc=>NULL'::hstore); - -CREATE FUNCTION test1none(val hstore) RETURNS int -LANGUAGE plperlu -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; -elog(INFO, Dumper($_[0])); -return scalar(keys %{$_[0]}); -$$; - -SELECT test1none('aa=>bb, cc=>NULL'::hstore); - -CREATE FUNCTION test1list(val hstore) RETURNS int -LANGUAGE plperlu -TRANSFORM FOR TYPE hstore -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; -elog(INFO, Dumper($_[0])); -return scalar(keys %{$_[0]}); -$$; - -SELECT test1list('aa=>bb, cc=>NULL'::hstore); - - --- test hstore[] -> perl -CREATE FUNCTION test1arr(val hstore[]) RETURNS int -LANGUAGE plperlu -TRANSFORM FOR TYPE hstore -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; -elog(INFO, Dumper($_[0]->[0], $_[0]->[1])); -return scalar(keys %{$_[0]}); -$$; - -SELECT test1arr(array['aa=>bb, cc=>NULL'::hstore, 'dd=>ee']); - - --- test as part of prepare/execute -CREATE FUNCTION test3() RETURNS void -LANGUAGE plperlu -TRANSFORM FOR TYPE hstore -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; - -$rv = spi_exec_query(q{SELECT 'aa=>bb, cc=>NULL'::hstore AS col1}); -elog(INFO, Dumper($rv->{rows}[0]->{col1})); - -$val = {a => 1, b => 'boo', c => undef}; -$plan = spi_prepare(q{SELECT $1::text AS col1}, "hstore"); -$rv = spi_exec_prepared($plan, {}, $val); -elog(INFO, Dumper($rv->{rows}[0]->{col1})); -$$; - -SELECT test3(); - - --- test trigger -CREATE TABLE test1 (a int, b hstore); -INSERT INTO test1 VALUES (1, 'aa=>bb, cc=>NULL'); -SELECT * FROM test1; - -CREATE FUNCTION test4() RETURNS trigger -LANGUAGE plperlu -TRANSFORM FOR TYPE hstore -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; -elog(INFO, Dumper($_TD->{new})); -if ($_TD->{new}{a} == 1) { - $_TD->{new}{b} = {a => 1, b => 'boo', c => undef}; -} - -return "MODIFY"; -$$; - -CREATE TRIGGER test4 BEFORE UPDATE ON test1 FOR EACH ROW EXECUTE PROCEDURE test4(); - -UPDATE test1 SET a = a; -SELECT * FROM test1; - - -DROP TABLE test1; - -DROP FUNCTION test1(hstore); -DROP FUNCTION test1none(hstore); -DROP FUNCTION test1list(hstore); -DROP FUNCTION test1arr(hstore[]); -DROP FUNCTION test3(); -DROP FUNCTION test4(); - - -DROP EXTENSION hstore_plperlu; -DROP EXTENSION hstore; -DROP EXTENSION plperlu; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plpython%2Fsql%2Fhstore_plpython.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plpython%2Fsql%2Fhstore_plpython.sql deleted file mode 100644 index a9cfbbe13e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fhstore_plpython%2Fsql%2Fhstore_plpython.sql +++ /dev/null @@ -1,119 +0,0 @@ -CREATE EXTENSION hstore_plpython3u CASCADE; - - --- test hstore -> python -CREATE FUNCTION test1(val hstore) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -assert isinstance(val, dict) -plpy.info(sorted(val.items())) -return len(val) -$$; - -SELECT test1('aa=>bb, cc=>NULL'::hstore); - - --- the same with the versioned language name -CREATE FUNCTION test1n(val hstore) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -assert isinstance(val, dict) -plpy.info(sorted(val.items())) -return len(val) -$$; - -SELECT test1n('aa=>bb, cc=>NULL'::hstore); - - --- test hstore[] -> python -CREATE FUNCTION test1arr(val hstore[]) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -assert(val == [{'aa': 'bb', 'cc': None}, {'dd': 'ee'}]) -return len(val) -$$; - -SELECT test1arr(array['aa=>bb, cc=>NULL'::hstore, 'dd=>ee']); - - --- test python -> hstore -CREATE FUNCTION test2(a int, b text) RETURNS hstore -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -val = {'a': a, 'b': b, 'c': None} -return val -$$; - -SELECT test2(1, 'boo'); - ---- test ruleutils -\sf test2 - - --- test python -> hstore[] -CREATE FUNCTION test2arr() RETURNS hstore[] -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -val = [{'a': 1, 'b': 'boo', 'c': None}, {'d': 2}] -return val -$$; - -SELECT test2arr(); - - --- test python -> domain over hstore -CREATE DOMAIN hstore_foo AS hstore CHECK(VALUE ? 'foo'); - -CREATE FUNCTION test2dom(fn text) RETURNS hstore_foo -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -return {'a': 1, fn: 'boo', 'c': None} -$$; - -SELECT test2dom('foo'); -SELECT test2dom('bar'); -- fail - - --- test as part of prepare/execute -CREATE FUNCTION test3() RETURNS void -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -rv = plpy.execute("SELECT 'aa=>bb, cc=>NULL'::hstore AS col1") -assert(rv[0]["col1"] == {'aa': 'bb', 'cc': None}) - -val = {'a': 1, 'b': 'boo', 'c': None} -plan = plpy.prepare("SELECT $1::text AS col1", ["hstore"]) -rv = plpy.execute(plan, [val]) -assert(rv[0]["col1"] == '"a"=>"1", "b"=>"boo", "c"=>NULL') -$$; - -SELECT test3(); - - --- test trigger -CREATE TABLE test1 (a int, b hstore); -INSERT INTO test1 VALUES (1, 'aa=>bb, cc=>NULL'); -SELECT * FROM test1; - -CREATE FUNCTION test4() RETURNS trigger -LANGUAGE plpython3u -TRANSFORM FOR TYPE hstore -AS $$ -assert(TD["new"] == {'a': 1, 'b': {'aa': 'bb', 'cc': None}}) -if TD["new"]["a"] == 1: - TD["new"]["b"] = {'a': 1, 'b': 'boo', 'c': None} - -return "MODIFY" -$$; - -CREATE TRIGGER test4 BEFORE UPDATE ON test1 FOR EACH ROW EXECUTE PROCEDURE test4(); - -UPDATE test1 SET a = a; -SELECT * FROM test1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fintagg%2Fintagg--1.0--1.1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fintagg%2Fintagg--1.0--1.1.sql deleted file mode 100644 index c0cc17a033..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fintagg%2Fintagg--1.0--1.1.sql +++ /dev/null @@ -1,23 +0,0 @@ -/* contrib/intagg/intagg--1.0--1.1.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION intagg UPDATE TO '1.1'" to load this file. \quit - -ALTER FUNCTION int_agg_state(internal, int4) PARALLEL SAFE; -ALTER FUNCTION int_agg_final_array(internal) PARALLEL SAFE; -ALTER FUNCTION int_array_enum(int4[]) PARALLEL SAFE; -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_proc SET proparallel = 's' -WHERE oid = (my_schema || '.int_array_aggregate(int4)')::pg_catalog.regprocedure; - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fintarray%2Fintarray--1.1--1.2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fintarray%2Fintarray--1.1--1.2.sql deleted file mode 100644 index 919340ef01..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fintarray%2Fintarray--1.1--1.2.sql +++ /dev/null @@ -1,94 +0,0 @@ -/* contrib/intarray/intarray--1.1--1.2.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION intarray UPDATE TO '1.2'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('g_int_consistent(internal,_int4,int4,oid,internal)', '{internal,_int4,int2,oid,internal}'), -('g_intbig_consistent(internal,internal,int4,oid,internal)', '{internal,_int4,int2,oid,internal}'), -('g_intbig_same(internal,internal,internal)', '{SCH.intbig_gkey,SCH.intbig_gkey,internal}'), -('ginint4_queryextract(internal,internal,int2,internal,internal,internal,internal)', '{_int4,internal,int2,internal,internal,internal,internal}'), -('ginint4_consistent(internal,int2,internal,int4,internal,internal,internal,internal)', '{internal,int2,_int4,int4,internal,internal,internal,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -UPDATE pg_catalog.pg_proc SET - prorettype = (my_schema || '.intbig_gkey')::pg_catalog.regtype -WHERE oid = pg_catalog.to_regprocedure(my_schema || '.g_intbig_union(internal,internal)'); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER FUNCTION bqarr_in(cstring) PARALLEL SAFE; -ALTER FUNCTION bqarr_out(query_int) PARALLEL SAFE; -ALTER FUNCTION querytree(query_int) PARALLEL SAFE; -ALTER FUNCTION boolop(_int4, query_int) PARALLEL SAFE; -ALTER FUNCTION rboolop(query_int, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_matchsel(internal, oid, internal, integer) PARALLEL SAFE; -ALTER FUNCTION _int_contains(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_contained(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_overlap(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_same(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_different(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_union(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_inter(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION _int_overlap_sel(internal, oid, internal, integer) PARALLEL SAFE; -ALTER FUNCTION _int_contains_sel(internal, oid, internal, integer) PARALLEL SAFE; -ALTER FUNCTION _int_contained_sel(internal, oid, internal, integer) PARALLEL SAFE; -ALTER FUNCTION _int_overlap_joinsel(internal, oid, internal, smallint, internal) PARALLEL SAFE; -ALTER FUNCTION _int_contains_joinsel(internal, oid, internal, smallint, internal) PARALLEL SAFE; -ALTER FUNCTION _int_contained_joinsel(internal, oid, internal, smallint, internal) PARALLEL SAFE; -ALTER FUNCTION intset(int4) PARALLEL SAFE; -ALTER FUNCTION icount(_int4) PARALLEL SAFE; -ALTER FUNCTION sort(_int4, text) PARALLEL SAFE; -ALTER FUNCTION sort(_int4) PARALLEL SAFE; -ALTER FUNCTION sort_asc(_int4) PARALLEL SAFE; -ALTER FUNCTION sort_desc(_int4) PARALLEL SAFE; -ALTER FUNCTION uniq(_int4) PARALLEL SAFE; -ALTER FUNCTION idx(_int4, int4) PARALLEL SAFE; -ALTER FUNCTION subarray(_int4, int4, int4) PARALLEL SAFE; -ALTER FUNCTION subarray(_int4, int4) PARALLEL SAFE; -ALTER FUNCTION intarray_push_elem(_int4, int4) PARALLEL SAFE; -ALTER FUNCTION intarray_push_array(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION intarray_del_elem(_int4, int4) PARALLEL SAFE; -ALTER FUNCTION intset_union_elem(_int4, int4) PARALLEL SAFE; -ALTER FUNCTION intset_subtract(_int4, _int4) PARALLEL SAFE; -ALTER FUNCTION g_int_consistent(internal, _int4, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION g_int_compress(internal) PARALLEL SAFE; -ALTER FUNCTION g_int_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION g_int_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_int_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_int_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_int_same(_int4, _int4, internal) PARALLEL SAFE; -ALTER FUNCTION _intbig_in(cstring) PARALLEL SAFE; -ALTER FUNCTION _intbig_out(intbig_gkey) PARALLEL SAFE; -ALTER FUNCTION g_intbig_consistent(internal, _int4, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION g_intbig_compress(internal) PARALLEL SAFE; -ALTER FUNCTION g_intbig_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION g_intbig_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_intbig_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_intbig_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION g_intbig_same(intbig_gkey, intbig_gkey, internal) PARALLEL SAFE; -ALTER FUNCTION ginint4_queryextract(_int4, internal, int2, internal, internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION ginint4_consistent(internal, int2, _int4, int4, internal, internal, internal, internal) PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plperl%2Fsql%2Fjsonb_plperl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plperl%2Fsql%2Fjsonb_plperl.sql deleted file mode 100644 index a5b2cffe6b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plperl%2Fsql%2Fjsonb_plperl.sql +++ /dev/null @@ -1,117 +0,0 @@ -CREATE EXTENSION jsonb_plperl CASCADE; - - -CREATE FUNCTION testHVToJsonb() RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -AS $$ -$val = {a => 1, b => 'boo', c => undef}; -return $val; -$$; - -SELECT testHVToJsonb(); - - -CREATE FUNCTION testAVToJsonb() RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -AS $$ -$val = [{a => 1, b => 'boo', c => undef}, {d => 2}]; -return $val; -$$; - -SELECT testAVToJsonb(); - - -CREATE FUNCTION testSVToJsonb() RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -AS $$ -$val = 1; -return $val; -$$; - -SELECT testSVToJsonb(); - - -CREATE FUNCTION testUVToJsonb() RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -as $$ -$val = ~0; -return $val; -$$; - --- this might produce either 18446744073709551615 or 4294967295 -SELECT testUVToJsonb() IN ('18446744073709551615'::jsonb, '4294967295'::jsonb); - - --- this revealed a bug in the original implementation -CREATE FUNCTION testRegexpResultToJsonb() RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -AS $$ -return ('1' =~ m(0\t2)); -$$; - -SELECT testRegexpResultToJsonb(); - - --- this revealed a different bug -CREATE FUNCTION testTextToJsonbObject(text) RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -AS $$ -my $x = shift; -return {a => $x}; -$$; - -SELECT testTextToJsonbObject('abc'); -SELECT testTextToJsonbObject(NULL); - - -CREATE FUNCTION roundtrip(val jsonb, ref text = '') RETURNS jsonb -LANGUAGE plperl -TRANSFORM FOR TYPE jsonb -AS $$ -# can't use Data::Dumper, but let's at least check for unexpected ref type -die 'unexpected '.(ref($_[0]) || 'not a').' reference' - if ref($_[0]) ne $_[1]; -return $_[0]; -$$; - - -SELECT roundtrip('null') is null; -SELECT roundtrip('1'); -SELECT roundtrip('1E+131071'); -SELECT roundtrip('-1'); -SELECT roundtrip('1.2'); -SELECT roundtrip('-1.2'); -SELECT roundtrip('"string"'); -SELECT roundtrip('"NaN"'); - -SELECT roundtrip('true'); -SELECT roundtrip('false'); - -SELECT roundtrip('[]', 'ARRAY'); -SELECT roundtrip('[null, null]', 'ARRAY'); -SELECT roundtrip('[1, 2, 3]', 'ARRAY'); -SELECT roundtrip('[-1, 2, -3]', 'ARRAY'); -SELECT roundtrip('[1.2, 2.3, 3.4]', 'ARRAY'); -SELECT roundtrip('[-1.2, 2.3, -3.4]', 'ARRAY'); -SELECT roundtrip('["string1", "string2"]', 'ARRAY'); -SELECT roundtrip('[["string1", "string2"]]', 'ARRAY'); - -SELECT roundtrip('{}', 'HASH'); -SELECT roundtrip('{"1": null}', 'HASH'); -SELECT roundtrip('{"1": 1}', 'HASH'); -SELECT roundtrip('{"1": -1}', 'HASH'); -SELECT roundtrip('{"1": 1.1}', 'HASH'); -SELECT roundtrip('{"1": -1.1}', 'HASH'); -SELECT roundtrip('{"1": "string1"}', 'HASH'); - -SELECT roundtrip('{"1": {"2": [3, 4, 5]}, "2": 3}', 'HASH'); - - -\set VERBOSITY terse \\ -- suppress cascade details -DROP EXTENSION plperl CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plperl%2Fsql%2Fjsonb_plperlu.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plperl%2Fsql%2Fjsonb_plperlu.sql deleted file mode 100644 index c68ef7308a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plperl%2Fsql%2Fjsonb_plperlu.sql +++ /dev/null @@ -1,121 +0,0 @@ -CREATE EXTENSION jsonb_plperlu CASCADE; - - -CREATE FUNCTION testHVToJsonb() RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -AS $$ -$val = {a => 1, b => 'boo', c => undef}; -return $val; -$$; - -SELECT testHVToJsonb(); - - -CREATE FUNCTION testAVToJsonb() RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -AS $$ -$val = [{a => 1, b => 'boo', c => undef}, {d => 2}]; -return $val; -$$; - -SELECT testAVToJsonb(); - - -CREATE FUNCTION testSVToJsonb() RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -AS $$ -$val = 1; -return $val; -$$; - -SELECT testSVToJsonb(); - - -CREATE FUNCTION testUVToJsonb() RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -as $$ -$val = ~0; -return $val; -$$; - --- this might produce either 18446744073709551615 or 4294967295 -SELECT testUVToJsonb() IN ('18446744073709551615'::jsonb, '4294967295'::jsonb); - - --- this revealed a bug in the original implementation -CREATE FUNCTION testRegexpResultToJsonb() RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -AS $$ -return ('1' =~ m(0\t2)); -$$; - -SELECT testRegexpResultToJsonb(); - - --- this revealed a different bug -CREATE FUNCTION testTextToJsonbObject(text) RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -AS $$ -my $x = shift; -return {a => $x}; -$$; - -SELECT testTextToJsonbObject('abc'); -SELECT testTextToJsonbObject(NULL); - - -CREATE FUNCTION roundtrip(val jsonb, ref text = '') RETURNS jsonb -LANGUAGE plperlu -TRANSFORM FOR TYPE jsonb -AS $$ -use Data::Dumper; -$Data::Dumper::Sortkeys = 1; -$Data::Dumper::Indent = 0; -elog(INFO, Dumper($_[0])); -die 'unexpected '.(ref($_[0]) || 'not a').' reference' - if ref($_[0]) ne $_[1]; -return $_[0]; -$$; - - -SELECT roundtrip('null') is null; -SELECT roundtrip('1'); --- skip because Data::Dumper produces a platform-dependent spelling of infinity --- SELECT roundtrip('1E+131071'); -SELECT roundtrip('-1'); -SELECT roundtrip('1.2'); -SELECT roundtrip('-1.2'); -SELECT roundtrip('"string"'); -SELECT roundtrip('"NaN"'); - -SELECT roundtrip('true'); -SELECT roundtrip('false'); - -SELECT roundtrip('[]', 'ARRAY'); -SELECT roundtrip('[null, null]', 'ARRAY'); -SELECT roundtrip('[1, 2, 3]', 'ARRAY'); -SELECT roundtrip('[-1, 2, -3]', 'ARRAY'); -SELECT roundtrip('[1.2, 2.3, 3.4]', 'ARRAY'); -SELECT roundtrip('[-1.2, 2.3, -3.4]', 'ARRAY'); -SELECT roundtrip('["string1", "string2"]', 'ARRAY'); -SELECT roundtrip('[["string1", "string2"]]', 'ARRAY'); - -SELECT roundtrip('{}', 'HASH'); -SELECT roundtrip('{"1": null}', 'HASH'); -SELECT roundtrip('{"1": 1}', 'HASH'); -SELECT roundtrip('{"1": -1}', 'HASH'); -SELECT roundtrip('{"1": 1.1}', 'HASH'); -SELECT roundtrip('{"1": -1.1}', 'HASH'); -SELECT roundtrip('{"1": "string1"}', 'HASH'); - -SELECT roundtrip('{"1": {"2": [3, 4, 5]}, "2": 3}', 'HASH'); - - -\set VERBOSITY terse \\ -- suppress cascade details -DROP EXTENSION plperlu CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plpython%2Fsql%2Fjsonb_plpython.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plpython%2Fsql%2Fjsonb_plpython.sql deleted file mode 100644 index 29dc33279a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fjsonb_plpython%2Fsql%2Fjsonb_plpython.sql +++ /dev/null @@ -1,183 +0,0 @@ -CREATE EXTENSION jsonb_plpython3u CASCADE; - --- test jsonb -> python dict -CREATE FUNCTION test1(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert isinstance(val, dict) -assert(val == {'a': 1, 'c': 'NULL'}) -return len(val) -$$; - -SELECT test1('{"a": 1, "c": "NULL"}'::jsonb); - --- test jsonb -> python dict --- complex dict with dicts as value -CREATE FUNCTION test1complex(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert isinstance(val, dict) -assert(val == {"d": {"d": 1}}) -return len(val) -$$; - -SELECT test1complex('{"d": {"d": 1}}'::jsonb); - - --- test jsonb[] -> python dict --- dict with array as value -CREATE FUNCTION test1arr(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert isinstance(val, dict) -assert(val == {"d": [12, 1]}) -return len(val) -$$; - -SELECT test1arr('{"d":[12, 1]}'::jsonb); - --- test jsonb[] -> python list --- simple list -CREATE FUNCTION test2arr(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert isinstance(val, list) -assert(val == [12, 1]) -return len(val) -$$; - -SELECT test2arr('[12, 1]'::jsonb); - --- test jsonb[] -> python list --- array of dicts -CREATE FUNCTION test3arr(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert isinstance(val, list) -assert(val == [{"a": 1,"b": 2}, {"c": 3,"d": 4}]) -return len(val) -$$; - -SELECT test3arr('[{"a": 1, "b": 2}, {"c": 3,"d": 4}]'::jsonb); - --- test jsonb int -> python int -CREATE FUNCTION test1int(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert(val == 1) -return val -$$; - -SELECT test1int('1'::jsonb); - --- test jsonb string -> python string -CREATE FUNCTION test1string(val jsonb) RETURNS text -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert(val == "a") -return val -$$; - -SELECT test1string('"a"'::jsonb); - --- test jsonb null -> python None -CREATE FUNCTION test1null(val jsonb) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -assert(val == None) -return 1 -$$; - -SELECT test1null('null'::jsonb); - --- test python -> jsonb -CREATE FUNCTION roundtrip(val jsonb) RETURNS jsonb -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -as $$ -return val -$$; - -SELECT roundtrip('null'::jsonb); -SELECT roundtrip('1'::jsonb); -SELECT roundtrip('1234567890.0987654321'::jsonb); -SELECT roundtrip('-1234567890.0987654321'::jsonb); -SELECT roundtrip('true'::jsonb); -SELECT roundtrip('"string"'::jsonb); - -SELECT roundtrip('{"1": null}'::jsonb); -SELECT roundtrip('{"1": 1}'::jsonb); -SELECT roundtrip('{"1": true}'::jsonb); -SELECT roundtrip('{"1": "string"}'::jsonb); - -SELECT roundtrip('[null]'::jsonb); -SELECT roundtrip('[1]'::jsonb); -SELECT roundtrip('[true]'::jsonb); -SELECT roundtrip('["string"]'::jsonb); -SELECT roundtrip('[null, 1]'::jsonb); -SELECT roundtrip('[1, true]'::jsonb); -SELECT roundtrip('[true, "string"]'::jsonb); -SELECT roundtrip('["string", "string2"]'::jsonb); - --- complex numbers -> jsonb -CREATE FUNCTION testComplexNumbers() RETURNS jsonb -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -x = 1 + 2j -return x -$$; - -SELECT testComplexNumbers(); - --- range -> jsonb -CREATE FUNCTION testRange() RETURNS jsonb -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -x = range(3) -return x -$$; - -SELECT testRange(); - --- 0xff -> jsonb -CREATE FUNCTION testDecimal() RETURNS jsonb -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -x = 0xff -return x -$$; - -SELECT testDecimal(); - --- tuple -> jsonb -CREATE FUNCTION testTuple() RETURNS jsonb -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -x = (1, 'String', None) -return x -$$; - -SELECT testTuple(); - --- interesting dict -> jsonb -CREATE FUNCTION test_dict1() RETURNS jsonb -LANGUAGE plpython3u -TRANSFORM FOR TYPE jsonb -AS $$ -x = {"a": 1, None: 2, 33: 3} -return x -$$; - -SELECT test_dict1(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fltree%2Fltree--1.0--1.1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fltree%2Fltree--1.0--1.1.sql deleted file mode 100644 index 2ce6f5adbc..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fltree%2Fltree--1.0--1.1.sql +++ /dev/null @@ -1,115 +0,0 @@ -/* contrib/ltree/ltree--1.0--1.1.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION ltree UPDATE TO '1.1'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('ltree_consistent(internal,internal,int2,oid,internal)', '{internal,SCH.ltree,int2,oid,internal}'), -('ltree_same(internal,internal,internal)', '{SCH.ltree_gist,SCH.ltree_gist,internal}'), -('_ltree_consistent(internal,internal,int2,oid,internal)', '{internal,SCH._ltree,int2,oid,internal}'), -('_ltree_same(internal,internal,internal)', '{SCH.ltree_gist,SCH.ltree_gist,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -UPDATE pg_catalog.pg_proc SET - prorettype = (my_schema || '.ltree_gist')::pg_catalog.regtype -WHERE oid = pg_catalog.to_regprocedure(my_schema || '.ltree_union(internal,internal)'); - -UPDATE pg_catalog.pg_proc SET - prorettype = (my_schema || '.ltree_gist')::pg_catalog.regtype -WHERE oid = pg_catalog.to_regprocedure(my_schema || '._ltree_union(internal,internal)'); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER FUNCTION ltree_in(cstring) PARALLEL SAFE; -ALTER FUNCTION ltree_out(ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_cmp(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_lt(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_le(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_eq(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_ge(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_gt(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_ne(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION subltree(ltree, int4, int4) PARALLEL SAFE; -ALTER FUNCTION subpath(ltree, int4, int4) PARALLEL SAFE; -ALTER FUNCTION subpath(ltree, int4) PARALLEL SAFE; -ALTER FUNCTION index(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION index(ltree, ltree, int4) PARALLEL SAFE; -ALTER FUNCTION nlevel(ltree) PARALLEL SAFE; -ALTER FUNCTION ltree2text(ltree) PARALLEL SAFE; -ALTER FUNCTION text2ltree(text) PARALLEL SAFE; -ALTER FUNCTION lca(_ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree, ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree, ltree, ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree, ltree, ltree, ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree, ltree, ltree, ltree, ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION lca(ltree, ltree, ltree, ltree, ltree, ltree, ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_isparent(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_risparent(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_addltree(ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_addtext(ltree, text) PARALLEL SAFE; -ALTER FUNCTION ltree_textadd(text, ltree) PARALLEL SAFE; -ALTER FUNCTION ltreeparentsel(internal, oid, internal, integer) PARALLEL SAFE; -ALTER FUNCTION lquery_in(cstring) PARALLEL SAFE; -ALTER FUNCTION lquery_out(lquery) PARALLEL SAFE; -ALTER FUNCTION ltq_regex(ltree, lquery) PARALLEL SAFE; -ALTER FUNCTION ltq_rregex(lquery, ltree) PARALLEL SAFE; -ALTER FUNCTION lt_q_regex(ltree, _lquery) PARALLEL SAFE; -ALTER FUNCTION lt_q_rregex(_lquery, ltree) PARALLEL SAFE; -ALTER FUNCTION ltxtq_in(cstring) PARALLEL SAFE; -ALTER FUNCTION ltxtq_out(ltxtquery) PARALLEL SAFE; -ALTER FUNCTION ltxtq_exec(ltree, ltxtquery) PARALLEL SAFE; -ALTER FUNCTION ltxtq_rexec(ltxtquery, ltree) PARALLEL SAFE; -ALTER FUNCTION ltree_gist_in(cstring) PARALLEL SAFE; -ALTER FUNCTION ltree_gist_out(ltree_gist) PARALLEL SAFE; -ALTER FUNCTION ltree_consistent(internal, ltree, int2, oid, internal) PARALLEL SAFE; -ALTER FUNCTION ltree_compress(internal) PARALLEL SAFE; -ALTER FUNCTION ltree_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION ltree_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION ltree_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION ltree_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION ltree_same(ltree_gist, ltree_gist, internal) PARALLEL SAFE; -ALTER FUNCTION _ltree_isparent(_ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION _ltree_r_isparent(ltree, _ltree) PARALLEL SAFE; -ALTER FUNCTION _ltree_risparent(_ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION _ltree_r_risparent(ltree, _ltree) PARALLEL SAFE; -ALTER FUNCTION _ltq_regex(_ltree, lquery) PARALLEL SAFE; -ALTER FUNCTION _ltq_rregex(lquery, _ltree) PARALLEL SAFE; -ALTER FUNCTION _lt_q_regex(_ltree, _lquery) PARALLEL SAFE; -ALTER FUNCTION _lt_q_rregex(_lquery, _ltree) PARALLEL SAFE; -ALTER FUNCTION _ltxtq_exec(_ltree, ltxtquery) PARALLEL SAFE; -ALTER FUNCTION _ltxtq_rexec(ltxtquery, _ltree) PARALLEL SAFE; -ALTER FUNCTION _ltree_extract_isparent(_ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION _ltree_extract_risparent(_ltree, ltree) PARALLEL SAFE; -ALTER FUNCTION _ltq_extract_regex(_ltree, lquery) PARALLEL SAFE; -ALTER FUNCTION _ltxtq_extract_exec(_ltree, ltxtquery) PARALLEL SAFE; -ALTER FUNCTION _ltree_consistent(internal, _ltree, int2, oid, internal) PARALLEL SAFE; -ALTER FUNCTION _ltree_compress(internal) PARALLEL SAFE; -ALTER FUNCTION _ltree_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION _ltree_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION _ltree_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION _ltree_same(ltree_gist, ltree_gist, internal) PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fltree_plpython%2Fsql%2Fltree_plpython.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fltree_plpython%2Fsql%2Fltree_plpython.sql deleted file mode 100644 index 0b8d28399a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fltree_plpython%2Fsql%2Fltree_plpython.sql +++ /dev/null @@ -1,36 +0,0 @@ -CREATE EXTENSION ltree_plpython3u CASCADE; - - -CREATE FUNCTION test1(val ltree) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE ltree -AS $$ -plpy.info(repr(val)) -return len(val) -$$; - -SELECT test1('aa.bb.cc'::ltree); - - -CREATE FUNCTION test1n(val ltree) RETURNS int -LANGUAGE plpython3u -TRANSFORM FOR TYPE ltree -AS $$ -plpy.info(repr(val)) -return len(val) -$$; - -SELECT test1n('aa.bb.cc'::ltree); - - -CREATE FUNCTION test2() RETURNS ltree -LANGUAGE plpython3u -TRANSFORM FOR TYPE ltree -AS $$ -return ['foo', 'bar', 'baz'] -$$; - --- plpython to ltree is not yet implemented, so this will fail, --- because it will try to parse the Python list as an ltree input --- string. -SELECT test2(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fpageinspect--1.3--1.4.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fpageinspect--1.3--1.4.sql deleted file mode 100644 index 86e0dfafc0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fpageinspect--1.3--1.4.sql +++ /dev/null @@ -1,118 +0,0 @@ -/* contrib/pageinspect/pageinspect--1.3--1.4.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION pageinspect UPDATE TO '1.4'" to load this file. \quit - --- --- heap_page_items() --- -DROP FUNCTION heap_page_items(bytea); -CREATE FUNCTION heap_page_items(IN page bytea, - OUT lp smallint, - OUT lp_off smallint, - OUT lp_flags smallint, - OUT lp_len smallint, - OUT t_xmin xid, - OUT t_xmax xid, - OUT t_field3 int4, - OUT t_ctid tid, - OUT t_infomask2 integer, - OUT t_infomask integer, - OUT t_hoff smallint, - OUT t_bits text, - OUT t_oid oid, - OUT t_data bytea) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'heap_page_items' -LANGUAGE C STRICT; - --- --- tuple_data_split() --- -CREATE FUNCTION tuple_data_split(rel_oid oid, - t_data bytea, - t_infomask integer, - t_infomask2 integer, - t_bits text) -RETURNS bytea[] -AS 'MODULE_PATHNAME','tuple_data_split' -LANGUAGE C; - -CREATE FUNCTION tuple_data_split(rel_oid oid, - t_data bytea, - t_infomask integer, - t_infomask2 integer, - t_bits text, - do_detoast bool) -RETURNS bytea[] -AS 'MODULE_PATHNAME','tuple_data_split' -LANGUAGE C; - --- --- heap_page_item_attrs() --- -CREATE FUNCTION heap_page_item_attrs( - IN page bytea, - IN rel_oid regclass, - IN do_detoast bool, - OUT lp smallint, - OUT lp_off smallint, - OUT lp_flags smallint, - OUT lp_len smallint, - OUT t_xmin xid, - OUT t_xmax xid, - OUT t_field3 int4, - OUT t_ctid tid, - OUT t_infomask2 integer, - OUT t_infomask integer, - OUT t_hoff smallint, - OUT t_bits text, - OUT t_oid oid, - OUT t_attrs bytea[] - ) -RETURNS SETOF record AS $$ -SELECT lp, - lp_off, - lp_flags, - lp_len, - t_xmin, - t_xmax, - t_field3, - t_ctid, - t_infomask2, - t_infomask, - t_hoff, - t_bits, - t_oid, - tuple_data_split( - rel_oid, - t_data, - t_infomask, - t_infomask2, - t_bits, - do_detoast) - AS t_attrs - FROM heap_page_items(page); -$$ LANGUAGE SQL; - -CREATE FUNCTION heap_page_item_attrs( - IN page bytea, - IN rel_oid regclass, - OUT lp smallint, - OUT lp_off smallint, - OUT lp_flags smallint, - OUT lp_len smallint, - OUT t_xmin xid, - OUT t_xmax xid, - OUT t_field3 int4, - OUT t_ctid tid, - OUT t_infomask2 integer, - OUT t_infomask integer, - OUT t_hoff smallint, - OUT t_bits text, - OUT t_oid oid, - OUT t_attrs bytea[] - ) -RETURNS SETOF record AS $$ -SELECT * from heap_page_item_attrs(page, rel_oid, false); -$$ LANGUAGE SQL; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fpageinspect--1.5.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fpageinspect--1.5.sql deleted file mode 100644 index 1e40c3c97e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fpageinspect--1.5.sql +++ /dev/null @@ -1,279 +0,0 @@ -/* contrib/pageinspect/pageinspect--1.5.sql */ - --- complain if script is sourced in psql, rather than via CREATE EXTENSION -\echo Use "CREATE EXTENSION pageinspect" to load this file. \quit - --- --- get_raw_page() --- -CREATE FUNCTION get_raw_page(text, int4) -RETURNS bytea -AS 'MODULE_PATHNAME', 'get_raw_page' -LANGUAGE C STRICT PARALLEL SAFE; - -CREATE FUNCTION get_raw_page(text, text, int4) -RETURNS bytea -AS 'MODULE_PATHNAME', 'get_raw_page_fork' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- page_header() --- -CREATE FUNCTION page_header(IN page bytea, - OUT lsn pg_lsn, - OUT checksum smallint, - OUT flags smallint, - OUT lower smallint, - OUT upper smallint, - OUT special smallint, - OUT pagesize smallint, - OUT version smallint, - OUT prune_xid xid) -AS 'MODULE_PATHNAME', 'page_header' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- heap_page_items() --- -CREATE FUNCTION heap_page_items(IN page bytea, - OUT lp smallint, - OUT lp_off smallint, - OUT lp_flags smallint, - OUT lp_len smallint, - OUT t_xmin xid, - OUT t_xmax xid, - OUT t_field3 int4, - OUT t_ctid tid, - OUT t_infomask2 integer, - OUT t_infomask integer, - OUT t_hoff smallint, - OUT t_bits text, - OUT t_oid oid, - OUT t_data bytea) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'heap_page_items' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- tuple_data_split() --- -CREATE FUNCTION tuple_data_split(rel_oid oid, - t_data bytea, - t_infomask integer, - t_infomask2 integer, - t_bits text) -RETURNS bytea[] -AS 'MODULE_PATHNAME','tuple_data_split' -LANGUAGE C PARALLEL SAFE; - -CREATE FUNCTION tuple_data_split(rel_oid oid, - t_data bytea, - t_infomask integer, - t_infomask2 integer, - t_bits text, - do_detoast bool) -RETURNS bytea[] -AS 'MODULE_PATHNAME','tuple_data_split' -LANGUAGE C PARALLEL SAFE; - --- --- heap_page_item_attrs() --- -CREATE FUNCTION heap_page_item_attrs( - IN page bytea, - IN rel_oid regclass, - IN do_detoast bool, - OUT lp smallint, - OUT lp_off smallint, - OUT lp_flags smallint, - OUT lp_len smallint, - OUT t_xmin xid, - OUT t_xmax xid, - OUT t_field3 int4, - OUT t_ctid tid, - OUT t_infomask2 integer, - OUT t_infomask integer, - OUT t_hoff smallint, - OUT t_bits text, - OUT t_oid oid, - OUT t_attrs bytea[] - ) -RETURNS SETOF record AS $$ -SELECT lp, - lp_off, - lp_flags, - lp_len, - t_xmin, - t_xmax, - t_field3, - t_ctid, - t_infomask2, - t_infomask, - t_hoff, - t_bits, - t_oid, - tuple_data_split( - rel_oid, - t_data, - t_infomask, - t_infomask2, - t_bits, - do_detoast) - AS t_attrs - FROM heap_page_items(page); -$$ LANGUAGE SQL PARALLEL SAFE; - -CREATE FUNCTION heap_page_item_attrs(IN page bytea, IN rel_oid regclass, - OUT lp smallint, - OUT lp_off smallint, - OUT lp_flags smallint, - OUT lp_len smallint, - OUT t_xmin xid, - OUT t_xmax xid, - OUT t_field3 int4, - OUT t_ctid tid, - OUT t_infomask2 integer, - OUT t_infomask integer, - OUT t_hoff smallint, - OUT t_bits text, - OUT t_oid oid, - OUT t_attrs bytea[] - ) -RETURNS SETOF record AS $$ -SELECT * from heap_page_item_attrs(page, rel_oid, false); -$$ LANGUAGE SQL PARALLEL SAFE; - --- --- bt_metap() --- -CREATE FUNCTION bt_metap(IN relname text, - OUT magic int4, - OUT version int4, - OUT root int4, - OUT level int4, - OUT fastroot int4, - OUT fastlevel int4) -AS 'MODULE_PATHNAME', 'bt_metap' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- bt_page_stats() --- -CREATE FUNCTION bt_page_stats(IN relname text, IN blkno int4, - OUT blkno int4, - OUT type "char", - OUT live_items int4, - OUT dead_items int4, - OUT avg_item_size int4, - OUT page_size int4, - OUT free_size int4, - OUT btpo_prev int4, - OUT btpo_next int4, - OUT btpo int4, - OUT btpo_flags int4) -AS 'MODULE_PATHNAME', 'bt_page_stats' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- bt_page_items() --- -CREATE FUNCTION bt_page_items(IN relname text, IN blkno int4, - OUT itemoffset smallint, - OUT ctid tid, - OUT itemlen smallint, - OUT nulls bool, - OUT vars bool, - OUT data text) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'bt_page_items' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- brin_page_type() --- -CREATE FUNCTION brin_page_type(IN page bytea) -RETURNS text -AS 'MODULE_PATHNAME', 'brin_page_type' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- brin_metapage_info() --- -CREATE FUNCTION brin_metapage_info(IN page bytea, OUT magic text, - OUT version integer, OUT pagesperrange integer, OUT lastrevmappage bigint) -AS 'MODULE_PATHNAME', 'brin_metapage_info' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- brin_revmap_data() --- -CREATE FUNCTION brin_revmap_data(IN page bytea, - OUT pages tid) -RETURNS SETOF tid -AS 'MODULE_PATHNAME', 'brin_revmap_data' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- brin_page_items() --- -CREATE FUNCTION brin_page_items(IN page bytea, IN index_oid regclass, - OUT itemoffset int, - OUT blknum int, - OUT attnum int, - OUT allnulls bool, - OUT hasnulls bool, - OUT placeholder bool, - OUT value text) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'brin_page_items' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- fsm_page_contents() --- -CREATE FUNCTION fsm_page_contents(IN page bytea) -RETURNS text -AS 'MODULE_PATHNAME', 'fsm_page_contents' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- GIN functions --- - --- --- gin_metapage_info() --- -CREATE FUNCTION gin_metapage_info(IN page bytea, - OUT pending_head bigint, - OUT pending_tail bigint, - OUT tail_free_size int4, - OUT n_pending_pages bigint, - OUT n_pending_tuples bigint, - OUT n_total_pages bigint, - OUT n_entry_pages bigint, - OUT n_data_pages bigint, - OUT n_entries bigint, - OUT version int4) -AS 'MODULE_PATHNAME', 'gin_metapage_info' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- gin_page_opaque_info() --- -CREATE FUNCTION gin_page_opaque_info(IN page bytea, - OUT rightlink bigint, - OUT maxoff int4, - OUT flags text[]) -AS 'MODULE_PATHNAME', 'gin_page_opaque_info' -LANGUAGE C STRICT PARALLEL SAFE; - --- --- gin_leafpage_items() --- -CREATE FUNCTION gin_leafpage_items(IN page bytea, - OUT first_tid tid, - OUT nbytes int2, - OUT tids tid[]) -RETURNS SETOF record -AS 'MODULE_PATHNAME', 'gin_leafpage_items' -LANGUAGE C STRICT PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fsql%2Fgist.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fsql%2Fgist.sql deleted file mode 100644 index 1edf2b307f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpageinspect%2Fsql%2Fgist.sql +++ /dev/null @@ -1,53 +0,0 @@ --- The gist_page_opaque_info() function prints the page's LSN. Normally, --- that's constant 1 (GistBuildLSN) on every page of a freshly built GiST --- index. But with wal_level=minimal, the whole relation is dumped to WAL at --- the end of the transaction if it's smaller than wal_skip_threshold, which --- updates the LSNs. Wrap the tests on gist_page_opaque_info() in the --- same transaction with the CREATE INDEX so that we see the LSNs before --- they are possibly overwritten at end of transaction. -BEGIN; - --- Create a test table and GiST index. -CREATE TABLE test_gist AS SELECT point(i,i) p, i::text t FROM - generate_series(1,1000) i; -CREATE INDEX test_gist_idx ON test_gist USING gist (p); - --- Page 0 is the root, the rest are leaf pages -SELECT * FROM gist_page_opaque_info(get_raw_page('test_gist_idx', 0)); -SELECT * FROM gist_page_opaque_info(get_raw_page('test_gist_idx', 1)); -SELECT * FROM gist_page_opaque_info(get_raw_page('test_gist_idx', 2)); - -COMMIT; - -SELECT * FROM gist_page_items(get_raw_page('test_gist_idx', 0), 'test_gist_idx'); -SELECT * FROM gist_page_items(get_raw_page('test_gist_idx', 1), 'test_gist_idx') LIMIT 5; - --- gist_page_items_bytea prints the raw key data as a bytea. The output of that is --- platform-dependent (endianness), so omit the actual key data from the output. -SELECT itemoffset, ctid, itemlen FROM gist_page_items_bytea(get_raw_page('test_gist_idx', 0)); - --- Failure with non-GiST index. -CREATE INDEX test_gist_btree on test_gist(t); -SELECT gist_page_items(get_raw_page('test_gist_btree', 0), 'test_gist_btree'); - --- Failure with various modes. --- Suppress the DETAIL message, to allow the tests to work across various --- page sizes and architectures. -\set VERBOSITY terse --- invalid page size -SELECT gist_page_items_bytea('aaa'::bytea); -SELECT gist_page_items('aaa'::bytea, 'test_gist_idx'::regclass); -SELECT gist_page_opaque_info('aaa'::bytea); --- invalid special area size -SELECT * FROM gist_page_opaque_info(get_raw_page('test_gist', 0)); -SELECT gist_page_items_bytea(get_raw_page('test_gist', 0)); -SELECT gist_page_items_bytea(get_raw_page('test_gist_btree', 0)); -\set VERBOSITY default - --- Tests with all-zero pages. -SHOW block_size \gset -SELECT gist_page_items_bytea(decode(repeat('00', :block_size), 'hex')); -SELECT gist_page_items(decode(repeat('00', :block_size), 'hex'), 'test_gist_idx'::regclass); -SELECT gist_page_opaque_info(decode(repeat('00', :block_size), 'hex')); - -DROP TABLE test_gist; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_freespacemap%2Fpg_freespacemap--1.1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_freespacemap%2Fpg_freespacemap--1.1.sql deleted file mode 100644 index e1b8242268..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_freespacemap%2Fpg_freespacemap--1.1.sql +++ /dev/null @@ -1,25 +0,0 @@ -/* contrib/pg_freespacemap/pg_freespacemap--1.1.sql */ - --- complain if script is sourced in psql, rather than via CREATE EXTENSION -\echo Use "CREATE EXTENSION pg_freespacemap" to load this file. \quit - --- Register the C function. -CREATE FUNCTION pg_freespace(regclass, bigint) -RETURNS int2 -AS 'MODULE_PATHNAME', 'pg_freespace' -LANGUAGE C STRICT PARALLEL SAFE; - --- pg_freespace shows the recorded space avail at each block in a relation -CREATE FUNCTION - pg_freespace(rel regclass, blkno OUT bigint, avail OUT int2) -RETURNS SETOF RECORD -AS $$ - SELECT blkno, pg_freespace($1, blkno) AS avail - FROM generate_series(0, pg_relation_size($1) / current_setting('block_size')::bigint - 1) AS blkno; -$$ -LANGUAGE SQL PARALLEL SAFE; - - --- Don't want these to be available to public. -REVOKE ALL ON FUNCTION pg_freespace(regclass, bigint) FROM PUBLIC; -REVOKE ALL ON FUNCTION pg_freespace(regclass) FROM PUBLIC; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_stat_statements%2Fsql%2Fpg_stat_statements.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_stat_statements%2Fsql%2Fpg_stat_statements.sql deleted file mode 100644 index dffd2c8c18..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_stat_statements%2Fsql%2Fpg_stat_statements.sql +++ /dev/null @@ -1,445 +0,0 @@ -CREATE EXTENSION pg_stat_statements; - --- --- simple and compound statements --- -SET pg_stat_statements.track_utility = FALSE; -SET pg_stat_statements.track_planning = TRUE; -SELECT pg_stat_statements_reset(); - -SELECT 1 AS "int"; - -SELECT 'hello' - -- multiline - AS "text"; - -SELECT 'world' AS "text"; - --- transaction -BEGIN; -SELECT 1 AS "int"; -SELECT 'hello' AS "text"; -COMMIT; - --- compound transaction -BEGIN \; -SELECT 2.0 AS "float" \; -SELECT 'world' AS "text" \; -COMMIT; - --- compound with empty statements and spurious leading spacing -\;\; SELECT 3 + 3 \;\;\; SELECT ' ' || ' !' \;\; SELECT 1 + 4 \;; - --- non ;-terminated statements -SELECT 1 + 1 + 1 AS "add" \gset -SELECT :add + 1 + 1 AS "add" \; -SELECT :add + 1 + 1 AS "add" \gset - --- set operator -SELECT 1 AS i UNION SELECT 2 ORDER BY i; - --- ? operator -select '{"a":1, "b":2}'::jsonb ? 'b'; - --- cte -WITH t(f) AS ( - VALUES (1.0), (2.0) -) - SELECT f FROM t ORDER BY f; - --- prepared statement with parameter -PREPARE pgss_test (int) AS SELECT $1, 'test' LIMIT 1; -EXECUTE pgss_test(1); -DEALLOCATE pgss_test; - -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- CRUD: INSERT SELECT UPDATE DELETE on test table --- -SELECT pg_stat_statements_reset(); - --- utility "create table" should not be shown -CREATE TEMP TABLE test (a int, b char(20)); - -INSERT INTO test VALUES(generate_series(1, 10), 'aaa'); -UPDATE test SET b = 'bbb' WHERE a > 7; -DELETE FROM test WHERE a > 9; - --- explicit transaction -BEGIN; -UPDATE test SET b = '111' WHERE a = 1 ; -COMMIT; - -BEGIN \; -UPDATE test SET b = '222' WHERE a = 2 \; -COMMIT ; - -UPDATE test SET b = '333' WHERE a = 3 \; -UPDATE test SET b = '444' WHERE a = 4 ; - -BEGIN \; -UPDATE test SET b = '555' WHERE a = 5 \; -UPDATE test SET b = '666' WHERE a = 6 \; -COMMIT ; - --- many INSERT values -INSERT INTO test (a, b) VALUES (1, 'a'), (2, 'b'), (3, 'c'); - --- SELECT with constants -SELECT * FROM test WHERE a > 5 ORDER BY a ; - -SELECT * - FROM test - WHERE a > 9 - ORDER BY a ; - --- SELECT without constants -SELECT * FROM test ORDER BY a; - --- SELECT with IN clause -SELECT * FROM test WHERE a IN (1, 2, 3, 4, 5); - -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- INSERT, UPDATE, DELETE on test table to validate WAL generation metrics --- -SELECT pg_stat_statements_reset(); - --- utility "create table" should not be shown -CREATE TABLE pgss_test (a int, b char(20)); - -INSERT INTO pgss_test VALUES(generate_series(1, 10), 'aaa'); -UPDATE pgss_test SET b = 'bbb' WHERE a > 7; -DELETE FROM pgss_test WHERE a > 9; --- DROP test table -SET pg_stat_statements.track_utility = TRUE; -DROP TABLE pgss_test; -SET pg_stat_statements.track_utility = FALSE; - --- Check WAL is generated for the above statements -SELECT query, calls, rows, -wal_bytes > 0 as wal_bytes_generated, -wal_records > 0 as wal_records_generated, -wal_records = rows as wal_records_as_rows -FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- pg_stat_statements.track = none --- -SET pg_stat_statements.track = 'none'; -SELECT pg_stat_statements_reset(); - -SELECT 1 AS "one"; -SELECT 1 + 1 AS "two"; - -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- pg_stat_statements.track = top --- -SET pg_stat_statements.track = 'top'; -SELECT pg_stat_statements_reset(); - -DO LANGUAGE plpgsql $$ -BEGIN - -- this is a SELECT - PERFORM 'hello world'::TEXT; -END; -$$; - --- PL/pgSQL function -CREATE FUNCTION PLUS_TWO(i INTEGER) RETURNS INTEGER AS $$ -DECLARE - r INTEGER; -BEGIN - SELECT (i + 1 + 1.0)::INTEGER INTO r; - RETURN r; -END; $$ LANGUAGE plpgsql; - -SELECT PLUS_TWO(3); -SELECT PLUS_TWO(7); - --- SQL function --- use LIMIT to keep it from being inlined -CREATE FUNCTION PLUS_ONE(i INTEGER) RETURNS INTEGER AS -$$ SELECT (i + 1.0)::INTEGER LIMIT 1 $$ LANGUAGE SQL; - -SELECT PLUS_ONE(8); -SELECT PLUS_ONE(10); - -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- pg_stat_statements.track = all --- -SET pg_stat_statements.track = 'all'; -SELECT pg_stat_statements_reset(); - --- we drop and recreate the functions to avoid any caching funnies -DROP FUNCTION PLUS_ONE(INTEGER); -DROP FUNCTION PLUS_TWO(INTEGER); - --- PL/pgSQL function -CREATE FUNCTION PLUS_TWO(i INTEGER) RETURNS INTEGER AS $$ -DECLARE - r INTEGER; -BEGIN - SELECT (i + 1 + 1.0)::INTEGER INTO r; - RETURN r; -END; $$ LANGUAGE plpgsql; - -SELECT PLUS_TWO(-1); -SELECT PLUS_TWO(2); - --- SQL function --- use LIMIT to keep it from being inlined -CREATE FUNCTION PLUS_ONE(i INTEGER) RETURNS INTEGER AS -$$ SELECT (i + 1.0)::INTEGER LIMIT 1 $$ LANGUAGE SQL; - -SELECT PLUS_ONE(3); -SELECT PLUS_ONE(1); - -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- queries with locking clauses --- -CREATE TABLE pgss_a (id integer PRIMARY KEY); -CREATE TABLE pgss_b (id integer PRIMARY KEY, a_id integer REFERENCES pgss_a); - -SELECT pg_stat_statements_reset(); - --- control query -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id; - --- test range tables -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE; -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE OF pgss_a; -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE OF pgss_b; -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE OF pgss_a, pgss_b; -- matches plain "FOR UPDATE" -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE OF pgss_b, pgss_a; - --- test strengths -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR NO KEY UPDATE; -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR SHARE; -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR KEY SHARE; - --- test wait policies -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE NOWAIT; -SELECT * FROM pgss_a JOIN pgss_b ON pgss_b.a_id = pgss_a.id FOR UPDATE SKIP LOCKED; - -SELECT calls, query FROM pg_stat_statements ORDER BY query COLLATE "C"; - -DROP TABLE pgss_a, pgss_b CASCADE; - --- --- utility commands --- -SET pg_stat_statements.track_utility = TRUE; -SELECT pg_stat_statements_reset(); - -SELECT 1; -CREATE INDEX test_b ON test(b); -DROP TABLE test \; -DROP TABLE IF EXISTS test \; -DROP FUNCTION PLUS_ONE(INTEGER); -DROP TABLE IF EXISTS test \; -DROP TABLE IF EXISTS test \; -DROP FUNCTION IF EXISTS PLUS_ONE(INTEGER); -DROP FUNCTION PLUS_TWO(INTEGER); - -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- Track the total number of rows retrieved or affected by the utility --- commands of COPY, FETCH, CREATE TABLE AS, CREATE MATERIALIZED VIEW, --- REFRESH MATERIALIZED VIEW and SELECT INTO --- -SELECT pg_stat_statements_reset(); - -CREATE TABLE pgss_ctas AS SELECT a, 'ctas' b FROM generate_series(1, 10) a; -SELECT generate_series(1, 10) c INTO pgss_select_into; -COPY pgss_ctas (a, b) FROM STDIN; -11 copy -12 copy -13 copy -\. -CREATE MATERIALIZED VIEW pgss_matv AS SELECT * FROM pgss_ctas; -REFRESH MATERIALIZED VIEW pgss_matv; -BEGIN; -DECLARE pgss_cursor CURSOR FOR SELECT * FROM pgss_matv; -FETCH NEXT pgss_cursor; -FETCH FORWARD 5 pgss_cursor; -FETCH FORWARD ALL pgss_cursor; -COMMIT; - -SELECT query, plans, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- Track user activity and reset them --- -SELECT pg_stat_statements_reset(); -CREATE ROLE regress_stats_user1; -CREATE ROLE regress_stats_user2; - -SET ROLE regress_stats_user1; - -SELECT 1 AS "ONE"; -SELECT 1+1 AS "TWO"; - -RESET ROLE; -SET ROLE regress_stats_user2; - -SELECT 1 AS "ONE"; -SELECT 1+1 AS "TWO"; - -RESET ROLE; -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- Don't reset anything if any of the parameter is NULL --- -SELECT pg_stat_statements_reset(NULL); -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- remove query ('SELECT $1+$2 AS "TWO"') executed by regress_stats_user2 --- in the current_database --- -SELECT pg_stat_statements_reset( - (SELECT r.oid FROM pg_roles AS r WHERE r.rolname = 'regress_stats_user2'), - (SELECT d.oid FROM pg_database As d where datname = current_database()), - (SELECT s.queryid FROM pg_stat_statements AS s - WHERE s.query = 'SELECT $1+$2 AS "TWO"' LIMIT 1)); -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- remove query ('SELECT $1 AS "ONE"') executed by two users --- -SELECT pg_stat_statements_reset(0,0,s.queryid) - FROM pg_stat_statements AS s WHERE s.query = 'SELECT $1 AS "ONE"'; -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- remove query of a user (regress_stats_user1) --- -SELECT pg_stat_statements_reset(r.oid) - FROM pg_roles AS r WHERE r.rolname = 'regress_stats_user1'; -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- reset all --- -SELECT pg_stat_statements_reset(0,0,0); -SELECT query, calls, rows FROM pg_stat_statements ORDER BY query COLLATE "C"; - --- --- cleanup --- -DROP ROLE regress_stats_user1; -DROP ROLE regress_stats_user2; -DROP MATERIALIZED VIEW pgss_matv; -DROP TABLE pgss_ctas; -DROP TABLE pgss_select_into; - --- --- [re]plan counting --- -SELECT pg_stat_statements_reset(); -CREATE TABLE test (); -PREPARE prep1 AS SELECT COUNT(*) FROM test; -EXECUTE prep1; -EXECUTE prep1; -EXECUTE prep1; -ALTER TABLE test ADD COLUMN x int; -EXECUTE prep1; -SELECT 42; -SELECT 42; -SELECT 42; -SELECT query, plans, calls, rows FROM pg_stat_statements - WHERE query NOT LIKE 'PREPARE%' ORDER BY query COLLATE "C"; --- for the prepared statement we expect at least one replan, but cache --- invalidations could force more -SELECT query, plans >= 2 AND plans <= calls AS plans_ok, calls, rows FROM pg_stat_statements - WHERE query LIKE 'PREPARE%' ORDER BY query COLLATE "C"; - --- --- access to pg_stat_statements_info view --- -SELECT pg_stat_statements_reset(); -SELECT dealloc FROM pg_stat_statements_info; - --- --- top level handling --- -SET pg_stat_statements.track = 'top'; -DELETE FROM test; -DO $$ -BEGIN - DELETE FROM test; -END; -$$ LANGUAGE plpgsql; -SELECT query, toplevel, plans, calls FROM pg_stat_statements WHERE query LIKE '%DELETE%' ORDER BY query COLLATE "C", toplevel; - -SET pg_stat_statements.track = 'all'; -DELETE FROM test; -DO $$ -BEGIN - DELETE FROM test; -END; -$$ LANGUAGE plpgsql; -SELECT query, toplevel, plans, calls FROM pg_stat_statements WHERE query LIKE '%DELETE%' ORDER BY query COLLATE "C", toplevel; - --- FROM [ONLY] -CREATE TABLE tbl_inh(id integer); -CREATE TABLE tbl_inh_1() INHERITS (tbl_inh); -INSERT INTO tbl_inh_1 SELECT 1; - -SELECT * FROM tbl_inh; -SELECT * FROM ONLY tbl_inh; - -SELECT COUNT(*) FROM pg_stat_statements WHERE query LIKE '%FROM%tbl_inh%'; - --- WITH TIES -CREATE TABLE limitoption AS SELECT 0 AS val FROM generate_series(1, 10); -SELECT * -FROM limitoption -WHERE val < 2 -ORDER BY val -FETCH FIRST 2 ROWS WITH TIES; - -SELECT * -FROM limitoption -WHERE val < 2 -ORDER BY val -FETCH FIRST 2 ROW ONLY; - -SELECT COUNT(*) FROM pg_stat_statements WHERE query LIKE '%FETCH FIRST%'; - --- GROUP BY [DISTINCT] -SELECT a, b, c -FROM (VALUES (1, 2, 3), (4, NULL, 6), (7, 8, 9)) AS t (a, b, c) -GROUP BY ROLLUP(a, b), rollup(a, c) -ORDER BY a, b, c; -SELECT a, b, c -FROM (VALUES (1, 2, 3), (4, NULL, 6), (7, 8, 9)) AS t (a, b, c) -GROUP BY DISTINCT ROLLUP(a, b), rollup(a, c) -ORDER BY a, b, c; - -SELECT COUNT(*) FROM pg_stat_statements WHERE query LIKE '%GROUP BY%ROLLUP%'; - --- GROUPING SET agglevelsup -SELECT ( - SELECT ( - SELECT GROUPING(a,b) FROM (VALUES (1)) v2(c) - ) FROM (VALUES (1,2)) v1(a,b) GROUP BY (a,b) -) FROM (VALUES(6,7)) v3(e,f) GROUP BY ROLLUP(e,f); -SELECT ( - SELECT ( - SELECT GROUPING(e,f) FROM (VALUES (1)) v2(c) - ) FROM (VALUES (1,2)) v1(a,b) GROUP BY (a,b) -) FROM (VALUES(6,7)) v3(e,f) GROUP BY ROLLUP(e,f); - -SELECT COUNT(*) FROM pg_stat_statements WHERE query LIKE '%SELECT GROUPING%'; - -DROP EXTENSION pg_stat_statements; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_surgery%2Fsql%2Fheap_surgery.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_surgery%2Fsql%2Fheap_surgery.sql deleted file mode 100644 index 6526b27535..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_surgery%2Fsql%2Fheap_surgery.sql +++ /dev/null @@ -1,88 +0,0 @@ -create extension pg_surgery; - --- create a normal heap table and insert some rows. --- use a temp table so that vacuum behavior doesn't depend on global xmin -create temp table htab (a int); -insert into htab values (100), (200), (300), (400), (500); - --- test empty TID array -select heap_force_freeze('htab'::regclass, ARRAY[]::tid[]); - --- nothing should be frozen yet -select * from htab where xmin = 2; - --- freeze forcibly -select heap_force_freeze('htab'::regclass, ARRAY['(0, 4)']::tid[]); - --- now we should have one frozen tuple -select ctid, xmax from htab where xmin = 2; - --- kill forcibly -select heap_force_kill('htab'::regclass, ARRAY['(0, 4)']::tid[]); - --- should be gone now -select * from htab where ctid = '(0, 4)'; - --- should now be skipped because it's already dead -select heap_force_kill('htab'::regclass, ARRAY['(0, 4)']::tid[]); -select heap_force_freeze('htab'::regclass, ARRAY['(0, 4)']::tid[]); - --- freeze two TIDs at once while skipping an out-of-range block number -select heap_force_freeze('htab'::regclass, - ARRAY['(0, 1)', '(0, 3)', '(1, 1)']::tid[]); - --- we should now have two frozen tuples -select ctid, xmax from htab where xmin = 2; - --- out-of-range TIDs should be skipped -select heap_force_freeze('htab'::regclass, ARRAY['(0, 0)', '(0, 6)']::tid[]); - --- set up a new table with a redirected line pointer --- use a temp table so that vacuum behavior doesn't depend on global xmin -create temp table htab2(a int); -insert into htab2 values (100); -update htab2 set a = 200; -vacuum htab2; - --- redirected TIDs should be skipped -select heap_force_kill('htab2'::regclass, ARRAY['(0, 1)']::tid[]); - --- now create an unused line pointer -select ctid from htab2; -update htab2 set a = 300; -select ctid from htab2; -vacuum freeze htab2; - --- unused TIDs should be skipped -select heap_force_kill('htab2'::regclass, ARRAY['(0, 2)']::tid[]); - --- multidimensional TID array should be rejected -select heap_force_kill('htab2'::regclass, ARRAY[['(0, 2)']]::tid[]); - --- TID array with nulls should be rejected -select heap_force_kill('htab2'::regclass, ARRAY[NULL]::tid[]); - --- but we should be able to kill the one tuple we have -select heap_force_kill('htab2'::regclass, ARRAY['(0, 3)']::tid[]); - --- materialized view. --- note that we don't commit the transaction, so autovacuum can't interfere. -begin; -create materialized view mvw as select a from generate_series(1, 3) a; - -select * from mvw where xmin = 2; -select heap_force_freeze('mvw'::regclass, ARRAY['(0, 3)']::tid[]); -select * from mvw where xmin = 2; - -select heap_force_kill('mvw'::regclass, ARRAY['(0, 3)']::tid[]); -select * from mvw where ctid = '(0, 3)'; -rollback; - --- check that it fails on an unsupported relkind -create view vw as select 1; -select heap_force_kill('vw'::regclass, ARRAY['(0, 1)']::tid[]); -select heap_force_freeze('vw'::regclass, ARRAY['(0, 1)']::tid[]); - --- cleanup. -drop view vw; -drop extension pg_surgery; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_trgm%2Fpg_trgm--1.2--1.3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_trgm%2Fpg_trgm--1.2--1.3.sql deleted file mode 100644 index 8dc772c407..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_trgm%2Fpg_trgm--1.2--1.3.sql +++ /dev/null @@ -1,65 +0,0 @@ -/* contrib/pg_trgm/pg_trgm--1.2--1.3.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION pg_trgm UPDATE TO '1.3'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('gtrgm_consistent(internal,text,int4,oid,internal)', '{internal,text,int2,oid,internal}'), -('gtrgm_distance(internal,text,int4,oid)', '{internal,text,int2,oid,internal}'), -('gtrgm_union(bytea,internal)', '{internal,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -UPDATE pg_catalog.pg_proc SET - prorettype = (my_schema || '.gtrgm')::pg_catalog.regtype -WHERE oid = pg_catalog.to_regprocedure(my_schema || '.gtrgm_union(internal,internal)'); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER FUNCTION set_limit(float4) PARALLEL UNSAFE; -ALTER FUNCTION show_limit() PARALLEL SAFE; -ALTER FUNCTION show_trgm(text) PARALLEL SAFE; -ALTER FUNCTION similarity(text, text) PARALLEL SAFE; -ALTER FUNCTION similarity_op(text, text) PARALLEL SAFE; -ALTER FUNCTION word_similarity(text, text) PARALLEL SAFE; -ALTER FUNCTION word_similarity_op(text, text) PARALLEL SAFE; -ALTER FUNCTION word_similarity_commutator_op(text, text) PARALLEL SAFE; -ALTER FUNCTION similarity_dist(text, text) PARALLEL SAFE; -ALTER FUNCTION word_similarity_dist_op(text, text) PARALLEL SAFE; -ALTER FUNCTION word_similarity_dist_commutator_op(text, text) PARALLEL SAFE; -ALTER FUNCTION gtrgm_in(cstring) PARALLEL SAFE; -ALTER FUNCTION gtrgm_out(gtrgm) PARALLEL SAFE; -ALTER FUNCTION gtrgm_consistent(internal, text, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_distance(internal, text, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_compress(internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION gtrgm_same(gtrgm, gtrgm, internal) PARALLEL SAFE; -ALTER FUNCTION gin_extract_value_trgm(text, internal) PARALLEL SAFE; -ALTER FUNCTION gin_extract_query_trgm(text, internal, int2, internal, internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION gin_trgm_consistent(internal, int2, text, int4, internal, internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION gin_trgm_triconsistent(internal, int2, text, int4, internal, internal, internal) PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_visibility%2Fsql%2Fpg_visibility.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_visibility%2Fsql%2Fpg_visibility.sql deleted file mode 100644 index ff3538f996..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpg_visibility%2Fsql%2Fpg_visibility.sql +++ /dev/null @@ -1,182 +0,0 @@ -CREATE EXTENSION pg_visibility; - --- --- recently-dropped table --- -\set VERBOSITY sqlstate -BEGIN; -CREATE TABLE droppedtest (c int); -SELECT 'droppedtest'::regclass::oid AS oid \gset -SAVEPOINT q; DROP TABLE droppedtest; RELEASE q; -SAVEPOINT q; SELECT * FROM pg_visibility_map(:oid); ROLLBACK TO q; --- ERROR: could not open relation with OID 16xxx -SAVEPOINT q; SELECT 1; ROLLBACK TO q; -SAVEPOINT q; SELECT 1; ROLLBACK TO q; -SELECT pg_relation_size(:oid), pg_relation_filepath(:oid), - has_table_privilege(:oid, 'SELECT'); -SELECT * FROM pg_visibility_map(:oid); --- ERROR: could not open relation with OID 16xxx -ROLLBACK; -\set VERBOSITY default - --- --- check that using the module's functions with unsupported relations will fail --- - --- partitioned tables (the parent ones) don't have visibility maps -create table test_partitioned (a int) partition by list (a); --- these should all fail -select pg_visibility('test_partitioned', 0); -select pg_visibility_map('test_partitioned'); -select pg_visibility_map_summary('test_partitioned'); -select pg_check_frozen('test_partitioned'); -select pg_truncate_visibility_map('test_partitioned'); - -create table test_partition partition of test_partitioned for values in (1); -create index test_index on test_partition (a); --- indexes do not, so these all fail -select pg_visibility('test_index', 0); -select pg_visibility_map('test_index'); -select pg_visibility_map_summary('test_index'); -select pg_check_frozen('test_index'); -select pg_truncate_visibility_map('test_index'); - -create view test_view as select 1; --- views do not have VMs, so these all fail -select pg_visibility('test_view', 0); -select pg_visibility_map('test_view'); -select pg_visibility_map_summary('test_view'); -select pg_check_frozen('test_view'); -select pg_truncate_visibility_map('test_view'); - -create sequence test_sequence; --- sequences do not have VMs, so these all fail -select pg_visibility('test_sequence', 0); -select pg_visibility_map('test_sequence'); -select pg_visibility_map_summary('test_sequence'); -select pg_check_frozen('test_sequence'); -select pg_truncate_visibility_map('test_sequence'); - -create foreign data wrapper dummy; -create server dummy_server foreign data wrapper dummy; -create foreign table test_foreign_table () server dummy_server; --- foreign tables do not have VMs, so these all fail -select pg_visibility('test_foreign_table', 0); -select pg_visibility_map('test_foreign_table'); -select pg_visibility_map_summary('test_foreign_table'); -select pg_check_frozen('test_foreign_table'); -select pg_truncate_visibility_map('test_foreign_table'); - --- check some of the allowed relkinds -create table regular_table (a int, b text); -alter table regular_table alter column b set storage external; -insert into regular_table values (1, repeat('one', 1000)), (2, repeat('two', 1000)); -vacuum (disable_page_skipping) regular_table; -select count(*) > 0 from pg_visibility('regular_table'); -select count(*) > 0 from pg_visibility((select reltoastrelid from pg_class where relname = 'regular_table')); -truncate regular_table; -select count(*) > 0 from pg_visibility('regular_table'); -select count(*) > 0 from pg_visibility((select reltoastrelid from pg_class where relname = 'regular_table')); - -create materialized view matview_visibility_test as select * from regular_table; -vacuum (disable_page_skipping) matview_visibility_test; -select count(*) > 0 from pg_visibility('matview_visibility_test'); -insert into regular_table values (1), (2); -refresh materialized view matview_visibility_test; -select count(*) > 0 from pg_visibility('matview_visibility_test'); - --- regular tables which are part of a partition *do* have visibility maps -insert into test_partition values (1); -vacuum (disable_page_skipping) test_partition; -select count(*) > 0 from pg_visibility('test_partition', 0); -select count(*) > 0 from pg_visibility_map('test_partition'); -select count(*) > 0 from pg_visibility_map_summary('test_partition'); -select * from pg_check_frozen('test_partition'); -- hopefully none -select pg_truncate_visibility_map('test_partition'); - --- test copy freeze -create table copyfreeze (a int, b char(1500)); - --- load all rows via COPY FREEZE and ensure that all pages are set all-visible --- and all-frozen. -begin; -truncate copyfreeze; -copy copyfreeze from stdin freeze; -1 '1' -2 '2' -3 '3' -4 '4' -5 '5' -6 '6' -7 '7' -8 '8' -9 '9' -10 '10' -11 '11' -12 '12' -\. -commit; -select * from pg_visibility_map('copyfreeze'); -select * from pg_check_frozen('copyfreeze'); - --- load half the rows via regular COPY and rest via COPY FREEZE. The pages --- which are touched by regular COPY must not be set all-visible/all-frozen. On --- the other hand, pages allocated by COPY FREEZE should be marked --- all-frozen/all-visible. -begin; -truncate copyfreeze; -copy copyfreeze from stdin; -1 '1' -2 '2' -3 '3' -4 '4' -5 '5' -6 '6' -\. -copy copyfreeze from stdin freeze; -7 '7' -8 '8' -9 '9' -10 '10' -11 '11' -12 '12' -\. -commit; -select * from pg_visibility_map('copyfreeze'); -select * from pg_check_frozen('copyfreeze'); - --- Try a mix of regular COPY and COPY FREEZE. -begin; -truncate copyfreeze; -copy copyfreeze from stdin freeze; -1 '1' -2 '2' -3 '3' -4 '4' -5 '5' -\. -copy copyfreeze from stdin; -6 '6' -\. -copy copyfreeze from stdin freeze; -7 '7' -8 '8' -9 '9' -10 '10' -11 '11' -12 '12' -\. -commit; -select * from pg_visibility_map('copyfreeze'); -select * from pg_check_frozen('copyfreeze'); - --- cleanup -drop table test_partitioned; -drop view test_view; -drop sequence test_sequence; -drop foreign table test_foreign_table; -drop server dummy_server; -drop foreign data wrapper dummy; -drop materialized view matview_visibility_test; -drop table regular_table; -drop table copyfreeze; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpostgres_fdw%2Fsql%2Fpostgres_fdw.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpostgres_fdw%2Fsql%2Fpostgres_fdw.sql deleted file mode 100644 index 92d1212027..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fpostgres_fdw%2Fsql%2Fpostgres_fdw.sql +++ /dev/null @@ -1,3637 +0,0 @@ --- =================================================================== --- create FDW objects --- =================================================================== - -CREATE EXTENSION postgres_fdw; - -CREATE SERVER testserver1 FOREIGN DATA WRAPPER postgres_fdw; -DO $d$ - BEGIN - EXECUTE $$CREATE SERVER loopback FOREIGN DATA WRAPPER postgres_fdw - OPTIONS (dbname '$$||current_database()||$$', - port '$$||current_setting('port')||$$' - )$$; - EXECUTE $$CREATE SERVER loopback2 FOREIGN DATA WRAPPER postgres_fdw - OPTIONS (dbname '$$||current_database()||$$', - port '$$||current_setting('port')||$$' - )$$; - EXECUTE $$CREATE SERVER loopback3 FOREIGN DATA WRAPPER postgres_fdw - OPTIONS (dbname '$$||current_database()||$$', - port '$$||current_setting('port')||$$' - )$$; - END; -$d$; - -CREATE USER MAPPING FOR public SERVER testserver1 - OPTIONS (user 'value', password 'value'); -CREATE USER MAPPING FOR CURRENT_USER SERVER loopback; -CREATE USER MAPPING FOR CURRENT_USER SERVER loopback2; -CREATE USER MAPPING FOR public SERVER loopback3; - --- =================================================================== --- create objects used through FDW loopback server --- =================================================================== -CREATE TYPE user_enum AS ENUM ('foo', 'bar', 'buz'); -CREATE SCHEMA "S 1"; -CREATE TABLE "S 1"."T 1" ( - "C 1" int NOT NULL, - c2 int NOT NULL, - c3 text, - c4 timestamptz, - c5 timestamp, - c6 varchar(10), - c7 char(10), - c8 user_enum, - CONSTRAINT t1_pkey PRIMARY KEY ("C 1") -); -CREATE TABLE "S 1"."T 2" ( - c1 int NOT NULL, - c2 text, - CONSTRAINT t2_pkey PRIMARY KEY (c1) -); -CREATE TABLE "S 1"."T 3" ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text, - CONSTRAINT t3_pkey PRIMARY KEY (c1) -); -CREATE TABLE "S 1"."T 4" ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text, - CONSTRAINT t4_pkey PRIMARY KEY (c1) -); - --- Disable autovacuum for these tables to avoid unexpected effects of that -ALTER TABLE "S 1"."T 1" SET (autovacuum_enabled = 'false'); -ALTER TABLE "S 1"."T 2" SET (autovacuum_enabled = 'false'); -ALTER TABLE "S 1"."T 3" SET (autovacuum_enabled = 'false'); -ALTER TABLE "S 1"."T 4" SET (autovacuum_enabled = 'false'); - -INSERT INTO "S 1"."T 1" - SELECT id, - id % 10, - to_char(id, 'FM00000'), - '1970-01-01'::timestamptz + ((id % 100) || ' days')::interval, - '1970-01-01'::timestamp + ((id % 100) || ' days')::interval, - id % 10, - id % 10, - 'foo'::user_enum - FROM generate_series(1, 1000) id; -INSERT INTO "S 1"."T 2" - SELECT id, - 'AAA' || to_char(id, 'FM000') - FROM generate_series(1, 100) id; -INSERT INTO "S 1"."T 3" - SELECT id, - id + 1, - 'AAA' || to_char(id, 'FM000') - FROM generate_series(1, 100) id; -DELETE FROM "S 1"."T 3" WHERE c1 % 2 != 0; -- delete for outer join tests -INSERT INTO "S 1"."T 4" - SELECT id, - id + 1, - 'AAA' || to_char(id, 'FM000') - FROM generate_series(1, 100) id; -DELETE FROM "S 1"."T 4" WHERE c1 % 3 != 0; -- delete for outer join tests - -ANALYZE "S 1"."T 1"; -ANALYZE "S 1"."T 2"; -ANALYZE "S 1"."T 3"; -ANALYZE "S 1"."T 4"; - --- =================================================================== --- create foreign tables --- =================================================================== -CREATE FOREIGN TABLE ft1 ( - c0 int, - c1 int NOT NULL, - c2 int NOT NULL, - c3 text, - c4 timestamptz, - c5 timestamp, - c6 varchar(10), - c7 char(10) default 'ft1', - c8 user_enum -) SERVER loopback; -ALTER FOREIGN TABLE ft1 DROP COLUMN c0; - -CREATE FOREIGN TABLE ft2 ( - c1 int NOT NULL, - c2 int NOT NULL, - cx int, - c3 text, - c4 timestamptz, - c5 timestamp, - c6 varchar(10), - c7 char(10) default 'ft2', - c8 user_enum -) SERVER loopback; -ALTER FOREIGN TABLE ft2 DROP COLUMN cx; - -CREATE FOREIGN TABLE ft4 ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text -) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 3'); - -CREATE FOREIGN TABLE ft5 ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text -) SERVER loopback OPTIONS (schema_name 'S 1', table_name 'T 4'); - -CREATE FOREIGN TABLE ft6 ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text -) SERVER loopback2 OPTIONS (schema_name 'S 1', table_name 'T 4'); - -CREATE FOREIGN TABLE ft7 ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text -) SERVER loopback3 OPTIONS (schema_name 'S 1', table_name 'T 4'); - --- =================================================================== --- tests for validator --- =================================================================== --- requiressl and some other parameters are omitted because --- valid values for them depend on configure options -ALTER SERVER testserver1 OPTIONS ( - use_remote_estimate 'false', - updatable 'true', - fdw_startup_cost '123.456', - fdw_tuple_cost '0.123', - service 'value', - connect_timeout 'value', - dbname 'value', - host 'value', - hostaddr 'value', - port 'value', - --client_encoding 'value', - application_name 'value', - --fallback_application_name 'value', - keepalives 'value', - keepalives_idle 'value', - keepalives_interval 'value', - tcp_user_timeout 'value', - -- requiressl 'value', - sslcompression 'value', - sslmode 'value', - sslcert 'value', - sslkey 'value', - sslrootcert 'value', - sslcrl 'value', - --requirepeer 'value', - krbsrvname 'value', - gsslib 'value' - --replication 'value' -); - --- Error, invalid list syntax -ALTER SERVER testserver1 OPTIONS (ADD extensions 'foo; bar'); - --- OK but gets a warning -ALTER SERVER testserver1 OPTIONS (ADD extensions 'foo, bar'); -ALTER SERVER testserver1 OPTIONS (DROP extensions); - -ALTER USER MAPPING FOR public SERVER testserver1 - OPTIONS (DROP user, DROP password); - --- Attempt to add a valid option that's not allowed in a user mapping -ALTER USER MAPPING FOR public SERVER testserver1 - OPTIONS (ADD sslmode 'require'); - --- But we can add valid ones fine -ALTER USER MAPPING FOR public SERVER testserver1 - OPTIONS (ADD sslpassword 'dummy'); - --- Ensure valid options we haven't used in a user mapping yet are --- permitted to check validation. -ALTER USER MAPPING FOR public SERVER testserver1 - OPTIONS (ADD sslkey 'value', ADD sslcert 'value'); - -ALTER FOREIGN TABLE ft1 OPTIONS (schema_name 'S 1', table_name 'T 1'); -ALTER FOREIGN TABLE ft2 OPTIONS (schema_name 'S 1', table_name 'T 1'); -ALTER FOREIGN TABLE ft1 ALTER COLUMN c1 OPTIONS (column_name 'C 1'); -ALTER FOREIGN TABLE ft2 ALTER COLUMN c1 OPTIONS (column_name 'C 1'); -\det+ - --- Test that alteration of server options causes reconnection --- Remote's errors might be non-English, so hide them to ensure stable results -\set VERBOSITY terse -SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work -ALTER SERVER loopback OPTIONS (SET dbname 'no such database'); -SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should fail -DO $d$ - BEGIN - EXECUTE $$ALTER SERVER loopback - OPTIONS (SET dbname '$$||current_database()||$$')$$; - END; -$d$; -SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again - --- Test that alteration of user mapping options causes reconnection -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback - OPTIONS (ADD user 'no such user'); -SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should fail -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback - OPTIONS (DROP user); -SELECT c3, c4 FROM ft1 ORDER BY c3, c1 LIMIT 1; -- should work again -\set VERBOSITY default - --- Now we should be able to run ANALYZE. --- To exercise multiple code paths, we use local stats on ft1 --- and remote-estimate mode on ft2. -ANALYZE ft1; -ALTER FOREIGN TABLE ft2 OPTIONS (use_remote_estimate 'true'); - --- =================================================================== --- test error case for create publication on foreign table --- =================================================================== -CREATE PUBLICATION testpub_ftbl FOR TABLE ft1; -- should fail - --- =================================================================== --- simple queries --- =================================================================== --- single table without alias -EXPLAIN (COSTS OFF) SELECT * FROM ft1 ORDER BY c3, c1 OFFSET 100 LIMIT 10; -SELECT * FROM ft1 ORDER BY c3, c1 OFFSET 100 LIMIT 10; --- single table with alias - also test that tableoid sort is not pushed to remote side -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 ORDER BY t1.c3, t1.c1, t1.tableoid OFFSET 100 LIMIT 10; -SELECT * FROM ft1 t1 ORDER BY t1.c3, t1.c1, t1.tableoid OFFSET 100 LIMIT 10; --- whole-row reference -EXPLAIN (VERBOSE, COSTS OFF) SELECT t1 FROM ft1 t1 ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; -SELECT t1 FROM ft1 t1 ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; --- empty result -SELECT * FROM ft1 WHERE false; --- with WHERE clause -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 101 AND t1.c6 = '1' AND t1.c7 >= '1'; -SELECT * FROM ft1 t1 WHERE t1.c1 = 101 AND t1.c6 = '1' AND t1.c7 >= '1'; --- with FOR UPDATE/SHARE -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 101 FOR UPDATE; -SELECT * FROM ft1 t1 WHERE c1 = 101 FOR UPDATE; -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = 102 FOR SHARE; -SELECT * FROM ft1 t1 WHERE c1 = 102 FOR SHARE; --- aggregate -SELECT COUNT(*) FROM ft1 t1; --- subquery -SELECT * FROM ft1 t1 WHERE t1.c3 IN (SELECT c3 FROM ft2 t2 WHERE c1 <= 10) ORDER BY c1; --- subquery+MAX -SELECT * FROM ft1 t1 WHERE t1.c3 = (SELECT MAX(c3) FROM ft2 t2) ORDER BY c1; --- used in CTE -WITH t1 AS (SELECT * FROM ft1 WHERE c1 <= 10) SELECT t2.c1, t2.c2, t2.c3, t2.c4 FROM t1, ft2 t2 WHERE t1.c1 = t2.c1 ORDER BY t1.c1; --- fixed values -SELECT 'fixed', NULL FROM ft1 t1 WHERE c1 = 1; --- Test forcing the remote server to produce sorted data for a merge join. -SET enable_hashjoin TO false; -SET enable_nestloop TO false; --- inner join; expressions in the clauses appear in the equivalence class list -EXPLAIN (VERBOSE, COSTS OFF) - SELECT t1.c1, t2."C 1" FROM ft2 t1 JOIN "S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100 LIMIT 10; -SELECT t1.c1, t2."C 1" FROM ft2 t1 JOIN "S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100 LIMIT 10; --- outer join; expressions in the clauses do not appear in equivalence class --- list but no output change as compared to the previous query -EXPLAIN (VERBOSE, COSTS OFF) - SELECT t1.c1, t2."C 1" FROM ft2 t1 LEFT JOIN "S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100 LIMIT 10; -SELECT t1.c1, t2."C 1" FROM ft2 t1 LEFT JOIN "S 1"."T 1" t2 ON (t1.c1 = t2."C 1") OFFSET 100 LIMIT 10; --- A join between local table and foreign join. ORDER BY clause is added to the --- foreign join so that the local table can be joined using merge join strategy. -EXPLAIN (VERBOSE, COSTS OFF) - SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10; -SELECT t1."C 1" FROM "S 1"."T 1" t1 left join ft1 t2 join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10; --- Test similar to above, except that the full join prevents any equivalence --- classes from being merged. This produces single relation equivalence classes --- included in join restrictions. -EXPLAIN (VERBOSE, COSTS OFF) - SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10; -SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 left join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10; --- Test similar to above with all full outer joins -EXPLAIN (VERBOSE, COSTS OFF) - SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10; -SELECT t1."C 1", t2.c1, t3.c1 FROM "S 1"."T 1" t1 full join ft1 t2 full join ft2 t3 on (t2.c1 = t3.c1) on (t3.c1 = t1."C 1") OFFSET 100 LIMIT 10; -RESET enable_hashjoin; -RESET enable_nestloop; - --- Test executing assertion in estimate_path_cost_size() that makes sure that --- retrieved_rows for foreign rel re-used to cost pre-sorted foreign paths is --- a sensible value even when the rel has tuples=0 -CREATE TABLE loct_empty (c1 int NOT NULL, c2 text); -CREATE FOREIGN TABLE ft_empty (c1 int NOT NULL, c2 text) - SERVER loopback OPTIONS (table_name 'loct_empty'); -INSERT INTO loct_empty - SELECT id, 'AAA' || to_char(id, 'FM000') FROM generate_series(1, 100) id; -DELETE FROM loct_empty; -ANALYZE ft_empty; -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft_empty ORDER BY c1; - --- =================================================================== --- WHERE with remotely-executable conditions --- =================================================================== -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 1; -- Var, OpExpr(b), Const -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE t1.c1 = 100 AND t1.c2 = 0; -- BoolExpr -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 IS NULL; -- NullTest -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 IS NOT NULL; -- NullTest -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE round(abs(c1), 0) = 1; -- FuncExpr -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = -c1; -- OpExpr(l) -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE (c1 IS NOT NULL) IS DISTINCT FROM (c1 IS NOT NULL); -- DistinctExpr -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = ANY(ARRAY[c2, 1, c1 + 0]); -- ScalarArrayOpExpr -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c1 = (ARRAY[c1,c2,3])[1]; -- SubscriptingRef -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c6 = E'foo''s\\bar'; -- check special chars -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 t1 WHERE c8 = 'foo'; -- can't be sent to remote --- parameterized remote path for foreign table -EXPLAIN (VERBOSE, COSTS OFF) - SELECT * FROM "S 1"."T 1" a, ft2 b WHERE a."C 1" = 47 AND b.c1 = a.c2; -SELECT * FROM ft2 a, ft2 b WHERE a.c1 = 47 AND b.c1 = a.c2; - --- check both safe and unsafe join conditions -EXPLAIN (VERBOSE, COSTS OFF) - SELECT * FROM ft2 a, ft2 b - WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); -SELECT * FROM ft2 a, ft2 b -WHERE a.c2 = 6 AND b.c1 = a.c1 AND a.c8 = 'foo' AND b.c7 = upper(a.c7); --- bug before 9.3.5 due to sloppy handling of remote-estimate parameters -SELECT * FROM ft1 WHERE c1 = ANY (ARRAY(SELECT c1 FROM ft2 WHERE c1 < 5)); -SELECT * FROM ft2 WHERE c1 = ANY (ARRAY(SELECT c1 FROM ft1 WHERE c1 < 5)); --- we should not push order by clause with volatile expressions or unsafe --- collations -EXPLAIN (VERBOSE, COSTS OFF) - SELECT * FROM ft2 ORDER BY ft2.c1, random(); -EXPLAIN (VERBOSE, COSTS OFF) - SELECT * FROM ft2 ORDER BY ft2.c1, ft2.c3 collate "C"; - --- user-defined operator/function -CREATE FUNCTION postgres_fdw_abs(int) RETURNS int AS $$ -BEGIN -RETURN abs($1); -END -$$ LANGUAGE plpgsql IMMUTABLE; -CREATE OPERATOR === ( - LEFTARG = int, - RIGHTARG = int, - PROCEDURE = int4eq, - COMMUTATOR = === -); - --- built-in operators and functions can be shipped for remote execution -EXPLAIN (VERBOSE, COSTS OFF) - SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = abs(t1.c2); -SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = abs(t1.c2); -EXPLAIN (VERBOSE, COSTS OFF) - SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = t1.c2; -SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = t1.c2; - --- by default, user-defined ones cannot -EXPLAIN (VERBOSE, COSTS OFF) - SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); -SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); -EXPLAIN (VERBOSE, COSTS OFF) - SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; -SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; - --- ORDER BY can be shipped, though -EXPLAIN (VERBOSE, COSTS OFF) - SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 order by t1.c2 limit 1; -SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 order by t1.c2 limit 1; - --- but let's put them in an extension ... -ALTER EXTENSION postgres_fdw ADD FUNCTION postgres_fdw_abs(int); -ALTER EXTENSION postgres_fdw ADD OPERATOR === (int, int); -ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw'); - --- ... now they can be shipped -EXPLAIN (VERBOSE, COSTS OFF) - SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); -SELECT count(c3) FROM ft1 t1 WHERE t1.c1 = postgres_fdw_abs(t1.c2); -EXPLAIN (VERBOSE, COSTS OFF) - SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; -SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; - --- and both ORDER BY and LIMIT can be shipped -EXPLAIN (VERBOSE, COSTS OFF) - SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 order by t1.c2 limit 1; -SELECT * FROM ft1 t1 WHERE t1.c1 === t1.c2 order by t1.c2 limit 1; - --- Test CASE pushdown -EXPLAIN (VERBOSE, COSTS OFF) -SELECT c1,c2,c3 FROM ft2 WHERE CASE WHEN c1 > 990 THEN c1 END < 1000 ORDER BY c1; -SELECT c1,c2,c3 FROM ft2 WHERE CASE WHEN c1 > 990 THEN c1 END < 1000 ORDER BY c1; - --- Nested CASE -EXPLAIN (VERBOSE, COSTS OFF) -SELECT c1,c2,c3 FROM ft2 WHERE CASE CASE WHEN c2 > 0 THEN c2 END WHEN 100 THEN 601 WHEN c2 THEN c2 ELSE 0 END > 600 ORDER BY c1; - -SELECT c1,c2,c3 FROM ft2 WHERE CASE CASE WHEN c2 > 0 THEN c2 END WHEN 100 THEN 601 WHEN c2 THEN c2 ELSE 0 END > 600 ORDER BY c1; - --- CASE arg WHEN -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE c1 > (CASE mod(c1, 4) WHEN 0 THEN 1 WHEN 2 THEN 50 ELSE 100 END); - --- CASE cannot be pushed down because of unshippable arg clause -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE c1 > (CASE random()::integer WHEN 0 THEN 1 WHEN 2 THEN 50 ELSE 100 END); - --- these are shippable -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE CASE c6 WHEN 'foo' THEN true ELSE c3 < 'bar' END; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE CASE c3 WHEN c6 THEN true ELSE c3 < 'bar' END; - --- but this is not because of collation -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE CASE c3 COLLATE "C" WHEN c6 THEN true ELSE c3 < 'bar' END; - --- =================================================================== --- JOIN queries --- =================================================================== --- Analyze ft4 and ft5 so that we have better statistics. These tables do not --- have use_remote_estimate set. -ANALYZE ft4; -ANALYZE ft5; - --- join two tables -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; --- join three tables -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) JOIN ft4 t3 ON (t3.c1 = t1.c1) ORDER BY t1.c3, t1.c1 OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) JOIN ft4 t3 ON (t3.c1 = t1.c1) ORDER BY t1.c3, t1.c1 OFFSET 10 LIMIT 10; --- left outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; --- left outer join three tables -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- left outer join + placement of clauses. --- clauses within the nullable side are not pulled up, but top level clause on --- non-nullable side is pushed into non-nullable side -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFT JOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) WHERE t1.c1 < 10; -SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFT JOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) WHERE t1.c1 < 10; --- clauses within the nullable side are not pulled up, but the top level clause --- on nullable side is not pushed down into nullable side -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFT JOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) - WHERE (t2.c1 < 10 OR t2.c1 IS NULL) AND t1.c1 < 10; -SELECT t1.c1, t1.c2, t2.c1, t2.c2 FROM ft4 t1 LEFT JOIN (SELECT * FROM ft5 WHERE c1 < 10) t2 ON (t1.c1 = t2.c1) - WHERE (t2.c1 < 10 OR t2.c1 IS NULL) AND t1.c1 < 10; --- right outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft5 t1 RIGHT JOIN ft4 t2 ON (t1.c1 = t2.c1) ORDER BY t2.c1, t1.c1 OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft5 t1 RIGHT JOIN ft4 t2 ON (t1.c1 = t2.c1) ORDER BY t2.c1, t1.c1 OFFSET 10 LIMIT 10; --- right outer join three tables -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- full outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 45 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 45 LIMIT 10; --- full outer join with restrictions on the joining relations --- a. the joining relations are both base relations -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1; -SELECT t1.c1, t2.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT 1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t2 ON (TRUE) OFFSET 10 LIMIT 10; -SELECT 1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t2 ON (TRUE) OFFSET 10 LIMIT 10; --- b. one of the joining relations is a base relation and the other is a join --- relation -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT t2.c1, t3.c1 FROM ft4 t2 LEFT JOIN ft5 t3 ON (t2.c1 = t3.c1) WHERE (t2.c1 between 50 and 60)) ss(a, b) ON (t1.c1 = ss.a) ORDER BY t1.c1, ss.a, ss.b; -SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT t2.c1, t3.c1 FROM ft4 t2 LEFT JOIN ft5 t3 ON (t2.c1 = t3.c1) WHERE (t2.c1 between 50 and 60)) ss(a, b) ON (t1.c1 = ss.a) ORDER BY t1.c1, ss.a, ss.b; --- c. test deparsing the remote query as nested subqueries -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT t2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 IS NULL OR t2.c1 IS NOT NULL) ss(a, b) ON (t1.c1 = ss.a) ORDER BY t1.c1, ss.a, ss.b; -SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t1 FULL JOIN (SELECT t2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 IS NULL OR t2.c1 IS NOT NULL) ss(a, b) ON (t1.c1 = ss.a) ORDER BY t1.c1, ss.a, ss.b; --- d. test deparsing rowmarked relations as subqueries -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM "S 1"."T 3" WHERE c1 = 50) t1 INNER JOIN (SELECT t2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 IS NULL OR t2.c1 IS NOT NULL) ss(a, b) ON (TRUE) ORDER BY t1.c1, ss.a, ss.b FOR UPDATE OF t1; -SELECT t1.c1, ss.a, ss.b FROM (SELECT c1 FROM "S 1"."T 3" WHERE c1 = 50) t1 INNER JOIN (SELECT t2.c1, t3.c1 FROM (SELECT c1 FROM ft4 WHERE c1 between 50 and 60) t2 FULL JOIN (SELECT c1 FROM ft5 WHERE c1 between 50 and 60) t3 ON (t2.c1 = t3.c1) WHERE t2.c1 IS NULL OR t2.c1 IS NOT NULL) ss(a, b) ON (TRUE) ORDER BY t1.c1, ss.a, ss.b FOR UPDATE OF t1; --- full outer join + inner join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1, t3.c1 FROM ft4 t1 INNER JOIN ft5 t2 ON (t1.c1 = t2.c1 + 1 and t1.c1 between 50 and 60) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) ORDER BY t1.c1, t2.c1, t3.c1 LIMIT 10; -SELECT t1.c1, t2.c1, t3.c1 FROM ft4 t1 INNER JOIN ft5 t2 ON (t1.c1 = t2.c1 + 1 and t1.c1 between 50 and 60) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) ORDER BY t1.c1, t2.c1, t3.c1 LIMIT 10; --- full outer join three tables -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- full outer join + right outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- right outer join + full outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- full outer join + left outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- left outer join + full outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) FULL JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SET enable_memoize TO off; --- right outer join + left outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 RIGHT JOIN ft2 t2 ON (t1.c1 = t2.c1) LEFT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -RESET enable_memoize; --- left outer join + right outer join -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c2, t3.c3 FROM ft2 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) RIGHT JOIN ft4 t3 ON (t2.c1 = t3.c1) OFFSET 10 LIMIT 10; --- full outer join + WHERE clause, only matched rows -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) WHERE (t1.c1 = t2.c1 OR t1.c1 IS NULL) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft4 t1 FULL JOIN ft5 t2 ON (t1.c1 = t2.c1) WHERE (t1.c1 = t2.c1 OR t1.c1 IS NULL) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; --- full outer join + WHERE clause with shippable extensions set -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t1.c3 FROM ft1 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE postgres_fdw_abs(t1.c1) > 0 OFFSET 10 LIMIT 10; -ALTER SERVER loopback OPTIONS (DROP extensions); --- full outer join + WHERE clause with shippable extensions not set -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2, t1.c3 FROM ft1 t1 FULL JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE postgres_fdw_abs(t1.c1) > 0 OFFSET 10 LIMIT 10; -ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw'); --- join two tables with FOR UPDATE clause --- tests whole-row reference for row marks -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR UPDATE OF t1; -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR UPDATE OF t1; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR UPDATE; -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR UPDATE; --- join two tables with FOR SHARE clause -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR SHARE OF t1; -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR SHARE OF t1; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR SHARE; -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR SHARE; --- join in CTE -EXPLAIN (VERBOSE, COSTS OFF) -WITH t (c1_1, c1_3, c2_1) AS MATERIALIZED (SELECT t1.c1, t1.c3, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) SELECT c1_1, c2_1 FROM t ORDER BY c1_3, c1_1 OFFSET 100 LIMIT 10; -WITH t (c1_1, c1_3, c2_1) AS MATERIALIZED (SELECT t1.c1, t1.c3, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) SELECT c1_1, c2_1 FROM t ORDER BY c1_3, c1_1 OFFSET 100 LIMIT 10; --- ctid with whole-row reference -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.ctid, t1, t2, t1.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; --- SEMI JOIN, not pushed down -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1 FROM ft1 t1 WHERE EXISTS (SELECT 1 FROM ft2 t2 WHERE t1.c1 = t2.c1) ORDER BY t1.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1 FROM ft1 t1 WHERE EXISTS (SELECT 1 FROM ft2 t2 WHERE t1.c1 = t2.c1) ORDER BY t1.c1 OFFSET 100 LIMIT 10; --- ANTI JOIN, not pushed down -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1 FROM ft1 t1 WHERE NOT EXISTS (SELECT 1 FROM ft2 t2 WHERE t1.c1 = t2.c2) ORDER BY t1.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1 FROM ft1 t1 WHERE NOT EXISTS (SELECT 1 FROM ft2 t2 WHERE t1.c1 = t2.c2) ORDER BY t1.c1 OFFSET 100 LIMIT 10; --- CROSS JOIN can be pushed down -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 CROSS JOIN ft2 t2 ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft1 t1 CROSS JOIN ft2 t2 ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10; --- different server, not pushed down. No result expected. -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft5 t1 JOIN ft6 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10; --- unsafe join conditions (c8 has a UDT), not pushed down. Practically a CROSS --- JOIN since c8 in both tables has same value. -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 LEFT JOIN ft2 t2 ON (t1.c8 = t2.c8) ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft1 t1 LEFT JOIN ft2 t2 ON (t1.c8 = t2.c8) ORDER BY t1.c1, t2.c1 OFFSET 100 LIMIT 10; --- unsafe conditions on one side (c8 has a UDT), not pushed down. -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = 'foo' ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft1 t1 LEFT JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = 'foo' ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; --- join where unsafe to pushdown condition in WHERE clause has a column not --- in the SELECT clause. In this test unsafe clause needs to have column --- references from both joining sides so that the clause is not pushed down --- into one of the joining sides. -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = t2.c8 ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; -SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) WHERE t1.c8 = t2.c8 ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10; --- Aggregate after UNION, for testing setrefs -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1c1, avg(t1c1 + t2c1) FROM (SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) UNION SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) AS t (t1c1, t2c1) GROUP BY t1c1 ORDER BY t1c1 OFFSET 100 LIMIT 10; -SELECT t1c1, avg(t1c1 + t2c1) FROM (SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) UNION SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1)) AS t (t1c1, t2c1) GROUP BY t1c1 ORDER BY t1c1 OFFSET 100 LIMIT 10; --- join with lateral reference -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1."C 1" FROM "S 1"."T 1" t1, LATERAL (SELECT DISTINCT t2.c1, t3.c1 FROM ft1 t2, ft2 t3 WHERE t2.c1 = t3.c1 AND t2.c2 = t1.c2) q ORDER BY t1."C 1" OFFSET 10 LIMIT 10; -SELECT t1."C 1" FROM "S 1"."T 1" t1, LATERAL (SELECT DISTINCT t2.c1, t3.c1 FROM ft1 t2, ft2 t3 WHERE t2.c1 = t3.c1 AND t2.c2 = t1.c2) q ORDER BY t1."C 1" OFFSET 10 LIMIT 10; - --- non-Var items in targetlist of the nullable rel of a join preventing --- push-down in some cases --- unable to push {ft1, ft2} -EXPLAIN (VERBOSE, COSTS OFF) -SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; -SELECT q.a, ft2.c1 FROM (SELECT 13 FROM ft1 WHERE c1 = 13) q(a) RIGHT JOIN ft2 ON (q.a = ft2.c1) WHERE ft2.c1 BETWEEN 10 AND 15; - --- ok to push {ft1, ft2} but not {ft1, ft2, ft4} -EXPLAIN (VERBOSE, COSTS OFF) -SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT JOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN 10 AND 15; -SELECT ft4.c1, q.* FROM ft4 LEFT JOIN (SELECT 13, ft1.c1, ft2.c1 FROM ft1 RIGHT JOIN ft2 ON (ft1.c1 = ft2.c1) WHERE ft1.c1 = 12) q(a, b, c) ON (ft4.c1 = q.b) WHERE ft4.c1 BETWEEN 10 AND 15; - --- join with nullable side with some columns with null values -UPDATE ft5 SET c3 = null where c1 % 9 = 0; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1; -SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1; - --- multi-way join involving multiple merge joins --- (this case used to have EPQ-related planning problems) -CREATE TABLE local_tbl (c1 int NOT NULL, c2 int NOT NULL, c3 text, CONSTRAINT local_tbl_pkey PRIMARY KEY (c1)); -INSERT INTO local_tbl SELECT id, id % 10, to_char(id, 'FM0000') FROM generate_series(1, 1000) id; -ANALYZE local_tbl; -SET enable_nestloop TO false; -SET enable_hashjoin TO false; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1, ft2, ft4, ft5, local_tbl WHERE ft1.c1 = ft2.c1 AND ft1.c2 = ft4.c1 - AND ft1.c2 = ft5.c1 AND ft1.c2 = local_tbl.c1 AND ft1.c1 < 100 AND ft2.c1 < 100 FOR UPDATE; -SELECT * FROM ft1, ft2, ft4, ft5, local_tbl WHERE ft1.c1 = ft2.c1 AND ft1.c2 = ft4.c1 - AND ft1.c2 = ft5.c1 AND ft1.c2 = local_tbl.c1 AND ft1.c1 < 100 AND ft2.c1 < 100 FOR UPDATE; -RESET enable_nestloop; -RESET enable_hashjoin; -DROP TABLE local_tbl; - --- check join pushdown in situations where multiple userids are involved -CREATE ROLE regress_view_owner SUPERUSER; -CREATE USER MAPPING FOR regress_view_owner SERVER loopback; -GRANT SELECT ON ft4 TO regress_view_owner; -GRANT SELECT ON ft5 TO regress_view_owner; - -CREATE VIEW v4 AS SELECT * FROM ft4; -CREATE VIEW v5 AS SELECT * FROM ft5; -ALTER VIEW v5 OWNER TO regress_view_owner; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can't be pushed down, different view owners -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -ALTER VIEW v4 OWNER TO regress_view_owner; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can be pushed down -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN v5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can't be pushed down, view owner not current user -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -ALTER VIEW v4 OWNER TO CURRENT_USER; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -- can be pushed down -SELECT t1.c1, t2.c2 FROM v4 t1 LEFT JOIN ft5 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c1, t2.c1 OFFSET 10 LIMIT 10; -ALTER VIEW v4 OWNER TO regress_view_owner; - --- cleanup -DROP OWNED BY regress_view_owner; -DROP ROLE regress_view_owner; - - --- =================================================================== --- Aggregate and grouping queries --- =================================================================== - --- Simple aggregates -explain (verbose, costs off) -select count(c6), sum(c1), avg(c1), min(c2), max(c1), stddev(c2), sum(c1) * (random() <= 1)::int as sum2 from ft1 where c2 < 5 group by c2 order by 1, 2; -select count(c6), sum(c1), avg(c1), min(c2), max(c1), stddev(c2), sum(c1) * (random() <= 1)::int as sum2 from ft1 where c2 < 5 group by c2 order by 1, 2; - -explain (verbose, costs off) -select count(c6), sum(c1), avg(c1), min(c2), max(c1), stddev(c2), sum(c1) * (random() <= 1)::int as sum2 from ft1 where c2 < 5 group by c2 order by 1, 2 limit 1; -select count(c6), sum(c1), avg(c1), min(c2), max(c1), stddev(c2), sum(c1) * (random() <= 1)::int as sum2 from ft1 where c2 < 5 group by c2 order by 1, 2 limit 1; - --- Aggregate is not pushed down as aggregation contains random() -explain (verbose, costs off) -select sum(c1 * (random() <= 1)::int) as sum, avg(c1) from ft1; - --- Aggregate over join query -explain (verbose, costs off) -select count(*), sum(t1.c1), avg(t2.c1) from ft1 t1 inner join ft1 t2 on (t1.c2 = t2.c2) where t1.c2 = 6; -select count(*), sum(t1.c1), avg(t2.c1) from ft1 t1 inner join ft1 t2 on (t1.c2 = t2.c2) where t1.c2 = 6; - --- Not pushed down due to local conditions present in underneath input rel -explain (verbose, costs off) -select sum(t1.c1), count(t2.c1) from ft1 t1 inner join ft2 t2 on (t1.c1 = t2.c1) where ((t1.c1 * t2.c1)/(t1.c1 * t2.c1)) * random() <= 1; - --- GROUP BY clause having expressions -explain (verbose, costs off) -select c2/2, sum(c2) * (c2/2) from ft1 group by c2/2 order by c2/2; -select c2/2, sum(c2) * (c2/2) from ft1 group by c2/2 order by c2/2; - --- Aggregates in subquery are pushed down. -explain (verbose, costs off) -select count(x.a), sum(x.a) from (select c2 a, sum(c1) b from ft1 group by c2, sqrt(c1) order by 1, 2) x; -select count(x.a), sum(x.a) from (select c2 a, sum(c1) b from ft1 group by c2, sqrt(c1) order by 1, 2) x; - --- Aggregate is still pushed down by taking unshippable expression out -explain (verbose, costs off) -select c2 * (random() <= 1)::int as sum1, sum(c1) * c2 as sum2 from ft1 group by c2 order by 1, 2; -select c2 * (random() <= 1)::int as sum1, sum(c1) * c2 as sum2 from ft1 group by c2 order by 1, 2; - --- Aggregate with unshippable GROUP BY clause are not pushed -explain (verbose, costs off) -select c2 * (random() <= 1)::int as c2 from ft2 group by c2 * (random() <= 1)::int order by 1; - --- GROUP BY clause in various forms, cardinal, alias and constant expression -explain (verbose, costs off) -select count(c2) w, c2 x, 5 y, 7.0 z from ft1 group by 2, y, 9.0::int order by 2; -select count(c2) w, c2 x, 5 y, 7.0 z from ft1 group by 2, y, 9.0::int order by 2; - --- GROUP BY clause referring to same column multiple times --- Also, ORDER BY contains an aggregate function -explain (verbose, costs off) -select c2, c2 from ft1 where c2 > 6 group by 1, 2 order by sum(c1); -select c2, c2 from ft1 where c2 > 6 group by 1, 2 order by sum(c1); - --- Testing HAVING clause shippability -explain (verbose, costs off) -select c2, sum(c1) from ft2 group by c2 having avg(c1) < 500 and sum(c1) < 49800 order by c2; -select c2, sum(c1) from ft2 group by c2 having avg(c1) < 500 and sum(c1) < 49800 order by c2; - --- Unshippable HAVING clause will be evaluated locally, and other qual in HAVING clause is pushed down -explain (verbose, costs off) -select count(*) from (select c5, count(c1) from ft1 group by c5, sqrt(c2) having (avg(c1) / avg(c1)) * random() <= 1 and avg(c1) < 500) x; -select count(*) from (select c5, count(c1) from ft1 group by c5, sqrt(c2) having (avg(c1) / avg(c1)) * random() <= 1 and avg(c1) < 500) x; - --- Aggregate in HAVING clause is not pushable, and thus aggregation is not pushed down -explain (verbose, costs off) -select sum(c1) from ft1 group by c2 having avg(c1 * (random() <= 1)::int) > 100 order by 1; - --- Remote aggregate in combination with a local Param (for the output --- of an initplan) can be trouble, per bug #15781 -explain (verbose, costs off) -select exists(select 1 from pg_enum), sum(c1) from ft1; -select exists(select 1 from pg_enum), sum(c1) from ft1; - -explain (verbose, costs off) -select exists(select 1 from pg_enum), sum(c1) from ft1 group by 1; -select exists(select 1 from pg_enum), sum(c1) from ft1 group by 1; - - --- Testing ORDER BY, DISTINCT, FILTER, Ordered-sets and VARIADIC within aggregates - --- ORDER BY within aggregate, same column used to order -explain (verbose, costs off) -select array_agg(c1 order by c1) from ft1 where c1 < 100 group by c2 order by 1; -select array_agg(c1 order by c1) from ft1 where c1 < 100 group by c2 order by 1; - --- ORDER BY within aggregate, different column used to order also using DESC -explain (verbose, costs off) -select array_agg(c5 order by c1 desc) from ft2 where c2 = 6 and c1 < 50; -select array_agg(c5 order by c1 desc) from ft2 where c2 = 6 and c1 < 50; - --- DISTINCT within aggregate -explain (verbose, costs off) -select array_agg(distinct (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20 or (t1.c1 is null and t2.c1 < 5) group by (t2.c1)%3 order by 1; -select array_agg(distinct (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20 or (t1.c1 is null and t2.c1 < 5) group by (t2.c1)%3 order by 1; - --- DISTINCT combined with ORDER BY within aggregate -explain (verbose, costs off) -select array_agg(distinct (t1.c1)%5 order by (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20 or (t1.c1 is null and t2.c1 < 5) group by (t2.c1)%3 order by 1; -select array_agg(distinct (t1.c1)%5 order by (t1.c1)%5) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20 or (t1.c1 is null and t2.c1 < 5) group by (t2.c1)%3 order by 1; - -explain (verbose, costs off) -select array_agg(distinct (t1.c1)%5 order by (t1.c1)%5 desc nulls last) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20 or (t1.c1 is null and t2.c1 < 5) group by (t2.c1)%3 order by 1; -select array_agg(distinct (t1.c1)%5 order by (t1.c1)%5 desc nulls last) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) where t1.c1 < 20 or (t1.c1 is null and t2.c1 < 5) group by (t2.c1)%3 order by 1; - --- FILTER within aggregate -explain (verbose, costs off) -select sum(c1) filter (where c1 < 100 and c2 > 5) from ft1 group by c2 order by 1 nulls last; -select sum(c1) filter (where c1 < 100 and c2 > 5) from ft1 group by c2 order by 1 nulls last; - --- DISTINCT, ORDER BY and FILTER within aggregate -explain (verbose, costs off) -select sum(c1%3), sum(distinct c1%3 order by c1%3) filter (where c1%3 < 2), c2 from ft1 where c2 = 6 group by c2; -select sum(c1%3), sum(distinct c1%3 order by c1%3) filter (where c1%3 < 2), c2 from ft1 where c2 = 6 group by c2; - --- Outer query is aggregation query -explain (verbose, costs off) -select distinct (select count(*) filter (where t2.c2 = 6 and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0 order by 1; -select distinct (select count(*) filter (where t2.c2 = 6 and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0 order by 1; --- Inner query is aggregation query -explain (verbose, costs off) -select distinct (select count(t1.c1) filter (where t2.c2 = 6 and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0 order by 1; -select distinct (select count(t1.c1) filter (where t2.c2 = 6 and t2.c1 < 10) from ft1 t1 where t1.c1 = 6) from ft2 t2 where t2.c2 % 6 = 0 order by 1; - --- Aggregate not pushed down as FILTER condition is not pushable -explain (verbose, costs off) -select sum(c1) filter (where (c1 / c1) * random() <= 1) from ft1 group by c2 order by 1; -explain (verbose, costs off) -select sum(c2) filter (where c2 in (select c2 from ft1 where c2 < 5)) from ft1; - --- Ordered-sets within aggregate -explain (verbose, costs off) -select c2, rank('10'::varchar) within group (order by c6), percentile_cont(c2/10::numeric) within group (order by c1) from ft1 where c2 < 10 group by c2 having percentile_cont(c2/10::numeric) within group (order by c1) < 500 order by c2; -select c2, rank('10'::varchar) within group (order by c6), percentile_cont(c2/10::numeric) within group (order by c1) from ft1 where c2 < 10 group by c2 having percentile_cont(c2/10::numeric) within group (order by c1) < 500 order by c2; - --- Using multiple arguments within aggregates -explain (verbose, costs off) -select c1, rank(c1, c2) within group (order by c1, c2) from ft1 group by c1, c2 having c1 = 6 order by 1; -select c1, rank(c1, c2) within group (order by c1, c2) from ft1 group by c1, c2 having c1 = 6 order by 1; - --- User defined function for user defined aggregate, VARIADIC -create function least_accum(anyelement, variadic anyarray) -returns anyelement language sql as - 'select least($1, min($2[i])) from generate_subscripts($2,1) g(i)'; -create aggregate least_agg(variadic items anyarray) ( - stype = anyelement, sfunc = least_accum -); - --- Disable hash aggregation for plan stability. -set enable_hashagg to false; - --- Not pushed down due to user defined aggregate -explain (verbose, costs off) -select c2, least_agg(c1) from ft1 group by c2 order by c2; - --- Add function and aggregate into extension -alter extension postgres_fdw add function least_accum(anyelement, variadic anyarray); -alter extension postgres_fdw add aggregate least_agg(variadic items anyarray); -alter server loopback options (set extensions 'postgres_fdw'); - --- Now aggregate will be pushed. Aggregate will display VARIADIC argument. -explain (verbose, costs off) -select c2, least_agg(c1) from ft1 where c2 < 100 group by c2 order by c2; -select c2, least_agg(c1) from ft1 where c2 < 100 group by c2 order by c2; - --- Remove function and aggregate from extension -alter extension postgres_fdw drop function least_accum(anyelement, variadic anyarray); -alter extension postgres_fdw drop aggregate least_agg(variadic items anyarray); -alter server loopback options (set extensions 'postgres_fdw'); - --- Not pushed down as we have dropped objects from extension. -explain (verbose, costs off) -select c2, least_agg(c1) from ft1 group by c2 order by c2; - --- Cleanup -reset enable_hashagg; -drop aggregate least_agg(variadic items anyarray); -drop function least_accum(anyelement, variadic anyarray); - - --- Testing USING OPERATOR() in ORDER BY within aggregate. --- For this, we need user defined operators along with operator family and --- operator class. Create those and then add them in extension. Note that --- user defined objects are considered unshippable unless they are part of --- the extension. -create operator public.<^ ( - leftarg = int4, - rightarg = int4, - procedure = int4eq -); - -create operator public.=^ ( - leftarg = int4, - rightarg = int4, - procedure = int4lt -); - -create operator public.>^ ( - leftarg = int4, - rightarg = int4, - procedure = int4gt -); - -create operator family my_op_family using btree; - -create function my_op_cmp(a int, b int) returns int as - $$begin return btint4cmp(a, b); end $$ language plpgsql; - -create operator class my_op_class for type int using btree family my_op_family as - operator 1 public.<^, - operator 3 public.=^, - operator 5 public.>^, - function 1 my_op_cmp(int, int); - --- This will not be pushed as user defined sort operator is not part of the --- extension yet. -explain (verbose, costs off) -select array_agg(c1 order by c1 using operator(public.<^)) from ft2 where c2 = 6 and c1 < 100 group by c2; - --- This should not be pushed either. -explain (verbose, costs off) -select * from ft2 order by c1 using operator(public.<^); - --- Update local stats on ft2 -ANALYZE ft2; - --- Add into extension -alter extension postgres_fdw add operator class my_op_class using btree; -alter extension postgres_fdw add function my_op_cmp(a int, b int); -alter extension postgres_fdw add operator family my_op_family using btree; -alter extension postgres_fdw add operator public.<^(int, int); -alter extension postgres_fdw add operator public.=^(int, int); -alter extension postgres_fdw add operator public.>^(int, int); -alter server loopback options (set extensions 'postgres_fdw'); - --- Now this will be pushed as sort operator is part of the extension. -explain (verbose, costs off) -select array_agg(c1 order by c1 using operator(public.<^)) from ft2 where c2 = 6 and c1 < 100 group by c2; -select array_agg(c1 order by c1 using operator(public.<^)) from ft2 where c2 = 6 and c1 < 100 group by c2; - --- This should be pushed too. -explain (verbose, costs off) -select * from ft2 order by c1 using operator(public.<^); - --- Remove from extension -alter extension postgres_fdw drop operator class my_op_class using btree; -alter extension postgres_fdw drop function my_op_cmp(a int, b int); -alter extension postgres_fdw drop operator family my_op_family using btree; -alter extension postgres_fdw drop operator public.<^(int, int); -alter extension postgres_fdw drop operator public.=^(int, int); -alter extension postgres_fdw drop operator public.>^(int, int); -alter server loopback options (set extensions 'postgres_fdw'); - --- This will not be pushed as sort operator is now removed from the extension. -explain (verbose, costs off) -select array_agg(c1 order by c1 using operator(public.<^)) from ft2 where c2 = 6 and c1 < 100 group by c2; - --- Cleanup -drop operator class my_op_class using btree; -drop function my_op_cmp(a int, b int); -drop operator family my_op_family using btree; -drop operator public.>^(int, int); -drop operator public.=^(int, int); -drop operator public.<^(int, int); - --- Input relation to aggregate push down hook is not safe to pushdown and thus --- the aggregate cannot be pushed down to foreign server. -explain (verbose, costs off) -select count(t1.c3) from ft2 t1 left join ft2 t2 on (t1.c1 = random() * t2.c2); - --- Subquery in FROM clause having aggregate -explain (verbose, costs off) -select count(*), x.b from ft1, (select c2 a, sum(c1) b from ft1 group by c2) x where ft1.c2 = x.a group by x.b order by 1, 2; -select count(*), x.b from ft1, (select c2 a, sum(c1) b from ft1 group by c2) x where ft1.c2 = x.a group by x.b order by 1, 2; - --- FULL join with IS NULL check in HAVING -explain (verbose, costs off) -select avg(t1.c1), sum(t2.c1) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) group by t2.c1 having (avg(t1.c1) is null and sum(t2.c1) < 10) or sum(t2.c1) is null order by 1 nulls last, 2; -select avg(t1.c1), sum(t2.c1) from ft4 t1 full join ft5 t2 on (t1.c1 = t2.c1) group by t2.c1 having (avg(t1.c1) is null and sum(t2.c1) < 10) or sum(t2.c1) is null order by 1 nulls last, 2; - --- Aggregate over FULL join needing to deparse the joining relations as --- subqueries. -explain (verbose, costs off) -select count(*), sum(t1.c1), avg(t2.c1) from (select c1 from ft4 where c1 between 50 and 60) t1 full join (select c1 from ft5 where c1 between 50 and 60) t2 on (t1.c1 = t2.c1); -select count(*), sum(t1.c1), avg(t2.c1) from (select c1 from ft4 where c1 between 50 and 60) t1 full join (select c1 from ft5 where c1 between 50 and 60) t2 on (t1.c1 = t2.c1); - --- ORDER BY expression is part of the target list but not pushed down to --- foreign server. -explain (verbose, costs off) -select sum(c2) * (random() <= 1)::int as sum from ft1 order by 1; -select sum(c2) * (random() <= 1)::int as sum from ft1 order by 1; - --- LATERAL join, with parameterization -set enable_hashagg to false; -explain (verbose, costs off) -select c2, sum from "S 1"."T 1" t1, lateral (select sum(t2.c1 + t1."C 1") sum from ft2 t2 group by t2.c1) qry where t1.c2 * 2 = qry.sum and t1.c2 < 3 and t1."C 1" < 100 order by 1; -select c2, sum from "S 1"."T 1" t1, lateral (select sum(t2.c1 + t1."C 1") sum from ft2 t2 group by t2.c1) qry where t1.c2 * 2 = qry.sum and t1.c2 < 3 and t1."C 1" < 100 order by 1; -reset enable_hashagg; - --- bug #15613: bad plan for foreign table scan with lateral reference -EXPLAIN (VERBOSE, COSTS OFF) -SELECT ref_0.c2, subq_1.* -FROM - "S 1"."T 1" AS ref_0, - LATERAL ( - SELECT ref_0."C 1" c1, subq_0.* - FROM (SELECT ref_0.c2, ref_1.c3 - FROM ft1 AS ref_1) AS subq_0 - RIGHT JOIN ft2 AS ref_3 ON (subq_0.c3 = ref_3.c3) - ) AS subq_1 -WHERE ref_0."C 1" < 10 AND subq_1.c3 = '00001' -ORDER BY ref_0."C 1"; - -SELECT ref_0.c2, subq_1.* -FROM - "S 1"."T 1" AS ref_0, - LATERAL ( - SELECT ref_0."C 1" c1, subq_0.* - FROM (SELECT ref_0.c2, ref_1.c3 - FROM ft1 AS ref_1) AS subq_0 - RIGHT JOIN ft2 AS ref_3 ON (subq_0.c3 = ref_3.c3) - ) AS subq_1 -WHERE ref_0."C 1" < 10 AND subq_1.c3 = '00001' -ORDER BY ref_0."C 1"; - --- Check with placeHolderVars -explain (verbose, costs off) -select sum(q.a), count(q.b) from ft4 left join (select 13, avg(ft1.c1), sum(ft2.c1) from ft1 right join ft2 on (ft1.c1 = ft2.c1)) q(a, b, c) on (ft4.c1 <= q.b); -select sum(q.a), count(q.b) from ft4 left join (select 13, avg(ft1.c1), sum(ft2.c1) from ft1 right join ft2 on (ft1.c1 = ft2.c1)) q(a, b, c) on (ft4.c1 <= q.b); - - --- Not supported cases --- Grouping sets -explain (verbose, costs off) -select c2, sum(c1) from ft1 where c2 < 3 group by rollup(c2) order by 1 nulls last; -select c2, sum(c1) from ft1 where c2 < 3 group by rollup(c2) order by 1 nulls last; -explain (verbose, costs off) -select c2, sum(c1) from ft1 where c2 < 3 group by cube(c2) order by 1 nulls last; -select c2, sum(c1) from ft1 where c2 < 3 group by cube(c2) order by 1 nulls last; -explain (verbose, costs off) -select c2, c6, sum(c1) from ft1 where c2 < 3 group by grouping sets(c2, c6) order by 1 nulls last, 2 nulls last; -select c2, c6, sum(c1) from ft1 where c2 < 3 group by grouping sets(c2, c6) order by 1 nulls last, 2 nulls last; -explain (verbose, costs off) -select c2, sum(c1), grouping(c2) from ft1 where c2 < 3 group by c2 order by 1 nulls last; -select c2, sum(c1), grouping(c2) from ft1 where c2 < 3 group by c2 order by 1 nulls last; - --- DISTINCT itself is not pushed down, whereas underneath aggregate is pushed -explain (verbose, costs off) -select distinct sum(c1)/1000 s from ft2 where c2 < 6 group by c2 order by 1; -select distinct sum(c1)/1000 s from ft2 where c2 < 6 group by c2 order by 1; - --- WindowAgg -explain (verbose, costs off) -select c2, sum(c2), count(c2) over (partition by c2%2) from ft2 where c2 < 10 group by c2 order by 1; -select c2, sum(c2), count(c2) over (partition by c2%2) from ft2 where c2 < 10 group by c2 order by 1; -explain (verbose, costs off) -select c2, array_agg(c2) over (partition by c2%2 order by c2 desc) from ft1 where c2 < 10 group by c2 order by 1; -select c2, array_agg(c2) over (partition by c2%2 order by c2 desc) from ft1 where c2 < 10 group by c2 order by 1; -explain (verbose, costs off) -select c2, array_agg(c2) over (partition by c2%2 order by c2 range between current row and unbounded following) from ft1 where c2 < 10 group by c2 order by 1; -select c2, array_agg(c2) over (partition by c2%2 order by c2 range between current row and unbounded following) from ft1 where c2 < 10 group by c2 order by 1; - - --- =================================================================== --- parameterized queries --- =================================================================== --- simple join -PREPARE st1(int, int) AS SELECT t1.c3, t2.c3 FROM ft1 t1, ft2 t2 WHERE t1.c1 = $1 AND t2.c1 = $2; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st1(1, 2); -EXECUTE st1(1, 1); -EXECUTE st1(101, 101); --- subquery using stable function (can't be sent to remote) -PREPARE st2(int) AS SELECT * FROM ft1 t1 WHERE t1.c1 < $2 AND t1.c3 IN (SELECT c3 FROM ft2 t2 WHERE c1 > $1 AND date(c4) = '1970-01-17'::date) ORDER BY c1; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st2(10, 20); -EXECUTE st2(10, 20); -EXECUTE st2(101, 121); --- subquery using immutable function (can be sent to remote) -PREPARE st3(int) AS SELECT * FROM ft1 t1 WHERE t1.c1 < $2 AND t1.c3 IN (SELECT c3 FROM ft2 t2 WHERE c1 > $1 AND date(c5) = '1970-01-17'::date) ORDER BY c1; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st3(10, 20); -EXECUTE st3(10, 20); -EXECUTE st3(20, 30); --- custom plan should be chosen initially -PREPARE st4(int) AS SELECT * FROM ft1 t1 WHERE t1.c1 = $1; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); --- once we try it enough times, should switch to generic plan -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st4(1); --- value of $1 should not be sent to remote -PREPARE st5(user_enum,int) AS SELECT * FROM ft1 t1 WHERE c8 = $1 and c1 = $2; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st5('foo', 1); -EXECUTE st5('foo', 1); - --- altering FDW options requires replanning -PREPARE st6 AS SELECT * FROM ft1 t1 WHERE t1.c1 = t1.c2; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st6; -PREPARE st7 AS INSERT INTO ft1 (c1,c2,c3) VALUES (1001,101,'foo'); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st7; -ALTER TABLE "S 1"."T 1" RENAME TO "T 0"; -ALTER FOREIGN TABLE ft1 OPTIONS (SET table_name 'T 0'); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st6; -EXECUTE st6; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st7; -ALTER TABLE "S 1"."T 0" RENAME TO "T 1"; -ALTER FOREIGN TABLE ft1 OPTIONS (SET table_name 'T 1'); - -PREPARE st8 AS SELECT count(c3) FROM ft1 t1 WHERE t1.c1 === t1.c2; -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st8; -ALTER SERVER loopback OPTIONS (DROP extensions); -EXPLAIN (VERBOSE, COSTS OFF) EXECUTE st8; -EXECUTE st8; -ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw'); - --- cleanup -DEALLOCATE st1; -DEALLOCATE st2; -DEALLOCATE st3; -DEALLOCATE st4; -DEALLOCATE st5; -DEALLOCATE st6; -DEALLOCATE st7; -DEALLOCATE st8; - --- System columns, except ctid and oid, should not be sent to remote -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 t1 WHERE t1.tableoid = 'pg_class'::regclass LIMIT 1; -SELECT * FROM ft1 t1 WHERE t1.tableoid = 'ft1'::regclass LIMIT 1; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT tableoid::regclass, * FROM ft1 t1 LIMIT 1; -SELECT tableoid::regclass, * FROM ft1 t1 LIMIT 1; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 t1 WHERE t1.ctid = '(0,2)'; -SELECT * FROM ft1 t1 WHERE t1.ctid = '(0,2)'; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT ctid, * FROM ft1 t1 LIMIT 1; -SELECT ctid, * FROM ft1 t1 LIMIT 1; - --- =================================================================== --- used in PL/pgSQL function --- =================================================================== -CREATE OR REPLACE FUNCTION f_test(p_c1 int) RETURNS int AS $$ -DECLARE - v_c1 int; -BEGIN - SELECT c1 INTO v_c1 FROM ft1 WHERE c1 = p_c1 LIMIT 1; - PERFORM c1 FROM ft1 WHERE c1 = p_c1 AND p_c1 = v_c1 LIMIT 1; - RETURN v_c1; -END; -$$ LANGUAGE plpgsql; -SELECT f_test(100); -DROP FUNCTION f_test(int); - --- =================================================================== --- REINDEX --- =================================================================== --- remote table is not created here -CREATE FOREIGN TABLE reindex_foreign (c1 int, c2 int) - SERVER loopback2 OPTIONS (table_name 'reindex_local'); -REINDEX TABLE reindex_foreign; -- error -REINDEX TABLE CONCURRENTLY reindex_foreign; -- error -DROP FOREIGN TABLE reindex_foreign; --- partitions and foreign tables -CREATE TABLE reind_fdw_parent (c1 int) PARTITION BY RANGE (c1); -CREATE TABLE reind_fdw_0_10 PARTITION OF reind_fdw_parent - FOR VALUES FROM (0) TO (10); -CREATE FOREIGN TABLE reind_fdw_10_20 PARTITION OF reind_fdw_parent - FOR VALUES FROM (10) TO (20) - SERVER loopback OPTIONS (table_name 'reind_local_10_20'); -REINDEX TABLE reind_fdw_parent; -- ok -REINDEX TABLE CONCURRENTLY reind_fdw_parent; -- ok -DROP TABLE reind_fdw_parent; - --- =================================================================== --- conversion error --- =================================================================== -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE int; -SELECT * FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8) WHERE x1 = 1; -- ERROR -SELECT ftx.x1, ft2.c2, ftx.x8 FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2 - WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR -SELECT ftx.x1, ft2.c2, ftx FROM ft1 ftx(x1,x2,x3,x4,x5,x6,x7,x8), ft2 - WHERE ftx.x1 = ft2.c1 AND ftx.x1 = 1; -- ERROR -SELECT sum(c2), array_agg(c8) FROM ft1 GROUP BY c8; -- ERROR -ANALYZE ft1; -- ERROR -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum; - --- =================================================================== --- local type can be different from remote type in some cases, --- in particular if similarly-named operators do equivalent things --- =================================================================== -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE text; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE c8 = 'foo' LIMIT 1; -SELECT * FROM ft1 WHERE c8 = 'foo' LIMIT 1; -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ft1 WHERE 'foo' = c8 LIMIT 1; -SELECT * FROM ft1 WHERE 'foo' = c8 LIMIT 1; --- we declared c8 to be text locally, but it's still the same type on --- the remote which will balk if we try to do anything incompatible --- with that remote type -SELECT * FROM ft1 WHERE c8 LIKE 'foo' LIMIT 1; -- ERROR -SELECT * FROM ft1 WHERE c8::text LIKE 'foo' LIMIT 1; -- ERROR; cast not pushed down -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE user_enum; - --- =================================================================== --- subtransaction --- + local/remote error doesn't break cursor --- =================================================================== -BEGIN; -DECLARE c CURSOR FOR SELECT * FROM ft1 ORDER BY c1; -FETCH c; -SAVEPOINT s; -ERROR OUT; -- ERROR -ROLLBACK TO s; -FETCH c; -SAVEPOINT s; -SELECT * FROM ft1 WHERE 1 / (c1 - 1) > 0; -- ERROR -ROLLBACK TO s; -FETCH c; -SELECT * FROM ft1 ORDER BY c1 LIMIT 1; -COMMIT; - --- =================================================================== --- test handling of collations --- =================================================================== -create table loct3 (f1 text collate "C" unique, f2 text, f3 varchar(10) unique); -create foreign table ft3 (f1 text collate "C", f2 text, f3 varchar(10)) - server loopback options (table_name 'loct3', use_remote_estimate 'true'); - --- can be sent to remote -explain (verbose, costs off) select * from ft3 where f1 = 'foo'; -explain (verbose, costs off) select * from ft3 where f1 COLLATE "C" = 'foo'; -explain (verbose, costs off) select * from ft3 where f2 = 'foo'; -explain (verbose, costs off) select * from ft3 where f3 = 'foo'; -explain (verbose, costs off) select * from ft3 f, loct3 l - where f.f3 = l.f3 and l.f1 = 'foo'; --- can't be sent to remote -explain (verbose, costs off) select * from ft3 where f1 COLLATE "POSIX" = 'foo'; -explain (verbose, costs off) select * from ft3 where f1 = 'foo' COLLATE "C"; -explain (verbose, costs off) select * from ft3 where f2 COLLATE "C" = 'foo'; -explain (verbose, costs off) select * from ft3 where f2 = 'foo' COLLATE "C"; -explain (verbose, costs off) select * from ft3 f, loct3 l - where f.f3 = l.f3 COLLATE "POSIX" and l.f1 = 'foo'; - --- =================================================================== --- test writable foreign table stuff --- =================================================================== -EXPLAIN (verbose, costs off) -INSERT INTO ft2 (c1,c2,c3) SELECT c1+1000,c2+100, c3 || c3 FROM ft2 LIMIT 20; -INSERT INTO ft2 (c1,c2,c3) SELECT c1+1000,c2+100, c3 || c3 FROM ft2 LIMIT 20; -INSERT INTO ft2 (c1,c2,c3) - VALUES (1101,201,'aaa'), (1102,202,'bbb'), (1103,203,'ccc') RETURNING *; -INSERT INTO ft2 (c1,c2,c3) VALUES (1104,204,'ddd'), (1105,205,'eee'); -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c2 = c2 + 300, c3 = c3 || '_update3' WHERE c1 % 10 = 3; -- can be pushed down -UPDATE ft2 SET c2 = c2 + 300, c3 = c3 || '_update3' WHERE c1 % 10 = 3; -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c2 = c2 + 400, c3 = c3 || '_update7' WHERE c1 % 10 = 7 RETURNING *; -- can be pushed down -UPDATE ft2 SET c2 = c2 + 400, c3 = c3 || '_update7' WHERE c1 % 10 = 7 RETURNING *; -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c2 = ft2.c2 + 500, c3 = ft2.c3 || '_update9', c7 = DEFAULT - FROM ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 9; -- can be pushed down -UPDATE ft2 SET c2 = ft2.c2 + 500, c3 = ft2.c3 || '_update9', c7 = DEFAULT - FROM ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 9; -EXPLAIN (verbose, costs off) - DELETE FROM ft2 WHERE c1 % 10 = 5 RETURNING c1, c4; -- can be pushed down -DELETE FROM ft2 WHERE c1 % 10 = 5 RETURNING c1, c4; -EXPLAIN (verbose, costs off) -DELETE FROM ft2 USING ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 2; -- can be pushed down -DELETE FROM ft2 USING ft1 WHERE ft1.c1 = ft2.c2 AND ft1.c1 % 10 = 2; -SELECT c1,c2,c3,c4 FROM ft2 ORDER BY c1; -EXPLAIN (verbose, costs off) -INSERT INTO ft2 (c1,c2,c3) VALUES (1200,999,'foo') RETURNING tableoid::regclass; -INSERT INTO ft2 (c1,c2,c3) VALUES (1200,999,'foo') RETURNING tableoid::regclass; -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c3 = 'bar' WHERE c1 = 1200 RETURNING tableoid::regclass; -- can be pushed down -UPDATE ft2 SET c3 = 'bar' WHERE c1 = 1200 RETURNING tableoid::regclass; -EXPLAIN (verbose, costs off) -DELETE FROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass; -- can be pushed down -DELETE FROM ft2 WHERE c1 = 1200 RETURNING tableoid::regclass; - --- Test UPDATE/DELETE with RETURNING on a three-table join -INSERT INTO ft2 (c1,c2,c3) - SELECT id, id - 1200, to_char(id, 'FM00000') FROM generate_series(1201, 1300) id; -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c3 = 'foo' - FROM ft4 INNER JOIN ft5 ON (ft4.c1 = ft5.c1) - WHERE ft2.c1 > 1200 AND ft2.c2 = ft4.c1 - RETURNING ft2, ft2.*, ft4, ft4.*; -- can be pushed down -UPDATE ft2 SET c3 = 'foo' - FROM ft4 INNER JOIN ft5 ON (ft4.c1 = ft5.c1) - WHERE ft2.c1 > 1200 AND ft2.c2 = ft4.c1 - RETURNING ft2, ft2.*, ft4, ft4.*; -EXPLAIN (verbose, costs off) -DELETE FROM ft2 - USING ft4 LEFT JOIN ft5 ON (ft4.c1 = ft5.c1) - WHERE ft2.c1 > 1200 AND ft2.c1 % 10 = 0 AND ft2.c2 = ft4.c1 - RETURNING 100; -- can be pushed down -DELETE FROM ft2 - USING ft4 LEFT JOIN ft5 ON (ft4.c1 = ft5.c1) - WHERE ft2.c1 > 1200 AND ft2.c1 % 10 = 0 AND ft2.c2 = ft4.c1 - RETURNING 100; -DELETE FROM ft2 WHERE ft2.c1 > 1200; - --- Test UPDATE with a MULTIEXPR sub-select --- (maybe someday this'll be remotely executable, but not today) -EXPLAIN (verbose, costs off) -UPDATE ft2 AS target SET (c2, c7) = ( - SELECT c2 * 10, c7 - FROM ft2 AS src - WHERE target.c1 = src.c1 -) WHERE c1 > 1100; -UPDATE ft2 AS target SET (c2, c7) = ( - SELECT c2 * 10, c7 - FROM ft2 AS src - WHERE target.c1 = src.c1 -) WHERE c1 > 1100; - -UPDATE ft2 AS target SET (c2) = ( - SELECT c2 / 10 - FROM ft2 AS src - WHERE target.c1 = src.c1 -) WHERE c1 > 1100; - --- Test UPDATE involving a join that can be pushed down, --- but a SET clause that can't be -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE ft2 d SET c2 = CASE WHEN random() >= 0 THEN d.c2 ELSE 0 END - FROM ft2 AS t WHERE d.c1 = t.c1 AND d.c1 > 1000; -UPDATE ft2 d SET c2 = CASE WHEN random() >= 0 THEN d.c2 ELSE 0 END - FROM ft2 AS t WHERE d.c1 = t.c1 AND d.c1 > 1000; - --- Test UPDATE/DELETE with WHERE or JOIN/ON conditions containing --- user-defined operators/functions -ALTER SERVER loopback OPTIONS (DROP extensions); -INSERT INTO ft2 (c1,c2,c3) - SELECT id, id % 10, to_char(id, 'FM00000') FROM generate_series(2001, 2010) id; -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c3 = 'bar' WHERE postgres_fdw_abs(c1) > 2000 RETURNING *; -- can't be pushed down -UPDATE ft2 SET c3 = 'bar' WHERE postgres_fdw_abs(c1) > 2000 RETURNING *; -EXPLAIN (verbose, costs off) -UPDATE ft2 SET c3 = 'baz' - FROM ft4 INNER JOIN ft5 ON (ft4.c1 = ft5.c1) - WHERE ft2.c1 > 2000 AND ft2.c2 === ft4.c1 - RETURNING ft2.*, ft4.*, ft5.*; -- can't be pushed down -UPDATE ft2 SET c3 = 'baz' - FROM ft4 INNER JOIN ft5 ON (ft4.c1 = ft5.c1) - WHERE ft2.c1 > 2000 AND ft2.c2 === ft4.c1 - RETURNING ft2.*, ft4.*, ft5.*; -EXPLAIN (verbose, costs off) -DELETE FROM ft2 - USING ft4 INNER JOIN ft5 ON (ft4.c1 === ft5.c1) - WHERE ft2.c1 > 2000 AND ft2.c2 = ft4.c1 - RETURNING ft2.c1, ft2.c2, ft2.c3; -- can't be pushed down -DELETE FROM ft2 - USING ft4 INNER JOIN ft5 ON (ft4.c1 === ft5.c1) - WHERE ft2.c1 > 2000 AND ft2.c2 = ft4.c1 - RETURNING ft2.c1, ft2.c2, ft2.c3; -DELETE FROM ft2 WHERE ft2.c1 > 2000; -ALTER SERVER loopback OPTIONS (ADD extensions 'postgres_fdw'); - --- Test that trigger on remote table works as expected -CREATE OR REPLACE FUNCTION "S 1".F_BRTRIG() RETURNS trigger AS $$ -BEGIN - NEW.c3 = NEW.c3 || '_trig_update'; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; -CREATE TRIGGER t1_br_insert BEFORE INSERT OR UPDATE - ON "S 1"."T 1" FOR EACH ROW EXECUTE PROCEDURE "S 1".F_BRTRIG(); - -INSERT INTO ft2 (c1,c2,c3) VALUES (1208, 818, 'fff') RETURNING *; -INSERT INTO ft2 (c1,c2,c3,c6) VALUES (1218, 818, 'ggg', '(--;') RETURNING *; -UPDATE ft2 SET c2 = c2 + 600 WHERE c1 % 10 = 8 AND c1 < 1200 RETURNING *; - --- Test errors thrown on remote side during update -ALTER TABLE "S 1"."T 1" ADD CONSTRAINT c2positive CHECK (c2 >= 0); - -INSERT INTO ft1(c1, c2) VALUES(11, 12); -- duplicate key -INSERT INTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT DO NOTHING; -- works -INSERT INTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT (c1, c2) DO NOTHING; -- unsupported -INSERT INTO ft1(c1, c2) VALUES(11, 12) ON CONFLICT (c1, c2) DO UPDATE SET c3 = 'ffg'; -- unsupported -INSERT INTO ft1(c1, c2) VALUES(1111, -2); -- c2positive -UPDATE ft1 SET c2 = -c2 WHERE c1 = 1; -- c2positive - --- Test savepoint/rollback behavior -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -select c2, count(*) from "S 1"."T 1" where c2 < 500 group by 1 order by 1; -begin; -update ft2 set c2 = 42 where c2 = 0; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -savepoint s1; -update ft2 set c2 = 44 where c2 = 4; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -release savepoint s1; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -savepoint s2; -update ft2 set c2 = 46 where c2 = 6; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -rollback to savepoint s2; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -release savepoint s2; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -savepoint s3; -update ft2 set c2 = -2 where c2 = 42 and c1 = 10; -- fail on remote side -rollback to savepoint s3; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -release savepoint s3; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; --- none of the above is committed yet remotely -select c2, count(*) from "S 1"."T 1" where c2 < 500 group by 1 order by 1; -commit; -select c2, count(*) from ft2 where c2 < 500 group by 1 order by 1; -select c2, count(*) from "S 1"."T 1" where c2 < 500 group by 1 order by 1; - -VACUUM ANALYZE "S 1"."T 1"; - --- Above DMLs add data with c6 as NULL in ft1, so test ORDER BY NULLS LAST and NULLs --- FIRST behavior here. --- ORDER BY DESC NULLS LAST options -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDER BY c6 DESC NULLS LAST, c1 OFFSET 795 LIMIT 10; -SELECT * FROM ft1 ORDER BY c6 DESC NULLS LAST, c1 OFFSET 795 LIMIT 10; --- ORDER BY DESC NULLS FIRST options -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDER BY c6 DESC NULLS FIRST, c1 OFFSET 15 LIMIT 10; -SELECT * FROM ft1 ORDER BY c6 DESC NULLS FIRST, c1 OFFSET 15 LIMIT 10; --- ORDER BY ASC NULLS FIRST options -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM ft1 ORDER BY c6 ASC NULLS FIRST, c1 OFFSET 15 LIMIT 10; -SELECT * FROM ft1 ORDER BY c6 ASC NULLS FIRST, c1 OFFSET 15 LIMIT 10; - --- =================================================================== --- test check constraints --- =================================================================== - --- Consistent check constraints provide consistent results -ALTER FOREIGN TABLE ft1 ADD CONSTRAINT ft1_c2positive CHECK (c2 >= 0); -EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 < 0; -SELECT count(*) FROM ft1 WHERE c2 < 0; -SET constraint_exclusion = 'on'; -EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 < 0; -SELECT count(*) FROM ft1 WHERE c2 < 0; -RESET constraint_exclusion; --- check constraint is enforced on the remote side, not locally -INSERT INTO ft1(c1, c2) VALUES(1111, -2); -- c2positive -UPDATE ft1 SET c2 = -c2 WHERE c1 = 1; -- c2positive -ALTER FOREIGN TABLE ft1 DROP CONSTRAINT ft1_c2positive; - --- But inconsistent check constraints provide inconsistent results -ALTER FOREIGN TABLE ft1 ADD CONSTRAINT ft1_c2negative CHECK (c2 < 0); -EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 >= 0; -SELECT count(*) FROM ft1 WHERE c2 >= 0; -SET constraint_exclusion = 'on'; -EXPLAIN (VERBOSE, COSTS OFF) SELECT count(*) FROM ft1 WHERE c2 >= 0; -SELECT count(*) FROM ft1 WHERE c2 >= 0; -RESET constraint_exclusion; --- local check constraint is not actually enforced -INSERT INTO ft1(c1, c2) VALUES(1111, 2); -UPDATE ft1 SET c2 = c2 + 1 WHERE c1 = 1; -ALTER FOREIGN TABLE ft1 DROP CONSTRAINT ft1_c2negative; - --- =================================================================== --- test WITH CHECK OPTION constraints --- =================================================================== - -CREATE FUNCTION row_before_insupd_trigfunc() RETURNS trigger AS $$BEGIN NEW.a := NEW.a + 10; RETURN NEW; END$$ LANGUAGE plpgsql; - -CREATE TABLE base_tbl (a int, b int); -ALTER TABLE base_tbl SET (autovacuum_enabled = 'false'); -CREATE TRIGGER row_before_insupd_trigger BEFORE INSERT OR UPDATE ON base_tbl FOR EACH ROW EXECUTE PROCEDURE row_before_insupd_trigfunc(); -CREATE FOREIGN TABLE foreign_tbl (a int, b int) - SERVER loopback OPTIONS (table_name 'base_tbl'); -CREATE VIEW rw_view AS SELECT * FROM foreign_tbl - WHERE a < b WITH CHECK OPTION; -\d+ rw_view - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO rw_view VALUES (0, 5); -INSERT INTO rw_view VALUES (0, 5); -- should fail -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO rw_view VALUES (0, 15); -INSERT INTO rw_view VALUES (0, 15); -- ok -SELECT * FROM foreign_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE rw_view SET b = b + 5; -UPDATE rw_view SET b = b + 5; -- should fail -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE rw_view SET b = b + 15; -UPDATE rw_view SET b = b + 15; -- ok -SELECT * FROM foreign_tbl; - -DROP FOREIGN TABLE foreign_tbl CASCADE; -DROP TRIGGER row_before_insupd_trigger ON base_tbl; -DROP TABLE base_tbl; - --- test WCO for partitions - -CREATE TABLE child_tbl (a int, b int); -ALTER TABLE child_tbl SET (autovacuum_enabled = 'false'); -CREATE TRIGGER row_before_insupd_trigger BEFORE INSERT OR UPDATE ON child_tbl FOR EACH ROW EXECUTE PROCEDURE row_before_insupd_trigfunc(); -CREATE FOREIGN TABLE foreign_tbl (a int, b int) - SERVER loopback OPTIONS (table_name 'child_tbl'); - -CREATE TABLE parent_tbl (a int, b int) PARTITION BY RANGE(a); -ALTER TABLE parent_tbl ATTACH PARTITION foreign_tbl FOR VALUES FROM (0) TO (100); --- Detach and re-attach once, to stress the concurrent detach case. -ALTER TABLE parent_tbl DETACH PARTITION foreign_tbl CONCURRENTLY; -ALTER TABLE parent_tbl ATTACH PARTITION foreign_tbl FOR VALUES FROM (0) TO (100); - -CREATE VIEW rw_view AS SELECT * FROM parent_tbl - WHERE a < b WITH CHECK OPTION; -\d+ rw_view - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO rw_view VALUES (0, 5); -INSERT INTO rw_view VALUES (0, 5); -- should fail -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO rw_view VALUES (0, 15); -INSERT INTO rw_view VALUES (0, 15); -- ok -SELECT * FROM foreign_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE rw_view SET b = b + 5; -UPDATE rw_view SET b = b + 5; -- should fail -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE rw_view SET b = b + 15; -UPDATE rw_view SET b = b + 15; -- ok -SELECT * FROM foreign_tbl; - -DROP FOREIGN TABLE foreign_tbl CASCADE; -DROP TRIGGER row_before_insupd_trigger ON child_tbl; -DROP TABLE parent_tbl CASCADE; - -DROP FUNCTION row_before_insupd_trigfunc; - --- =================================================================== --- test serial columns (ie, sequence-based defaults) --- =================================================================== -create table loc1 (f1 serial, f2 text); -alter table loc1 set (autovacuum_enabled = 'false'); -create foreign table rem1 (f1 serial, f2 text) - server loopback options(table_name 'loc1'); -select pg_catalog.setval('rem1_f1_seq', 10, false); -insert into loc1(f2) values('hi'); -insert into rem1(f2) values('hi remote'); -insert into loc1(f2) values('bye'); -insert into rem1(f2) values('bye remote'); -select * from loc1; -select * from rem1; - --- =================================================================== --- test generated columns --- =================================================================== -create table gloc1 ( - a int, - b int generated always as (a * 2) stored); -alter table gloc1 set (autovacuum_enabled = 'false'); -create foreign table grem1 ( - a int, - b int generated always as (a * 2) stored) - server loopback options(table_name 'gloc1'); -explain (verbose, costs off) -insert into grem1 (a) values (1), (2); -insert into grem1 (a) values (1), (2); -explain (verbose, costs off) -update grem1 set a = 22 where a = 2; -update grem1 set a = 22 where a = 2; -select * from gloc1; -select * from grem1; -delete from grem1; - --- test copy from -copy grem1 from stdin; -1 -2 -\. -select * from gloc1; -select * from grem1; -delete from grem1; - --- test batch insert -alter server loopback options (add batch_size '10'); -explain (verbose, costs off) -insert into grem1 (a) values (1), (2); -insert into grem1 (a) values (1), (2); -select * from gloc1; -select * from grem1; -delete from grem1; -alter server loopback options (drop batch_size); - --- =================================================================== --- test local triggers --- =================================================================== - --- Trigger functions "borrowed" from triggers regress test. -CREATE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS $$ -BEGIN - RAISE NOTICE 'trigger_func(%) called: action = %, when = %, level = %', - TG_ARGV[0], TG_OP, TG_WHEN, TG_LEVEL; - RETURN NULL; -END;$$; - -CREATE TRIGGER trig_stmt_before BEFORE DELETE OR INSERT OR UPDATE ON rem1 - FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func(); -CREATE TRIGGER trig_stmt_after AFTER DELETE OR INSERT OR UPDATE ON rem1 - FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func(); - -CREATE OR REPLACE FUNCTION trigger_data() RETURNS trigger -LANGUAGE plpgsql AS $$ - -declare - oldnew text[]; - relid text; - argstr text; -begin - - relid := TG_relid::regclass; - argstr := ''; - for i in 0 .. TG_nargs - 1 loop - if i > 0 then - argstr := argstr || ', '; - end if; - argstr := argstr || TG_argv[i]; - end loop; - - RAISE NOTICE '%(%) % % % ON %', - tg_name, argstr, TG_when, TG_level, TG_OP, relid; - oldnew := '{}'::text[]; - if TG_OP != 'INSERT' then - oldnew := array_append(oldnew, format('OLD: %s', OLD)); - end if; - - if TG_OP != 'DELETE' then - oldnew := array_append(oldnew, format('NEW: %s', NEW)); - end if; - - RAISE NOTICE '%', array_to_string(oldnew, ','); - - if TG_OP = 'DELETE' then - return OLD; - else - return NEW; - end if; -end; -$$; - --- Test basic functionality -CREATE TRIGGER trig_row_before -BEFORE INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_row_after -AFTER INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -delete from rem1; -insert into rem1 values(1,'insert'); -update rem1 set f2 = 'update' where f1 = 1; -update rem1 set f2 = f2 || f2; - - --- cleanup -DROP TRIGGER trig_row_before ON rem1; -DROP TRIGGER trig_row_after ON rem1; -DROP TRIGGER trig_stmt_before ON rem1; -DROP TRIGGER trig_stmt_after ON rem1; - -DELETE from rem1; - --- Test multiple AFTER ROW triggers on a foreign table -CREATE TRIGGER trig_row_after1 -AFTER INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_row_after2 -AFTER INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -insert into rem1 values(1,'insert'); -update rem1 set f2 = 'update' where f1 = 1; -update rem1 set f2 = f2 || f2; -delete from rem1; - --- cleanup -DROP TRIGGER trig_row_after1 ON rem1; -DROP TRIGGER trig_row_after2 ON rem1; - --- Test WHEN conditions - -CREATE TRIGGER trig_row_before_insupd -BEFORE INSERT OR UPDATE ON rem1 -FOR EACH ROW -WHEN (NEW.f2 like '%update%') -EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_row_after_insupd -AFTER INSERT OR UPDATE ON rem1 -FOR EACH ROW -WHEN (NEW.f2 like '%update%') -EXECUTE PROCEDURE trigger_data(23,'skidoo'); - --- Insert or update not matching: nothing happens -INSERT INTO rem1 values(1, 'insert'); -UPDATE rem1 set f2 = 'test'; - --- Insert or update matching: triggers are fired -INSERT INTO rem1 values(2, 'update'); -UPDATE rem1 set f2 = 'update update' where f1 = '2'; - -CREATE TRIGGER trig_row_before_delete -BEFORE DELETE ON rem1 -FOR EACH ROW -WHEN (OLD.f2 like '%update%') -EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_row_after_delete -AFTER DELETE ON rem1 -FOR EACH ROW -WHEN (OLD.f2 like '%update%') -EXECUTE PROCEDURE trigger_data(23,'skidoo'); - --- Trigger is fired for f1=2, not for f1=1 -DELETE FROM rem1; - --- cleanup -DROP TRIGGER trig_row_before_insupd ON rem1; -DROP TRIGGER trig_row_after_insupd ON rem1; -DROP TRIGGER trig_row_before_delete ON rem1; -DROP TRIGGER trig_row_after_delete ON rem1; - - --- Test various RETURN statements in BEFORE triggers. - -CREATE FUNCTION trig_row_before_insupdate() RETURNS TRIGGER AS $$ - BEGIN - NEW.f2 := NEW.f2 || ' triggered !'; - RETURN NEW; - END -$$ language plpgsql; - -CREATE TRIGGER trig_row_before_insupd -BEFORE INSERT OR UPDATE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trig_row_before_insupdate(); - --- The new values should have 'triggered' appended -INSERT INTO rem1 values(1, 'insert'); -SELECT * from loc1; -INSERT INTO rem1 values(2, 'insert') RETURNING f2; -SELECT * from loc1; -UPDATE rem1 set f2 = ''; -SELECT * from loc1; -UPDATE rem1 set f2 = 'skidoo' RETURNING f2; -SELECT * from loc1; - -EXPLAIN (verbose, costs off) -UPDATE rem1 set f1 = 10; -- all columns should be transmitted -UPDATE rem1 set f1 = 10; -SELECT * from loc1; - -DELETE FROM rem1; - --- Add a second trigger, to check that the changes are propagated correctly --- from trigger to trigger -CREATE TRIGGER trig_row_before_insupd2 -BEFORE INSERT OR UPDATE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trig_row_before_insupdate(); - -INSERT INTO rem1 values(1, 'insert'); -SELECT * from loc1; -INSERT INTO rem1 values(2, 'insert') RETURNING f2; -SELECT * from loc1; -UPDATE rem1 set f2 = ''; -SELECT * from loc1; -UPDATE rem1 set f2 = 'skidoo' RETURNING f2; -SELECT * from loc1; - -DROP TRIGGER trig_row_before_insupd ON rem1; -DROP TRIGGER trig_row_before_insupd2 ON rem1; - -DELETE from rem1; - -INSERT INTO rem1 VALUES (1, 'test'); - --- Test with a trigger returning NULL -CREATE FUNCTION trig_null() RETURNS TRIGGER AS $$ - BEGIN - RETURN NULL; - END -$$ language plpgsql; - -CREATE TRIGGER trig_null -BEFORE INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trig_null(); - --- Nothing should have changed. -INSERT INTO rem1 VALUES (2, 'test2'); - -SELECT * from loc1; - -UPDATE rem1 SET f2 = 'test2'; - -SELECT * from loc1; - -DELETE from rem1; - -SELECT * from loc1; - -DROP TRIGGER trig_null ON rem1; -DELETE from rem1; - --- Test a combination of local and remote triggers -CREATE TRIGGER trig_row_before -BEFORE INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_row_after -AFTER INSERT OR UPDATE OR DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_local_before BEFORE INSERT OR UPDATE ON loc1 -FOR EACH ROW EXECUTE PROCEDURE trig_row_before_insupdate(); - -INSERT INTO rem1(f2) VALUES ('test'); -UPDATE rem1 SET f2 = 'testo'; - --- Test returning a system attribute -INSERT INTO rem1(f2) VALUES ('test') RETURNING ctid; - --- cleanup -DROP TRIGGER trig_row_before ON rem1; -DROP TRIGGER trig_row_after ON rem1; -DROP TRIGGER trig_local_before ON loc1; - - --- Test direct foreign table modification functionality -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1 WHERE false; -- currently can't be pushed down - --- Test with statement-level triggers -CREATE TRIGGER trig_stmt_before - BEFORE DELETE OR INSERT OR UPDATE ON rem1 - FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func(); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -DROP TRIGGER trig_stmt_before ON rem1; - -CREATE TRIGGER trig_stmt_after - AFTER DELETE OR INSERT OR UPDATE ON rem1 - FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func(); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -DROP TRIGGER trig_stmt_after ON rem1; - --- Test with row-level ON INSERT triggers -CREATE TRIGGER trig_row_before_insert -BEFORE INSERT ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -DROP TRIGGER trig_row_before_insert ON rem1; - -CREATE TRIGGER trig_row_after_insert -AFTER INSERT ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -DROP TRIGGER trig_row_after_insert ON rem1; - --- Test with row-level ON UPDATE triggers -CREATE TRIGGER trig_row_before_update -BEFORE UPDATE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can't be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -DROP TRIGGER trig_row_before_update ON rem1; - -CREATE TRIGGER trig_row_after_update -AFTER UPDATE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can't be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can be pushed down -DROP TRIGGER trig_row_after_update ON rem1; - --- Test with row-level ON DELETE triggers -CREATE TRIGGER trig_row_before_delete -BEFORE DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can't be pushed down -DROP TRIGGER trig_row_before_delete ON rem1; - -CREATE TRIGGER trig_row_after_delete -AFTER DELETE ON rem1 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (verbose, costs off) -UPDATE rem1 set f2 = ''; -- can be pushed down -EXPLAIN (verbose, costs off) -DELETE FROM rem1; -- can't be pushed down -DROP TRIGGER trig_row_after_delete ON rem1; - --- =================================================================== --- test inheritance features --- =================================================================== - -CREATE TABLE a (aa TEXT); -CREATE TABLE loct (aa TEXT, bb TEXT); -ALTER TABLE a SET (autovacuum_enabled = 'false'); -ALTER TABLE loct SET (autovacuum_enabled = 'false'); -CREATE FOREIGN TABLE b (bb TEXT) INHERITS (a) - SERVER loopback OPTIONS (table_name 'loct'); - -INSERT INTO a(aa) VALUES('aaa'); -INSERT INTO a(aa) VALUES('aaaa'); -INSERT INTO a(aa) VALUES('aaaaa'); - -INSERT INTO b(aa) VALUES('bbb'); -INSERT INTO b(aa) VALUES('bbbb'); -INSERT INTO b(aa) VALUES('bbbbb'); - -SELECT tableoid::regclass, * FROM a; -SELECT tableoid::regclass, * FROM b; -SELECT tableoid::regclass, * FROM ONLY a; - -UPDATE a SET aa = 'zzzzzz' WHERE aa LIKE 'aaaa%'; - -SELECT tableoid::regclass, * FROM a; -SELECT tableoid::regclass, * FROM b; -SELECT tableoid::regclass, * FROM ONLY a; - -UPDATE b SET aa = 'new'; - -SELECT tableoid::regclass, * FROM a; -SELECT tableoid::regclass, * FROM b; -SELECT tableoid::regclass, * FROM ONLY a; - -UPDATE a SET aa = 'newtoo'; - -SELECT tableoid::regclass, * FROM a; -SELECT tableoid::regclass, * FROM b; -SELECT tableoid::regclass, * FROM ONLY a; - -DELETE FROM a; - -SELECT tableoid::regclass, * FROM a; -SELECT tableoid::regclass, * FROM b; -SELECT tableoid::regclass, * FROM ONLY a; - -DROP TABLE a CASCADE; -DROP TABLE loct; - --- Check SELECT FOR UPDATE/SHARE with an inherited source table -create table loct1 (f1 int, f2 int, f3 int); -create table loct2 (f1 int, f2 int, f3 int); - -alter table loct1 set (autovacuum_enabled = 'false'); -alter table loct2 set (autovacuum_enabled = 'false'); - -create table foo (f1 int, f2 int); -create foreign table foo2 (f3 int) inherits (foo) - server loopback options (table_name 'loct1'); -create table bar (f1 int, f2 int); -create foreign table bar2 (f3 int) inherits (bar) - server loopback options (table_name 'loct2'); - -alter table foo set (autovacuum_enabled = 'false'); -alter table bar set (autovacuum_enabled = 'false'); - -insert into foo values(1,1); -insert into foo values(3,3); -insert into foo2 values(2,2,2); -insert into foo2 values(4,4,4); -insert into bar values(1,11); -insert into bar values(2,22); -insert into bar values(6,66); -insert into bar2 values(3,33,33); -insert into bar2 values(4,44,44); -insert into bar2 values(7,77,77); - -explain (verbose, costs off) -select * from bar where f1 in (select f1 from foo) for update; -select * from bar where f1 in (select f1 from foo) for update; - -explain (verbose, costs off) -select * from bar where f1 in (select f1 from foo) for share; -select * from bar where f1 in (select f1 from foo) for share; - --- Now check SELECT FOR UPDATE/SHARE with an inherited source table, --- where the parent is itself a foreign table -create table loct4 (f1 int, f2 int, f3 int); -create foreign table foo2child (f3 int) inherits (foo2) - server loopback options (table_name 'loct4'); - -explain (verbose, costs off) -select * from bar where f1 in (select f1 from foo2) for share; -select * from bar where f1 in (select f1 from foo2) for share; - -drop foreign table foo2child; - --- And with a local child relation of the foreign table parent -create table foo2child (f3 int) inherits (foo2); - -explain (verbose, costs off) -select * from bar where f1 in (select f1 from foo2) for share; -select * from bar where f1 in (select f1 from foo2) for share; - -drop table foo2child; - --- Check UPDATE with inherited target and an inherited source table -explain (verbose, costs off) -update bar set f2 = f2 + 100 where f1 in (select f1 from foo); -update bar set f2 = f2 + 100 where f1 in (select f1 from foo); - -select tableoid::regclass, * from bar order by 1,2; - --- Check UPDATE with inherited target and an appendrel subquery -explain (verbose, costs off) -update bar set f2 = f2 + 100 -from - ( select f1 from foo union all select f1+3 from foo ) ss -where bar.f1 = ss.f1; -update bar set f2 = f2 + 100 -from - ( select f1 from foo union all select f1+3 from foo ) ss -where bar.f1 = ss.f1; - -select tableoid::regclass, * from bar order by 1,2; - --- Test forcing the remote server to produce sorted data for a merge join, --- but the foreign table is an inheritance child. -truncate table loct1; -truncate table only foo; -\set num_rows_foo 2000 -insert into loct1 select generate_series(0, :num_rows_foo, 2), generate_series(0, :num_rows_foo, 2), generate_series(0, :num_rows_foo, 2); -insert into foo select generate_series(1, :num_rows_foo, 2), generate_series(1, :num_rows_foo, 2); -SET enable_hashjoin to false; -SET enable_nestloop to false; -alter foreign table foo2 options (use_remote_estimate 'true'); -create index i_loct1_f1 on loct1(f1); -create index i_foo_f1 on foo(f1); -analyze foo; -analyze loct1; --- inner join; expressions in the clauses appear in the equivalence class list -explain (verbose, costs off) - select foo.f1, loct1.f1 from foo join loct1 on (foo.f1 = loct1.f1) order by foo.f2 offset 10 limit 10; -select foo.f1, loct1.f1 from foo join loct1 on (foo.f1 = loct1.f1) order by foo.f2 offset 10 limit 10; --- outer join; expressions in the clauses do not appear in equivalence class --- list but no output change as compared to the previous query -explain (verbose, costs off) - select foo.f1, loct1.f1 from foo left join loct1 on (foo.f1 = loct1.f1) order by foo.f2 offset 10 limit 10; -select foo.f1, loct1.f1 from foo left join loct1 on (foo.f1 = loct1.f1) order by foo.f2 offset 10 limit 10; -RESET enable_hashjoin; -RESET enable_nestloop; - --- Test that WHERE CURRENT OF is not supported -begin; -declare c cursor for select * from bar where f1 = 7; -fetch from c; -update bar set f2 = null where current of c; -rollback; - -explain (verbose, costs off) -delete from foo where f1 < 5 returning *; -delete from foo where f1 < 5 returning *; -explain (verbose, costs off) -update bar set f2 = f2 + 100 returning *; -update bar set f2 = f2 + 100 returning *; - --- Test that UPDATE/DELETE with inherited target works with row-level triggers -CREATE TRIGGER trig_row_before -BEFORE UPDATE OR DELETE ON bar2 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER trig_row_after -AFTER UPDATE OR DELETE ON bar2 -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -explain (verbose, costs off) -update bar set f2 = f2 + 100; -update bar set f2 = f2 + 100; - -explain (verbose, costs off) -delete from bar where f2 < 400; -delete from bar where f2 < 400; - --- cleanup -drop table foo cascade; -drop table bar cascade; -drop table loct1; -drop table loct2; - --- Test pushing down UPDATE/DELETE joins to the remote server -create table parent (a int, b text); -create table loct1 (a int, b text); -create table loct2 (a int, b text); -create foreign table remt1 (a int, b text) - server loopback options (table_name 'loct1'); -create foreign table remt2 (a int, b text) - server loopback options (table_name 'loct2'); -alter foreign table remt1 inherit parent; - -insert into remt1 values (1, 'foo'); -insert into remt1 values (2, 'bar'); -insert into remt2 values (1, 'foo'); -insert into remt2 values (2, 'bar'); - -analyze remt1; -analyze remt2; - -explain (verbose, costs off) -update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *; -update parent set b = parent.b || remt2.b from remt2 where parent.a = remt2.a returning *; -explain (verbose, costs off) -delete from parent using remt2 where parent.a = remt2.a returning parent; -delete from parent using remt2 where parent.a = remt2.a returning parent; - --- cleanup -drop foreign table remt1; -drop foreign table remt2; -drop table loct1; -drop table loct2; -drop table parent; - --- =================================================================== --- test tuple routing for foreign-table partitions --- =================================================================== - --- Test insert tuple routing -create table itrtest (a int, b text) partition by list (a); -create table loct1 (a int check (a in (1)), b text); -create foreign table remp1 (a int check (a in (1)), b text) server loopback options (table_name 'loct1'); -create table loct2 (a int check (a in (2)), b text); -create foreign table remp2 (b text, a int check (a in (2))) server loopback options (table_name 'loct2'); -alter table itrtest attach partition remp1 for values in (1); -alter table itrtest attach partition remp2 for values in (2); - -insert into itrtest values (1, 'foo'); -insert into itrtest values (1, 'bar') returning *; -insert into itrtest values (2, 'baz'); -insert into itrtest values (2, 'qux') returning *; -insert into itrtest values (1, 'test1'), (2, 'test2') returning *; - -select tableoid::regclass, * FROM itrtest; -select tableoid::regclass, * FROM remp1; -select tableoid::regclass, * FROM remp2; - -delete from itrtest; - -create unique index loct1_idx on loct1 (a); - --- DO NOTHING without an inference specification is supported -insert into itrtest values (1, 'foo') on conflict do nothing returning *; -insert into itrtest values (1, 'foo') on conflict do nothing returning *; - --- But other cases are not supported -insert into itrtest values (1, 'bar') on conflict (a) do nothing; -insert into itrtest values (1, 'bar') on conflict (a) do update set b = excluded.b; - -select tableoid::regclass, * FROM itrtest; - -delete from itrtest; - -drop index loct1_idx; - --- Test that remote triggers work with insert tuple routing -create function br_insert_trigfunc() returns trigger as $$ -begin - new.b := new.b || ' triggered !'; - return new; -end -$$ language plpgsql; -create trigger loct1_br_insert_trigger before insert on loct1 - for each row execute procedure br_insert_trigfunc(); -create trigger loct2_br_insert_trigger before insert on loct2 - for each row execute procedure br_insert_trigfunc(); - --- The new values are concatenated with ' triggered !' -insert into itrtest values (1, 'foo') returning *; -insert into itrtest values (2, 'qux') returning *; -insert into itrtest values (1, 'test1'), (2, 'test2') returning *; -with result as (insert into itrtest values (1, 'test1'), (2, 'test2') returning *) select * from result; - -drop trigger loct1_br_insert_trigger on loct1; -drop trigger loct2_br_insert_trigger on loct2; - -drop table itrtest; -drop table loct1; -drop table loct2; - --- Test update tuple routing -create table utrtest (a int, b text) partition by list (a); -create table loct (a int check (a in (1)), b text); -create foreign table remp (a int check (a in (1)), b text) server loopback options (table_name 'loct'); -create table locp (a int check (a in (2)), b text); -alter table utrtest attach partition remp for values in (1); -alter table utrtest attach partition locp for values in (2); - -insert into utrtest values (1, 'foo'); -insert into utrtest values (2, 'qux'); - -select tableoid::regclass, * FROM utrtest; -select tableoid::regclass, * FROM remp; -select tableoid::regclass, * FROM locp; - --- It's not allowed to move a row from a partition that is foreign to another -update utrtest set a = 2 where b = 'foo' returning *; - --- But the reverse is allowed -update utrtest set a = 1 where b = 'qux' returning *; - -select tableoid::regclass, * FROM utrtest; -select tableoid::regclass, * FROM remp; -select tableoid::regclass, * FROM locp; - --- The executor should not let unexercised FDWs shut down -update utrtest set a = 1 where b = 'foo'; - --- Test that remote triggers work with update tuple routing -create trigger loct_br_insert_trigger before insert on loct - for each row execute procedure br_insert_trigfunc(); - -delete from utrtest; -insert into utrtest values (2, 'qux'); - --- Check case where the foreign partition is a subplan target rel -explain (verbose, costs off) -update utrtest set a = 1 where a = 1 or a = 2 returning *; --- The new values are concatenated with ' triggered !' -update utrtest set a = 1 where a = 1 or a = 2 returning *; - -delete from utrtest; -insert into utrtest values (2, 'qux'); - --- Check case where the foreign partition isn't a subplan target rel -explain (verbose, costs off) -update utrtest set a = 1 where a = 2 returning *; --- The new values are concatenated with ' triggered !' -update utrtest set a = 1 where a = 2 returning *; - -drop trigger loct_br_insert_trigger on loct; - --- We can move rows to a foreign partition that has been updated already, --- but can't move rows to a foreign partition that hasn't been updated yet - -delete from utrtest; -insert into utrtest values (1, 'foo'); -insert into utrtest values (2, 'qux'); - --- Test the former case: --- with a direct modification plan -explain (verbose, costs off) -update utrtest set a = 1 returning *; -update utrtest set a = 1 returning *; - -delete from utrtest; -insert into utrtest values (1, 'foo'); -insert into utrtest values (2, 'qux'); - --- with a non-direct modification plan -explain (verbose, costs off) -update utrtest set a = 1 from (values (1), (2)) s(x) where a = s.x returning *; -update utrtest set a = 1 from (values (1), (2)) s(x) where a = s.x returning *; - --- Change the definition of utrtest so that the foreign partition get updated --- after the local partition -delete from utrtest; -alter table utrtest detach partition remp; -drop foreign table remp; -alter table loct drop constraint loct_a_check; -alter table loct add check (a in (3)); -create foreign table remp (a int check (a in (3)), b text) server loopback options (table_name 'loct'); -alter table utrtest attach partition remp for values in (3); -insert into utrtest values (2, 'qux'); -insert into utrtest values (3, 'xyzzy'); - --- Test the latter case: --- with a direct modification plan -explain (verbose, costs off) -update utrtest set a = 3 returning *; -update utrtest set a = 3 returning *; -- ERROR - --- with a non-direct modification plan -explain (verbose, costs off) -update utrtest set a = 3 from (values (2), (3)) s(x) where a = s.x returning *; -update utrtest set a = 3 from (values (2), (3)) s(x) where a = s.x returning *; -- ERROR - -drop table utrtest; -drop table loct; - --- Test copy tuple routing -create table ctrtest (a int, b text) partition by list (a); -create table loct1 (a int check (a in (1)), b text); -create foreign table remp1 (a int check (a in (1)), b text) server loopback options (table_name 'loct1'); -create table loct2 (a int check (a in (2)), b text); -create foreign table remp2 (b text, a int check (a in (2))) server loopback options (table_name 'loct2'); -alter table ctrtest attach partition remp1 for values in (1); -alter table ctrtest attach partition remp2 for values in (2); - -copy ctrtest from stdin; -1 foo -2 qux -\. - -select tableoid::regclass, * FROM ctrtest; -select tableoid::regclass, * FROM remp1; -select tableoid::regclass, * FROM remp2; - --- Copying into foreign partitions directly should work as well -copy remp1 from stdin; -1 bar -\. - -select tableoid::regclass, * FROM remp1; - -drop table ctrtest; -drop table loct1; -drop table loct2; - --- =================================================================== --- test COPY FROM --- =================================================================== - -create table loc2 (f1 int, f2 text); -alter table loc2 set (autovacuum_enabled = 'false'); -create foreign table rem2 (f1 int, f2 text) server loopback options(table_name 'loc2'); - --- Test basic functionality -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -delete from rem2; - --- Test check constraints -alter table loc2 add constraint loc2_f1positive check (f1 >= 0); -alter foreign table rem2 add constraint rem2_f1positive check (f1 >= 0); - --- check constraint is enforced on the remote side, not locally -copy rem2 from stdin; -1 foo -2 bar -\. -copy rem2 from stdin; -- ERROR --1 xyzzy -\. -select * from rem2; - -alter foreign table rem2 drop constraint rem2_f1positive; -alter table loc2 drop constraint loc2_f1positive; - -delete from rem2; - --- Test local triggers -create trigger trig_stmt_before before insert on rem2 - for each statement execute procedure trigger_func(); -create trigger trig_stmt_after after insert on rem2 - for each statement execute procedure trigger_func(); -create trigger trig_row_before before insert on rem2 - for each row execute procedure trigger_data(23,'skidoo'); -create trigger trig_row_after after insert on rem2 - for each row execute procedure trigger_data(23,'skidoo'); - -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -drop trigger trig_row_before on rem2; -drop trigger trig_row_after on rem2; -drop trigger trig_stmt_before on rem2; -drop trigger trig_stmt_after on rem2; - -delete from rem2; - -create trigger trig_row_before_insert before insert on rem2 - for each row execute procedure trig_row_before_insupdate(); - --- The new values are concatenated with ' triggered !' -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -drop trigger trig_row_before_insert on rem2; - -delete from rem2; - -create trigger trig_null before insert on rem2 - for each row execute procedure trig_null(); - --- Nothing happens -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -drop trigger trig_null on rem2; - -delete from rem2; - --- Test remote triggers -create trigger trig_row_before_insert before insert on loc2 - for each row execute procedure trig_row_before_insupdate(); - --- The new values are concatenated with ' triggered !' -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -drop trigger trig_row_before_insert on loc2; - -delete from rem2; - -create trigger trig_null before insert on loc2 - for each row execute procedure trig_null(); - --- Nothing happens -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -drop trigger trig_null on loc2; - -delete from rem2; - --- Test a combination of local and remote triggers -create trigger rem2_trig_row_before before insert on rem2 - for each row execute procedure trigger_data(23,'skidoo'); -create trigger rem2_trig_row_after after insert on rem2 - for each row execute procedure trigger_data(23,'skidoo'); -create trigger loc2_trig_row_before_insert before insert on loc2 - for each row execute procedure trig_row_before_insupdate(); - -copy rem2 from stdin; -1 foo -2 bar -\. -select * from rem2; - -drop trigger rem2_trig_row_before on rem2; -drop trigger rem2_trig_row_after on rem2; -drop trigger loc2_trig_row_before_insert on loc2; - -delete from rem2; - --- test COPY FROM with foreign table created in the same transaction -create table loc3 (f1 int, f2 text); -begin; -create foreign table rem3 (f1 int, f2 text) - server loopback options(table_name 'loc3'); -copy rem3 from stdin; -1 foo -2 bar -\. -commit; -select * from rem3; -drop foreign table rem3; -drop table loc3; - --- =================================================================== --- test for TRUNCATE --- =================================================================== -CREATE TABLE tru_rtable0 (id int primary key); -CREATE FOREIGN TABLE tru_ftable (id int) - SERVER loopback OPTIONS (table_name 'tru_rtable0'); -INSERT INTO tru_rtable0 (SELECT x FROM generate_series(1,10) x); - -CREATE TABLE tru_ptable (id int) PARTITION BY HASH(id); -CREATE TABLE tru_ptable__p0 PARTITION OF tru_ptable - FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE tru_rtable1 (id int primary key); -CREATE FOREIGN TABLE tru_ftable__p1 PARTITION OF tru_ptable - FOR VALUES WITH (MODULUS 2, REMAINDER 1) - SERVER loopback OPTIONS (table_name 'tru_rtable1'); -INSERT INTO tru_ptable (SELECT x FROM generate_series(11,20) x); - -CREATE TABLE tru_pk_table(id int primary key); -CREATE TABLE tru_fk_table(fkey int references tru_pk_table(id)); -INSERT INTO tru_pk_table (SELECT x FROM generate_series(1,10) x); -INSERT INTO tru_fk_table (SELECT x % 10 + 1 FROM generate_series(5,25) x); -CREATE FOREIGN TABLE tru_pk_ftable (id int) - SERVER loopback OPTIONS (table_name 'tru_pk_table'); - -CREATE TABLE tru_rtable_parent (id int); -CREATE TABLE tru_rtable_child (id int); -CREATE FOREIGN TABLE tru_ftable_parent (id int) - SERVER loopback OPTIONS (table_name 'tru_rtable_parent'); -CREATE FOREIGN TABLE tru_ftable_child () INHERITS (tru_ftable_parent) - SERVER loopback OPTIONS (table_name 'tru_rtable_child'); -INSERT INTO tru_rtable_parent (SELECT x FROM generate_series(1,8) x); -INSERT INTO tru_rtable_child (SELECT x FROM generate_series(10, 18) x); - --- normal truncate -SELECT sum(id) FROM tru_ftable; -- 55 -TRUNCATE tru_ftable; -SELECT count(*) FROM tru_rtable0; -- 0 -SELECT count(*) FROM tru_ftable; -- 0 - --- 'truncatable' option -ALTER SERVER loopback OPTIONS (ADD truncatable 'false'); -TRUNCATE tru_ftable; -- error -ALTER FOREIGN TABLE tru_ftable OPTIONS (ADD truncatable 'true'); -TRUNCATE tru_ftable; -- accepted -ALTER FOREIGN TABLE tru_ftable OPTIONS (SET truncatable 'false'); -TRUNCATE tru_ftable; -- error -ALTER SERVER loopback OPTIONS (DROP truncatable); -ALTER FOREIGN TABLE tru_ftable OPTIONS (SET truncatable 'false'); -TRUNCATE tru_ftable; -- error -ALTER FOREIGN TABLE tru_ftable OPTIONS (SET truncatable 'true'); -TRUNCATE tru_ftable; -- accepted - --- partitioned table with both local and foreign tables as partitions -SELECT sum(id) FROM tru_ptable; -- 155 -TRUNCATE tru_ptable; -SELECT count(*) FROM tru_ptable; -- 0 -SELECT count(*) FROM tru_ptable__p0; -- 0 -SELECT count(*) FROM tru_ftable__p1; -- 0 -SELECT count(*) FROM tru_rtable1; -- 0 - --- 'CASCADE' option -SELECT sum(id) FROM tru_pk_ftable; -- 55 -TRUNCATE tru_pk_ftable; -- failed by FK reference -TRUNCATE tru_pk_ftable CASCADE; -SELECT count(*) FROM tru_pk_ftable; -- 0 -SELECT count(*) FROM tru_fk_table; -- also truncated,0 - --- truncate two tables at a command -INSERT INTO tru_ftable (SELECT x FROM generate_series(1,8) x); -INSERT INTO tru_pk_ftable (SELECT x FROM generate_series(3,10) x); -SELECT count(*) from tru_ftable; -- 8 -SELECT count(*) from tru_pk_ftable; -- 8 -TRUNCATE tru_ftable, tru_pk_ftable CASCADE; -SELECT count(*) from tru_ftable; -- 0 -SELECT count(*) from tru_pk_ftable; -- 0 - --- truncate with ONLY clause --- Since ONLY is specified, the table tru_ftable_child that inherits --- tru_ftable_parent locally is not truncated. -TRUNCATE ONLY tru_ftable_parent; -SELECT sum(id) FROM tru_ftable_parent; -- 126 -TRUNCATE tru_ftable_parent; -SELECT count(*) FROM tru_ftable_parent; -- 0 - --- in case when remote table has inherited children -CREATE TABLE tru_rtable0_child () INHERITS (tru_rtable0); -INSERT INTO tru_rtable0 (SELECT x FROM generate_series(5,9) x); -INSERT INTO tru_rtable0_child (SELECT x FROM generate_series(10,14) x); -SELECT sum(id) FROM tru_ftable; -- 95 - --- Both parent and child tables in the foreign server are truncated --- even though ONLY is specified because ONLY has no effect --- when truncating a foreign table. -TRUNCATE ONLY tru_ftable; -SELECT count(*) FROM tru_ftable; -- 0 - -INSERT INTO tru_rtable0 (SELECT x FROM generate_series(21,25) x); -INSERT INTO tru_rtable0_child (SELECT x FROM generate_series(26,30) x); -SELECT sum(id) FROM tru_ftable; -- 255 -TRUNCATE tru_ftable; -- truncate both of parent and child -SELECT count(*) FROM tru_ftable; -- 0 - --- cleanup -DROP FOREIGN TABLE tru_ftable_parent, tru_ftable_child, tru_pk_ftable,tru_ftable__p1,tru_ftable; -DROP TABLE tru_rtable0, tru_rtable1, tru_ptable, tru_ptable__p0, tru_pk_table, tru_fk_table, -tru_rtable_parent,tru_rtable_child, tru_rtable0_child; - --- =================================================================== --- test IMPORT FOREIGN SCHEMA --- =================================================================== - -CREATE SCHEMA import_source; -CREATE TABLE import_source.t1 (c1 int, c2 varchar NOT NULL); -CREATE TABLE import_source.t2 (c1 int default 42, c2 varchar NULL, c3 text collate "POSIX"); -CREATE TYPE typ1 AS (m1 int, m2 varchar); -CREATE TABLE import_source.t3 (c1 timestamptz default now(), c2 typ1); -CREATE TABLE import_source."x 4" (c1 float8, "C 2" text, c3 varchar(42)); -CREATE TABLE import_source."x 5" (c1 float8); -ALTER TABLE import_source."x 5" DROP COLUMN c1; -CREATE TABLE import_source."x 6" (c1 int, c2 int generated always as (c1 * 2) stored); -CREATE TABLE import_source.t4 (c1 int) PARTITION BY RANGE (c1); -CREATE TABLE import_source.t4_part PARTITION OF import_source.t4 - FOR VALUES FROM (1) TO (100); -CREATE TABLE import_source.t4_part2 PARTITION OF import_source.t4 - FOR VALUES FROM (100) TO (200); - -CREATE SCHEMA import_dest1; -IMPORT FOREIGN SCHEMA import_source FROM SERVER loopback INTO import_dest1; -\det+ import_dest1.* -\d import_dest1.* - --- Options -CREATE SCHEMA import_dest2; -IMPORT FOREIGN SCHEMA import_source FROM SERVER loopback INTO import_dest2 - OPTIONS (import_default 'true'); -\det+ import_dest2.* -\d import_dest2.* -CREATE SCHEMA import_dest3; -IMPORT FOREIGN SCHEMA import_source FROM SERVER loopback INTO import_dest3 - OPTIONS (import_collate 'false', import_generated 'false', import_not_null 'false'); -\det+ import_dest3.* -\d import_dest3.* - --- Check LIMIT TO and EXCEPT -CREATE SCHEMA import_dest4; -IMPORT FOREIGN SCHEMA import_source LIMIT TO (t1, nonesuch, t4_part) - FROM SERVER loopback INTO import_dest4; -\det+ import_dest4.* -IMPORT FOREIGN SCHEMA import_source EXCEPT (t1, "x 4", nonesuch, t4_part) - FROM SERVER loopback INTO import_dest4; -\det+ import_dest4.* - --- Assorted error cases -IMPORT FOREIGN SCHEMA import_source FROM SERVER loopback INTO import_dest4; -IMPORT FOREIGN SCHEMA nonesuch FROM SERVER loopback INTO import_dest4; -IMPORT FOREIGN SCHEMA nonesuch FROM SERVER loopback INTO notthere; -IMPORT FOREIGN SCHEMA nonesuch FROM SERVER nowhere INTO notthere; - --- Check case of a type present only on the remote server. --- We can fake this by dropping the type locally in our transaction. -CREATE TYPE "Colors" AS ENUM ('red', 'green', 'blue'); -CREATE TABLE import_source.t5 (c1 int, c2 text collate "C", "Col" "Colors"); - -CREATE SCHEMA import_dest5; -BEGIN; -DROP TYPE "Colors" CASCADE; -IMPORT FOREIGN SCHEMA import_source LIMIT TO (t5) - FROM SERVER loopback INTO import_dest5; -- ERROR - -ROLLBACK; - -BEGIN; - - -CREATE SERVER fetch101 FOREIGN DATA WRAPPER postgres_fdw OPTIONS( fetch_size '101' ); - -SELECT count(*) -FROM pg_foreign_server -WHERE srvname = 'fetch101' -AND srvoptions @> array['fetch_size=101']; - -ALTER SERVER fetch101 OPTIONS( SET fetch_size '202' ); - -SELECT count(*) -FROM pg_foreign_server -WHERE srvname = 'fetch101' -AND srvoptions @> array['fetch_size=101']; - -SELECT count(*) -FROM pg_foreign_server -WHERE srvname = 'fetch101' -AND srvoptions @> array['fetch_size=202']; - -CREATE FOREIGN TABLE table30000 ( x int ) SERVER fetch101 OPTIONS ( fetch_size '30000' ); - -SELECT COUNT(*) -FROM pg_foreign_table -WHERE ftrelid = 'table30000'::regclass -AND ftoptions @> array['fetch_size=30000']; - -ALTER FOREIGN TABLE table30000 OPTIONS ( SET fetch_size '60000'); - -SELECT COUNT(*) -FROM pg_foreign_table -WHERE ftrelid = 'table30000'::regclass -AND ftoptions @> array['fetch_size=30000']; - -SELECT COUNT(*) -FROM pg_foreign_table -WHERE ftrelid = 'table30000'::regclass -AND ftoptions @> array['fetch_size=60000']; - -ROLLBACK; - --- =================================================================== --- test partitionwise joins --- =================================================================== -SET enable_partitionwise_join=on; - -CREATE TABLE fprt1 (a int, b int, c varchar) PARTITION BY RANGE(a); -CREATE TABLE fprt1_p1 (LIKE fprt1); -CREATE TABLE fprt1_p2 (LIKE fprt1); -ALTER TABLE fprt1_p1 SET (autovacuum_enabled = 'false'); -ALTER TABLE fprt1_p2 SET (autovacuum_enabled = 'false'); -INSERT INTO fprt1_p1 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 249, 2) i; -INSERT INTO fprt1_p2 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(250, 499, 2) i; -CREATE FOREIGN TABLE ftprt1_p1 PARTITION OF fprt1 FOR VALUES FROM (0) TO (250) - SERVER loopback OPTIONS (table_name 'fprt1_p1', use_remote_estimate 'true'); -CREATE FOREIGN TABLE ftprt1_p2 PARTITION OF fprt1 FOR VALUES FROM (250) TO (500) - SERVER loopback OPTIONS (TABLE_NAME 'fprt1_p2'); -ANALYZE fprt1; -ANALYZE fprt1_p1; -ANALYZE fprt1_p2; - -CREATE TABLE fprt2 (a int, b int, c varchar) PARTITION BY RANGE(b); -CREATE TABLE fprt2_p1 (LIKE fprt2); -CREATE TABLE fprt2_p2 (LIKE fprt2); -ALTER TABLE fprt2_p1 SET (autovacuum_enabled = 'false'); -ALTER TABLE fprt2_p2 SET (autovacuum_enabled = 'false'); -INSERT INTO fprt2_p1 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(0, 249, 3) i; -INSERT INTO fprt2_p2 SELECT i, i, to_char(i/50, 'FM0000') FROM generate_series(250, 499, 3) i; -CREATE FOREIGN TABLE ftprt2_p1 (b int, c varchar, a int) - SERVER loopback OPTIONS (table_name 'fprt2_p1', use_remote_estimate 'true'); -ALTER TABLE fprt2 ATTACH PARTITION ftprt2_p1 FOR VALUES FROM (0) TO (250); -CREATE FOREIGN TABLE ftprt2_p2 PARTITION OF fprt2 FOR VALUES FROM (250) TO (500) - SERVER loopback OPTIONS (table_name 'fprt2_p2', use_remote_estimate 'true'); -ANALYZE fprt2; -ANALYZE fprt2_p1; -ANALYZE fprt2_p2; - --- inner join three tables -EXPLAIN (COSTS OFF) -SELECT t1.a,t2.b,t3.c FROM fprt1 t1 INNER JOIN fprt2 t2 ON (t1.a = t2.b) INNER JOIN fprt1 t3 ON (t2.b = t3.a) WHERE t1.a % 25 =0 ORDER BY 1,2,3; -SELECT t1.a,t2.b,t3.c FROM fprt1 t1 INNER JOIN fprt2 t2 ON (t1.a = t2.b) INNER JOIN fprt1 t3 ON (t2.b = t3.a) WHERE t1.a % 25 =0 ORDER BY 1,2,3; - --- left outer join + nullable clause -EXPLAIN (VERBOSE, COSTS OFF) -SELECT t1.a,t2.b,t2.c FROM fprt1 t1 LEFT JOIN (SELECT * FROM fprt2 WHERE a < 10) t2 ON (t1.a = t2.b and t1.b = t2.a) WHERE t1.a < 10 ORDER BY 1,2,3; -SELECT t1.a,t2.b,t2.c FROM fprt1 t1 LEFT JOIN (SELECT * FROM fprt2 WHERE a < 10) t2 ON (t1.a = t2.b and t1.b = t2.a) WHERE t1.a < 10 ORDER BY 1,2,3; - --- with whole-row reference; partitionwise join does not apply -EXPLAIN (COSTS OFF) -SELECT t1.wr, t2.wr FROM (SELECT t1 wr, a FROM fprt1 t1 WHERE t1.a % 25 = 0) t1 FULL JOIN (SELECT t2 wr, b FROM fprt2 t2 WHERE t2.b % 25 = 0) t2 ON (t1.a = t2.b) ORDER BY 1,2; -SELECT t1.wr, t2.wr FROM (SELECT t1 wr, a FROM fprt1 t1 WHERE t1.a % 25 = 0) t1 FULL JOIN (SELECT t2 wr, b FROM fprt2 t2 WHERE t2.b % 25 = 0) t2 ON (t1.a = t2.b) ORDER BY 1,2; - --- join with lateral reference -EXPLAIN (COSTS OFF) -SELECT t1.a,t1.b FROM fprt1 t1, LATERAL (SELECT t2.a, t2.b FROM fprt2 t2 WHERE t1.a = t2.b AND t1.b = t2.a) q WHERE t1.a%25 = 0 ORDER BY 1,2; -SELECT t1.a,t1.b FROM fprt1 t1, LATERAL (SELECT t2.a, t2.b FROM fprt2 t2 WHERE t1.a = t2.b AND t1.b = t2.a) q WHERE t1.a%25 = 0 ORDER BY 1,2; - --- with PHVs, partitionwise join selected but no join pushdown -EXPLAIN (COSTS OFF) -SELECT t1.a, t1.phv, t2.b, t2.phv FROM (SELECT 't1_phv' phv, * FROM fprt1 WHERE a % 25 = 0) t1 FULL JOIN (SELECT 't2_phv' phv, * FROM fprt2 WHERE b % 25 = 0) t2 ON (t1.a = t2.b) ORDER BY t1.a, t2.b; -SELECT t1.a, t1.phv, t2.b, t2.phv FROM (SELECT 't1_phv' phv, * FROM fprt1 WHERE a % 25 = 0) t1 FULL JOIN (SELECT 't2_phv' phv, * FROM fprt2 WHERE b % 25 = 0) t2 ON (t1.a = t2.b) ORDER BY t1.a, t2.b; - --- test FOR UPDATE; partitionwise join does not apply -EXPLAIN (COSTS OFF) -SELECT t1.a, t2.b FROM fprt1 t1 INNER JOIN fprt2 t2 ON (t1.a = t2.b) WHERE t1.a % 25 = 0 ORDER BY 1,2 FOR UPDATE OF t1; -SELECT t1.a, t2.b FROM fprt1 t1 INNER JOIN fprt2 t2 ON (t1.a = t2.b) WHERE t1.a % 25 = 0 ORDER BY 1,2 FOR UPDATE OF t1; - -RESET enable_partitionwise_join; - - --- =================================================================== --- test partitionwise aggregates --- =================================================================== - -CREATE TABLE pagg_tab (a int, b int, c text) PARTITION BY RANGE(a); - -CREATE TABLE pagg_tab_p1 (LIKE pagg_tab); -CREATE TABLE pagg_tab_p2 (LIKE pagg_tab); -CREATE TABLE pagg_tab_p3 (LIKE pagg_tab); - -INSERT INTO pagg_tab_p1 SELECT i % 30, i % 50, to_char(i/30, 'FM0000') FROM generate_series(1, 3000) i WHERE (i % 30) < 10; -INSERT INTO pagg_tab_p2 SELECT i % 30, i % 50, to_char(i/30, 'FM0000') FROM generate_series(1, 3000) i WHERE (i % 30) < 20 and (i % 30) >= 10; -INSERT INTO pagg_tab_p3 SELECT i % 30, i % 50, to_char(i/30, 'FM0000') FROM generate_series(1, 3000) i WHERE (i % 30) < 30 and (i % 30) >= 20; - --- Create foreign partitions -CREATE FOREIGN TABLE fpagg_tab_p1 PARTITION OF pagg_tab FOR VALUES FROM (0) TO (10) SERVER loopback OPTIONS (table_name 'pagg_tab_p1'); -CREATE FOREIGN TABLE fpagg_tab_p2 PARTITION OF pagg_tab FOR VALUES FROM (10) TO (20) SERVER loopback OPTIONS (table_name 'pagg_tab_p2'); -CREATE FOREIGN TABLE fpagg_tab_p3 PARTITION OF pagg_tab FOR VALUES FROM (20) TO (30) SERVER loopback OPTIONS (table_name 'pagg_tab_p3'); - -ANALYZE pagg_tab; -ANALYZE fpagg_tab_p1; -ANALYZE fpagg_tab_p2; -ANALYZE fpagg_tab_p3; - --- When GROUP BY clause matches with PARTITION KEY. --- Plan with partitionwise aggregates is disabled -SET enable_partitionwise_aggregate TO false; -EXPLAIN (COSTS OFF) -SELECT a, sum(b), min(b), count(*) FROM pagg_tab GROUP BY a HAVING avg(b) < 22 ORDER BY 1; - --- Plan with partitionwise aggregates is enabled -SET enable_partitionwise_aggregate TO true; -EXPLAIN (COSTS OFF) -SELECT a, sum(b), min(b), count(*) FROM pagg_tab GROUP BY a HAVING avg(b) < 22 ORDER BY 1; -SELECT a, sum(b), min(b), count(*) FROM pagg_tab GROUP BY a HAVING avg(b) < 22 ORDER BY 1; - --- Check with whole-row reference --- Should have all the columns in the target list for the given relation -EXPLAIN (VERBOSE, COSTS OFF) -SELECT a, count(t1) FROM pagg_tab t1 GROUP BY a HAVING avg(b) < 22 ORDER BY 1; -SELECT a, count(t1) FROM pagg_tab t1 GROUP BY a HAVING avg(b) < 22 ORDER BY 1; - --- When GROUP BY clause does not match with PARTITION KEY. -EXPLAIN (COSTS OFF) -SELECT b, avg(a), max(a), count(*) FROM pagg_tab GROUP BY b HAVING sum(a) < 700 ORDER BY 1; - --- =================================================================== --- access rights and superuser --- =================================================================== - --- Non-superuser cannot create a FDW without a password in the connstr -CREATE ROLE regress_nosuper NOSUPERUSER; - -GRANT USAGE ON FOREIGN DATA WRAPPER postgres_fdw TO regress_nosuper; - -SET ROLE regress_nosuper; - -SHOW is_superuser; - --- This will be OK, we can create the FDW -DO $d$ - BEGIN - EXECUTE $$CREATE SERVER loopback_nopw FOREIGN DATA WRAPPER postgres_fdw - OPTIONS (dbname '$$||current_database()||$$', - port '$$||current_setting('port')||$$' - )$$; - END; -$d$; - --- But creation of user mappings for non-superusers should fail -CREATE USER MAPPING FOR public SERVER loopback_nopw; -CREATE USER MAPPING FOR CURRENT_USER SERVER loopback_nopw; - -CREATE FOREIGN TABLE pg_temp.ft1_nopw ( - c1 int NOT NULL, - c2 int NOT NULL, - c3 text, - c4 timestamptz, - c5 timestamp, - c6 varchar(10), - c7 char(10) default 'ft1', - c8 user_enum -) SERVER loopback_nopw OPTIONS (schema_name 'public', table_name 'ft1'); - -SELECT 1 FROM ft1_nopw LIMIT 1; - --- If we add a password to the connstr it'll fail, because we don't allow passwords --- in connstrs only in user mappings. - -DO $d$ - BEGIN - EXECUTE $$ALTER SERVER loopback_nopw OPTIONS (ADD password 'dummypw')$$; - END; -$d$; - --- If we add a password for our user mapping instead, we should get a different --- error because the password wasn't actually *used* when we run with trust auth. --- --- This won't work with installcheck, but neither will most of the FDW checks. - -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback_nopw OPTIONS (ADD password 'dummypw'); - -SELECT 1 FROM ft1_nopw LIMIT 1; - --- Unpriv user cannot make the mapping passwordless -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback_nopw OPTIONS (ADD password_required 'false'); - - -SELECT 1 FROM ft1_nopw LIMIT 1; - -RESET ROLE; - --- But the superuser can -ALTER USER MAPPING FOR regress_nosuper SERVER loopback_nopw OPTIONS (ADD password_required 'false'); - -SET ROLE regress_nosuper; - --- Should finally work now -SELECT 1 FROM ft1_nopw LIMIT 1; - --- unpriv user also cannot set sslcert / sslkey on the user mapping --- first set password_required so we see the right error messages -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback_nopw OPTIONS (SET password_required 'true'); -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback_nopw OPTIONS (ADD sslcert 'foo.crt'); -ALTER USER MAPPING FOR CURRENT_USER SERVER loopback_nopw OPTIONS (ADD sslkey 'foo.key'); - --- We're done with the role named after a specific user and need to check the --- changes to the public mapping. -DROP USER MAPPING FOR CURRENT_USER SERVER loopback_nopw; - --- This will fail again as it'll resolve the user mapping for public, which --- lacks password_required=false -SELECT 1 FROM ft1_nopw LIMIT 1; - -RESET ROLE; - --- The user mapping for public is passwordless and lacks the password_required=false --- mapping option, but will work because the current user is a superuser. -SELECT 1 FROM ft1_nopw LIMIT 1; - --- cleanup -DROP USER MAPPING FOR public SERVER loopback_nopw; -DROP OWNED BY regress_nosuper; -DROP ROLE regress_nosuper; - --- Clean-up -RESET enable_partitionwise_aggregate; - --- Two-phase transactions are not supported. -BEGIN; -SELECT count(*) FROM ft1; --- error here -PREPARE TRANSACTION 'fdw_tpc'; -ROLLBACK; - --- =================================================================== --- reestablish new connection --- =================================================================== - --- Change application_name of remote connection to special one --- so that we can easily terminate the connection later. -ALTER SERVER loopback OPTIONS (application_name 'fdw_retry_check'); - --- If debug_discard_caches is active, it results in --- dropping remote connections after every transaction, making it --- impossible to test termination meaningfully. So turn that off --- for this test. -SET debug_discard_caches = 0; - --- Make sure we have a remote connection. -SELECT 1 FROM ft1 LIMIT 1; - --- Terminate the remote connection and wait for the termination to complete. -SELECT pg_terminate_backend(pid, 180000) FROM pg_stat_activity - WHERE application_name = 'fdw_retry_check'; - --- This query should detect the broken connection when starting new remote --- transaction, reestablish new connection, and then succeed. -BEGIN; -SELECT 1 FROM ft1 LIMIT 1; - --- If we detect the broken connection when starting a new remote --- subtransaction, we should fail instead of establishing a new connection. --- Terminate the remote connection and wait for the termination to complete. -SELECT pg_terminate_backend(pid, 180000) FROM pg_stat_activity - WHERE application_name = 'fdw_retry_check'; -SAVEPOINT s; --- The text of the error might vary across platforms, so only show SQLSTATE. -\set VERBOSITY sqlstate -SELECT 1 FROM ft1 LIMIT 1; -- should fail -\set VERBOSITY default -COMMIT; - -RESET debug_discard_caches; - --- ============================================================================= --- test connection invalidation cases and postgres_fdw_get_connections function --- ============================================================================= --- Let's ensure to close all the existing cached connections. -SELECT 1 FROM postgres_fdw_disconnect_all(); --- No cached connections, so no records should be output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; --- This test case is for closing the connection in pgfdw_xact_callback -BEGIN; --- Connection xact depth becomes 1 i.e. the connection is in midst of the xact. -SELECT 1 FROM ft1 LIMIT 1; -SELECT 1 FROM ft7 LIMIT 1; --- List all the existing cached connections. loopback and loopback3 should be --- output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; --- Connections are not closed at the end of the alter and drop statements. --- That's because the connections are in midst of this xact, --- they are just marked as invalid in pgfdw_inval_callback. -ALTER SERVER loopback OPTIONS (ADD use_remote_estimate 'off'); -DROP SERVER loopback3 CASCADE; --- List all the existing cached connections. loopback and loopback3 --- should be output as invalid connections. Also the server name for --- loopback3 should be NULL because the server was dropped. -SELECT * FROM postgres_fdw_get_connections() ORDER BY 1; --- The invalid connections get closed in pgfdw_xact_callback during commit. -COMMIT; --- All cached connections were closed while committing above xact, so no --- records should be output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; - --- ======================================================================= --- test postgres_fdw_disconnect and postgres_fdw_disconnect_all functions --- ======================================================================= -BEGIN; --- Ensure to cache loopback connection. -SELECT 1 FROM ft1 LIMIT 1; --- Ensure to cache loopback2 connection. -SELECT 1 FROM ft6 LIMIT 1; --- List all the existing cached connections. loopback and loopback2 should be --- output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; --- Issue a warning and return false as loopback connection is still in use and --- can not be closed. -SELECT postgres_fdw_disconnect('loopback'); --- List all the existing cached connections. loopback and loopback2 should be --- output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; --- Return false as connections are still in use, warnings are issued. --- But disable warnings temporarily because the order of them is not stable. -SET client_min_messages = 'ERROR'; -SELECT postgres_fdw_disconnect_all(); -RESET client_min_messages; -COMMIT; --- Ensure that loopback2 connection is closed. -SELECT 1 FROM postgres_fdw_disconnect('loopback2'); -SELECT server_name FROM postgres_fdw_get_connections() WHERE server_name = 'loopback2'; --- Return false as loopback2 connection is closed already. -SELECT postgres_fdw_disconnect('loopback2'); --- Return an error as there is no foreign server with given name. -SELECT postgres_fdw_disconnect('unknownserver'); --- Let's ensure to close all the existing cached connections. -SELECT 1 FROM postgres_fdw_disconnect_all(); --- No cached connections, so no records should be output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; - --- ============================================================================= --- test case for having multiple cached connections for a foreign server --- ============================================================================= -CREATE ROLE regress_multi_conn_user1 SUPERUSER; -CREATE ROLE regress_multi_conn_user2 SUPERUSER; -CREATE USER MAPPING FOR regress_multi_conn_user1 SERVER loopback; -CREATE USER MAPPING FOR regress_multi_conn_user2 SERVER loopback; - -BEGIN; --- Will cache loopback connection with user mapping for regress_multi_conn_user1 -SET ROLE regress_multi_conn_user1; -SELECT 1 FROM ft1 LIMIT 1; -RESET ROLE; - --- Will cache loopback connection with user mapping for regress_multi_conn_user2 -SET ROLE regress_multi_conn_user2; -SELECT 1 FROM ft1 LIMIT 1; -RESET ROLE; - --- Should output two connections for loopback server -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; -COMMIT; --- Let's ensure to close all the existing cached connections. -SELECT 1 FROM postgres_fdw_disconnect_all(); --- No cached connections, so no records should be output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; - --- Clean up -DROP USER MAPPING FOR regress_multi_conn_user1 SERVER loopback; -DROP USER MAPPING FOR regress_multi_conn_user2 SERVER loopback; -DROP ROLE regress_multi_conn_user1; -DROP ROLE regress_multi_conn_user2; - --- =================================================================== --- Test foreign server level option keep_connections --- =================================================================== --- By default, the connections associated with foreign server are cached i.e. --- keep_connections option is on. Set it to off. -ALTER SERVER loopback OPTIONS (keep_connections 'off'); --- connection to loopback server is closed at the end of xact --- as keep_connections was set to off. -SELECT 1 FROM ft1 LIMIT 1; --- No cached connections, so no records should be output. -SELECT server_name FROM postgres_fdw_get_connections() ORDER BY 1; -ALTER SERVER loopback OPTIONS (SET keep_connections 'on'); - --- =================================================================== --- batch insert --- =================================================================== - -BEGIN; - -CREATE SERVER batch10 FOREIGN DATA WRAPPER postgres_fdw OPTIONS( batch_size '10' ); - -SELECT count(*) -FROM pg_foreign_server -WHERE srvname = 'batch10' -AND srvoptions @> array['batch_size=10']; - -ALTER SERVER batch10 OPTIONS( SET batch_size '20' ); - -SELECT count(*) -FROM pg_foreign_server -WHERE srvname = 'batch10' -AND srvoptions @> array['batch_size=10']; - -SELECT count(*) -FROM pg_foreign_server -WHERE srvname = 'batch10' -AND srvoptions @> array['batch_size=20']; - -CREATE FOREIGN TABLE table30 ( x int ) SERVER batch10 OPTIONS ( batch_size '30' ); - -SELECT COUNT(*) -FROM pg_foreign_table -WHERE ftrelid = 'table30'::regclass -AND ftoptions @> array['batch_size=30']; - -ALTER FOREIGN TABLE table30 OPTIONS ( SET batch_size '40'); - -SELECT COUNT(*) -FROM pg_foreign_table -WHERE ftrelid = 'table30'::regclass -AND ftoptions @> array['batch_size=30']; - -SELECT COUNT(*) -FROM pg_foreign_table -WHERE ftrelid = 'table30'::regclass -AND ftoptions @> array['batch_size=40']; - -ROLLBACK; - -CREATE TABLE batch_table ( x int ); - -CREATE FOREIGN TABLE ftable ( x int ) SERVER loopback OPTIONS ( table_name 'batch_table', batch_size '10' ); -EXPLAIN (VERBOSE, COSTS OFF) INSERT INTO ftable SELECT * FROM generate_series(1, 10) i; -INSERT INTO ftable SELECT * FROM generate_series(1, 10) i; -INSERT INTO ftable SELECT * FROM generate_series(11, 31) i; -INSERT INTO ftable VALUES (32); -INSERT INTO ftable VALUES (33), (34); -SELECT COUNT(*) FROM ftable; -TRUNCATE batch_table; -DROP FOREIGN TABLE ftable; - --- try if large batches exceed max number of bind parameters -CREATE FOREIGN TABLE ftable ( x int ) SERVER loopback OPTIONS ( table_name 'batch_table', batch_size '100000' ); -INSERT INTO ftable SELECT * FROM generate_series(1, 70000) i; -SELECT COUNT(*) FROM ftable; -TRUNCATE batch_table; -DROP FOREIGN TABLE ftable; - --- Disable batch insert -CREATE FOREIGN TABLE ftable ( x int ) SERVER loopback OPTIONS ( table_name 'batch_table', batch_size '1' ); -EXPLAIN (VERBOSE, COSTS OFF) INSERT INTO ftable VALUES (1), (2); -INSERT INTO ftable VALUES (1), (2); -SELECT COUNT(*) FROM ftable; - --- Disable batch inserting into foreign tables with BEFORE ROW INSERT triggers --- even if the batch_size option is enabled. -ALTER FOREIGN TABLE ftable OPTIONS ( SET batch_size '10' ); -CREATE TRIGGER trig_row_before BEFORE INSERT ON ftable -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -EXPLAIN (VERBOSE, COSTS OFF) INSERT INTO ftable VALUES (3), (4); -INSERT INTO ftable VALUES (3), (4); -SELECT COUNT(*) FROM ftable; - --- Clean up -DROP TRIGGER trig_row_before ON ftable; -DROP FOREIGN TABLE ftable; -DROP TABLE batch_table; - --- Use partitioning -CREATE TABLE batch_table ( x int ) PARTITION BY HASH (x); - -CREATE TABLE batch_table_p0 (LIKE batch_table); -CREATE FOREIGN TABLE batch_table_p0f - PARTITION OF batch_table - FOR VALUES WITH (MODULUS 3, REMAINDER 0) - SERVER loopback - OPTIONS (table_name 'batch_table_p0', batch_size '10'); - -CREATE TABLE batch_table_p1 (LIKE batch_table); -CREATE FOREIGN TABLE batch_table_p1f - PARTITION OF batch_table - FOR VALUES WITH (MODULUS 3, REMAINDER 1) - SERVER loopback - OPTIONS (table_name 'batch_table_p1', batch_size '1'); - -CREATE TABLE batch_table_p2 - PARTITION OF batch_table - FOR VALUES WITH (MODULUS 3, REMAINDER 2); - -INSERT INTO batch_table SELECT * FROM generate_series(1, 66) i; -SELECT COUNT(*) FROM batch_table; - --- Check that enabling batched inserts doesn't interfere with cross-partition --- updates -CREATE TABLE batch_cp_upd_test (a int) PARTITION BY LIST (a); -CREATE TABLE batch_cp_upd_test1 (LIKE batch_cp_upd_test); -CREATE FOREIGN TABLE batch_cp_upd_test1_f - PARTITION OF batch_cp_upd_test - FOR VALUES IN (1) - SERVER loopback - OPTIONS (table_name 'batch_cp_upd_test1', batch_size '10'); -CREATE TABLE batch_cp_up_test1 PARTITION OF batch_cp_upd_test - FOR VALUES IN (2); -INSERT INTO batch_cp_upd_test VALUES (1), (2); - --- The following moves a row from the local partition to the foreign one -UPDATE batch_cp_upd_test t SET a = 1 FROM (VALUES (1), (2)) s(a) WHERE t.a = s.a; -SELECT tableoid::regclass, * FROM batch_cp_upd_test; - --- Clean up -DROP TABLE batch_table, batch_cp_upd_test, batch_table_p0, batch_table_p1 CASCADE; - --- Use partitioning -ALTER SERVER loopback OPTIONS (ADD batch_size '10'); - -CREATE TABLE batch_table ( x int, field1 text, field2 text) PARTITION BY HASH (x); - -CREATE TABLE batch_table_p0 (LIKE batch_table); -ALTER TABLE batch_table_p0 ADD CONSTRAINT p0_pkey PRIMARY KEY (x); -CREATE FOREIGN TABLE batch_table_p0f - PARTITION OF batch_table - FOR VALUES WITH (MODULUS 2, REMAINDER 0) - SERVER loopback - OPTIONS (table_name 'batch_table_p0'); - -CREATE TABLE batch_table_p1 (LIKE batch_table); -ALTER TABLE batch_table_p1 ADD CONSTRAINT p1_pkey PRIMARY KEY (x); -CREATE FOREIGN TABLE batch_table_p1f - PARTITION OF batch_table - FOR VALUES WITH (MODULUS 2, REMAINDER 1) - SERVER loopback - OPTIONS (table_name 'batch_table_p1'); - -INSERT INTO batch_table SELECT i, 'test'||i, 'test'|| i FROM generate_series(1, 50) i; -SELECT COUNT(*) FROM batch_table; -SELECT * FROM batch_table ORDER BY x; - -ALTER SERVER loopback OPTIONS (DROP batch_size); - --- =================================================================== --- test asynchronous execution --- =================================================================== - -ALTER SERVER loopback OPTIONS (DROP extensions); -ALTER SERVER loopback OPTIONS (ADD async_capable 'true'); -ALTER SERVER loopback2 OPTIONS (ADD async_capable 'true'); - -CREATE TABLE async_pt (a int, b int, c text) PARTITION BY RANGE (a); -CREATE TABLE base_tbl1 (a int, b int, c text); -CREATE TABLE base_tbl2 (a int, b int, c text); -CREATE FOREIGN TABLE async_p1 PARTITION OF async_pt FOR VALUES FROM (1000) TO (2000) - SERVER loopback OPTIONS (table_name 'base_tbl1'); -CREATE FOREIGN TABLE async_p2 PARTITION OF async_pt FOR VALUES FROM (2000) TO (3000) - SERVER loopback2 OPTIONS (table_name 'base_tbl2'); -INSERT INTO async_p1 SELECT 1000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; -INSERT INTO async_p2 SELECT 2000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; -ANALYZE async_pt; - --- simple queries -CREATE TABLE result_tbl (a int, b int, c text); - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b % 100 = 0; -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b % 100 = 0; - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505; -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505; - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl SELECT a, b, 'AAA' || c FROM async_pt WHERE b === 505; -INSERT INTO result_tbl SELECT a, b, 'AAA' || c FROM async_pt WHERE b === 505; - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - --- Check case where multiple partitions use the same connection -CREATE TABLE base_tbl3 (a int, b int, c text); -CREATE FOREIGN TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000) - SERVER loopback2 OPTIONS (table_name 'base_tbl3'); -INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; -ANALYZE async_pt; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505; -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505; - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - -DROP FOREIGN TABLE async_p3; -DROP TABLE base_tbl3; - --- Check case where the partitioned table has local/remote partitions -CREATE TABLE async_p3 PARTITION OF async_pt FOR VALUES FROM (3000) TO (4000); -INSERT INTO async_p3 SELECT 3000 + i, i, to_char(i, 'FM0000') FROM generate_series(0, 999, 5) i; -ANALYZE async_pt; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505; -INSERT INTO result_tbl SELECT * FROM async_pt WHERE b === 505; - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - --- partitionwise joins -SET enable_partitionwise_join TO true; - -CREATE TABLE join_tbl (a1 int, b1 int, c1 text, a2 int, b2 int, c2 text); - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO join_tbl SELECT * FROM async_pt t1, async_pt t2 WHERE t1.a = t2.a AND t1.b = t2.b AND t1.b % 100 = 0; -INSERT INTO join_tbl SELECT * FROM async_pt t1, async_pt t2 WHERE t1.a = t2.a AND t1.b = t2.b AND t1.b % 100 = 0; - -SELECT * FROM join_tbl ORDER BY a1; -DELETE FROM join_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO join_tbl SELECT t1.a, t1.b, 'AAA' || t1.c, t2.a, t2.b, 'AAA' || t2.c FROM async_pt t1, async_pt t2 WHERE t1.a = t2.a AND t1.b = t2.b AND t1.b % 100 = 0; -INSERT INTO join_tbl SELECT t1.a, t1.b, 'AAA' || t1.c, t2.a, t2.b, 'AAA' || t2.c FROM async_pt t1, async_pt t2 WHERE t1.a = t2.a AND t1.b = t2.b AND t1.b % 100 = 0; - -SELECT * FROM join_tbl ORDER BY a1; -DELETE FROM join_tbl; - -RESET enable_partitionwise_join; - --- Test rescan of an async Append node with do_exec_prune=false -SET enable_hashjoin TO false; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO join_tbl SELECT * FROM async_p1 t1, async_pt t2 WHERE t1.a = t2.a AND t1.b = t2.b AND t1.b % 100 = 0; -INSERT INTO join_tbl SELECT * FROM async_p1 t1, async_pt t2 WHERE t1.a = t2.a AND t1.b = t2.b AND t1.b % 100 = 0; - -SELECT * FROM join_tbl ORDER BY a1; -DELETE FROM join_tbl; - -RESET enable_hashjoin; - --- Test interaction of async execution with plan-time partition pruning -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM async_pt WHERE a < 3000; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM async_pt WHERE a < 2000; - --- Test interaction of async execution with run-time partition pruning -SET plan_cache_mode TO force_generic_plan; - -PREPARE async_pt_query (int, int) AS - INSERT INTO result_tbl SELECT * FROM async_pt WHERE a < $1 AND b === $2; - -EXPLAIN (VERBOSE, COSTS OFF) -EXECUTE async_pt_query (3000, 505); -EXECUTE async_pt_query (3000, 505); - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -EXECUTE async_pt_query (2000, 505); -EXECUTE async_pt_query (2000, 505); - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - -RESET plan_cache_mode; - -CREATE TABLE local_tbl(a int, b int, c text); -INSERT INTO local_tbl VALUES (1505, 505, 'foo'), (2505, 505, 'bar'); -ANALYZE local_tbl; - -CREATE INDEX base_tbl1_idx ON base_tbl1 (a); -CREATE INDEX base_tbl2_idx ON base_tbl2 (a); -CREATE INDEX async_p3_idx ON async_p3 (a); -ANALYZE base_tbl1; -ANALYZE base_tbl2; -ANALYZE async_p3; - -ALTER FOREIGN TABLE async_p1 OPTIONS (use_remote_estimate 'true'); -ALTER FOREIGN TABLE async_p2 OPTIONS (use_remote_estimate 'true'); - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM local_tbl, async_pt WHERE local_tbl.a = async_pt.a AND local_tbl.c = 'bar'; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -SELECT * FROM local_tbl, async_pt WHERE local_tbl.a = async_pt.a AND local_tbl.c = 'bar'; -SELECT * FROM local_tbl, async_pt WHERE local_tbl.a = async_pt.a AND local_tbl.c = 'bar'; - -ALTER FOREIGN TABLE async_p1 OPTIONS (DROP use_remote_estimate); -ALTER FOREIGN TABLE async_p2 OPTIONS (DROP use_remote_estimate); - -DROP TABLE local_tbl; -DROP INDEX base_tbl1_idx; -DROP INDEX base_tbl2_idx; -DROP INDEX async_p3_idx; - --- UNION queries -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl -(SELECT a, b, 'AAA' || c FROM async_p1 ORDER BY a LIMIT 10) -UNION -(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10); -INSERT INTO result_tbl -(SELECT a, b, 'AAA' || c FROM async_p1 ORDER BY a LIMIT 10) -UNION -(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10); - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO result_tbl -(SELECT a, b, 'AAA' || c FROM async_p1 ORDER BY a LIMIT 10) -UNION ALL -(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10); -INSERT INTO result_tbl -(SELECT a, b, 'AAA' || c FROM async_p1 ORDER BY a LIMIT 10) -UNION ALL -(SELECT a, b, 'AAA' || c FROM async_p2 WHERE b < 10); - -SELECT * FROM result_tbl ORDER BY a; -DELETE FROM result_tbl; - --- Disable async execution if we use gating Result nodes for pseudoconstant --- quals -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM async_pt WHERE CURRENT_USER = SESSION_USER; - -EXPLAIN (VERBOSE, COSTS OFF) -(SELECT * FROM async_p1 WHERE CURRENT_USER = SESSION_USER) -UNION ALL -(SELECT * FROM async_p2 WHERE CURRENT_USER = SESSION_USER); - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM ((SELECT * FROM async_p1 WHERE b < 10) UNION ALL (SELECT * FROM async_p2 WHERE b < 10)) s WHERE CURRENT_USER = SESSION_USER; - --- Test that pending requests are processed properly -SET enable_mergejoin TO false; -SET enable_hashjoin TO false; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM async_pt t1, async_p2 t2 WHERE t1.a = t2.a AND t1.b === 505; -SELECT * FROM async_pt t1, async_p2 t2 WHERE t1.a = t2.a AND t1.b === 505; - -CREATE TABLE local_tbl (a int, b int, c text); -INSERT INTO local_tbl VALUES (1505, 505, 'foo'); -ANALYZE local_tbl; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM local_tbl t1 LEFT JOIN (SELECT *, (SELECT count(*) FROM async_pt WHERE a < 3000) FROM async_pt WHERE a < 3000) t2 ON t1.a = t2.a; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -SELECT * FROM local_tbl t1 LEFT JOIN (SELECT *, (SELECT count(*) FROM async_pt WHERE a < 3000) FROM async_pt WHERE a < 3000) t2 ON t1.a = t2.a; -SELECT * FROM local_tbl t1 LEFT JOIN (SELECT *, (SELECT count(*) FROM async_pt WHERE a < 3000) FROM async_pt WHERE a < 3000) t2 ON t1.a = t2.a; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT * FROM async_pt t1 WHERE t1.b === 505 LIMIT 1; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -SELECT * FROM async_pt t1 WHERE t1.b === 505 LIMIT 1; -SELECT * FROM async_pt t1 WHERE t1.b === 505 LIMIT 1; - --- Check with foreign modify -CREATE TABLE base_tbl3 (a int, b int, c text); -CREATE FOREIGN TABLE remote_tbl (a int, b int, c text) - SERVER loopback OPTIONS (table_name 'base_tbl3'); -INSERT INTO remote_tbl VALUES (2505, 505, 'bar'); - -CREATE TABLE base_tbl4 (a int, b int, c text); -CREATE FOREIGN TABLE insert_tbl (a int, b int, c text) - SERVER loopback OPTIONS (table_name 'base_tbl4'); - -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl); -INSERT INTO insert_tbl (SELECT * FROM local_tbl UNION ALL SELECT * FROM remote_tbl); - -SELECT * FROM insert_tbl ORDER BY a; - --- Check with direct modify -EXPLAIN (VERBOSE, COSTS OFF) -WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *) -INSERT INTO join_tbl SELECT * FROM async_pt LEFT JOIN t ON (async_pt.a = t.a AND async_pt.b = t.b) WHERE async_pt.b === 505; -WITH t AS (UPDATE remote_tbl SET c = c || c RETURNING *) -INSERT INTO join_tbl SELECT * FROM async_pt LEFT JOIN t ON (async_pt.a = t.a AND async_pt.b = t.b) WHERE async_pt.b === 505; - -SELECT * FROM join_tbl ORDER BY a1; -DELETE FROM join_tbl; - -DROP TABLE local_tbl; -DROP FOREIGN TABLE remote_tbl; -DROP FOREIGN TABLE insert_tbl; -DROP TABLE base_tbl3; -DROP TABLE base_tbl4; - -RESET enable_mergejoin; -RESET enable_hashjoin; - --- Test that UPDATE/DELETE with inherited target works with async_capable enabled -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE async_pt SET c = c || c WHERE b = 0 RETURNING *; -UPDATE async_pt SET c = c || c WHERE b = 0 RETURNING *; -EXPLAIN (VERBOSE, COSTS OFF) -DELETE FROM async_pt WHERE b = 0 RETURNING *; -DELETE FROM async_pt WHERE b = 0 RETURNING *; - --- Check EXPLAIN ANALYZE for a query that scans empty partitions asynchronously -DELETE FROM async_p1; -DELETE FROM async_p2; -DELETE FROM async_p3; - -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -SELECT * FROM async_pt; - --- Clean up -DROP TABLE async_pt; -DROP TABLE base_tbl1; -DROP TABLE base_tbl2; -DROP TABLE result_tbl; -DROP TABLE join_tbl; - --- Test that an asynchronous fetch is processed before restarting the scan in --- ReScanForeignScan -CREATE TABLE base_tbl (a int, b int); -INSERT INTO base_tbl VALUES (1, 11), (2, 22), (3, 33); -CREATE FOREIGN TABLE foreign_tbl (b int) - SERVER loopback OPTIONS (table_name 'base_tbl'); -CREATE FOREIGN TABLE foreign_tbl2 () INHERITS (foreign_tbl) - SERVER loopback OPTIONS (table_name 'base_tbl'); - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT a FROM base_tbl WHERE a IN (SELECT a FROM foreign_tbl); -SELECT a FROM base_tbl WHERE a IN (SELECT a FROM foreign_tbl); - --- Clean up -DROP FOREIGN TABLE foreign_tbl CASCADE; -DROP TABLE base_tbl; - -ALTER SERVER loopback OPTIONS (DROP async_capable); -ALTER SERVER loopback2 OPTIONS (DROP async_capable); - --- =================================================================== --- test invalid server, foreign table and foreign data wrapper options --- =================================================================== --- Invalid fdw_startup_cost option -CREATE SERVER inv_scst FOREIGN DATA WRAPPER postgres_fdw - OPTIONS(fdw_startup_cost '100$%$#$#'); --- Invalid fdw_tuple_cost option -CREATE SERVER inv_scst FOREIGN DATA WRAPPER postgres_fdw - OPTIONS(fdw_tuple_cost '100$%$#$#'); --- Invalid fetch_size option -CREATE FOREIGN TABLE inv_fsz (c1 int ) - SERVER loopback OPTIONS (fetch_size '100$%$#$#'); --- Invalid batch_size option -CREATE FOREIGN TABLE inv_bsz (c1 int ) - SERVER loopback OPTIONS (batch_size '100$%$#$#'); - --- No option is allowed to be specified at foreign data wrapper level -ALTER FOREIGN DATA WRAPPER postgres_fdw OPTIONS (nonexistent 'fdw'); - --- =================================================================== --- test postgres_fdw.application_name GUC --- =================================================================== ---- Turn debug_discard_caches off for this test to make sure that ---- the remote connection is alive when checking its application_name. -SET debug_discard_caches = 0; - --- Specify escape sequences in application_name option of a server --- object so as to test that they are replaced with status information --- expectedly. --- --- Since pg_stat_activity.application_name may be truncated to less than --- NAMEDATALEN characters, note that substring() needs to be used --- at the condition of test query to make sure that the string consisting --- of database name and process ID is also less than that. -ALTER SERVER loopback2 OPTIONS (application_name 'fdw_%d%p'); -SELECT 1 FROM ft6 LIMIT 1; -SELECT pg_terminate_backend(pid, 180000) FROM pg_stat_activity - WHERE application_name = - substring('fdw_' || current_database() || pg_backend_pid() for - current_setting('max_identifier_length')::int); - --- postgres_fdw.application_name overrides application_name option --- of a server object if both settings are present. -SET postgres_fdw.application_name TO 'fdw_%a%u%%'; -SELECT 1 FROM ft6 LIMIT 1; -SELECT pg_terminate_backend(pid, 180000) FROM pg_stat_activity - WHERE application_name = - substring('fdw_' || current_setting('application_name') || - CURRENT_USER || '%' for current_setting('max_identifier_length')::int); - --- Test %c (session ID) and %C (cluster name) escape sequences. -SET postgres_fdw.application_name TO 'fdw_%C%c'; -SELECT 1 FROM ft6 LIMIT 1; -SELECT pg_terminate_backend(pid, 180000) FROM pg_stat_activity - WHERE application_name = - substring('fdw_' || current_setting('cluster_name') || - to_hex(trunc(EXTRACT(EPOCH FROM (SELECT backend_start FROM - pg_stat_get_activity(pg_backend_pid()))))::integer) || '.' || - to_hex(pg_backend_pid()) - for current_setting('max_identifier_length')::int); - ---Clean up -RESET postgres_fdw.application_name; -RESET debug_discard_caches; - --- =================================================================== --- test parallel commit --- =================================================================== -ALTER SERVER loopback OPTIONS (ADD parallel_commit 'true'); -ALTER SERVER loopback2 OPTIONS (ADD parallel_commit 'true'); - -CREATE TABLE ploc1 (f1 int, f2 text); -CREATE FOREIGN TABLE prem1 (f1 int, f2 text) - SERVER loopback OPTIONS (table_name 'ploc1'); -CREATE TABLE ploc2 (f1 int, f2 text); -CREATE FOREIGN TABLE prem2 (f1 int, f2 text) - SERVER loopback2 OPTIONS (table_name 'ploc2'); - -BEGIN; -INSERT INTO prem1 VALUES (101, 'foo'); -INSERT INTO prem2 VALUES (201, 'bar'); -COMMIT; -SELECT * FROM prem1; -SELECT * FROM prem2; - -BEGIN; -SAVEPOINT s; -INSERT INTO prem1 VALUES (102, 'foofoo'); -INSERT INTO prem2 VALUES (202, 'barbar'); -RELEASE SAVEPOINT s; -COMMIT; -SELECT * FROM prem1; -SELECT * FROM prem2; - --- This tests executing DEALLOCATE ALL against foreign servers in parallel --- during pre-commit -BEGIN; -SAVEPOINT s; -INSERT INTO prem1 VALUES (103, 'baz'); -INSERT INTO prem2 VALUES (203, 'qux'); -ROLLBACK TO SAVEPOINT s; -RELEASE SAVEPOINT s; -INSERT INTO prem1 VALUES (104, 'bazbaz'); -INSERT INTO prem2 VALUES (204, 'quxqux'); -COMMIT; -SELECT * FROM prem1; -SELECT * FROM prem2; - -ALTER SERVER loopback OPTIONS (DROP parallel_commit); -ALTER SERVER loopback2 OPTIONS (DROP parallel_commit); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fseg%2Fseg--1.0--1.1.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fseg%2Fseg--1.0--1.1.sql deleted file mode 100644 index ae6cb2fba8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fseg%2Fseg--1.0--1.1.sql +++ /dev/null @@ -1,63 +0,0 @@ -/* contrib/seg/seg--1.0--1.1.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION seg UPDATE TO '1.1'" to load this file. \quit - --- Update procedure signatures the hard way. --- We use to_regprocedure() so that query doesn't fail if run against 9.6beta1 definitions, --- wherein the signatures have been updated already. In that case to_regprocedure() will --- return NULL and no updates will happen. -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_proc SET - proargtypes = pg_catalog.array_to_string(newtypes::pg_catalog.oid[], ' ')::pg_catalog.oidvector, - pronargs = pg_catalog.array_length(newtypes, 1) -FROM (VALUES -(NULL::pg_catalog.text, NULL::pg_catalog.text[]), -- establish column types -('gseg_consistent(internal,SCH.seg,int4,oid,internal)', '{internal,SCH.seg,int2,oid,internal}') -) AS update_data (oldproc, newtypestext), -LATERAL ( - SELECT array_agg(replace(typ, 'SCH', my_schema)::regtype) as newtypes FROM unnest(newtypestext) typ -) ls -WHERE oid = to_regprocedure(my_schema || '.' || replace(oldproc, 'SCH', my_schema)); - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER FUNCTION seg_in(cstring) PARALLEL SAFE; -ALTER FUNCTION seg_out(seg) PARALLEL SAFE; -ALTER FUNCTION seg_over_left(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_over_right(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_left(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_right(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_lt(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_le(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_gt(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_ge(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_contains(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_contained(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_overlap(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_same(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_different(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_cmp(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_union(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_inter(seg, seg) PARALLEL SAFE; -ALTER FUNCTION seg_size(seg) PARALLEL SAFE; -ALTER FUNCTION seg_center(seg) PARALLEL SAFE; -ALTER FUNCTION seg_upper(seg) PARALLEL SAFE; -ALTER FUNCTION seg_lower(seg) PARALLEL SAFE; -ALTER FUNCTION gseg_consistent(internal, seg, smallint, oid, internal) PARALLEL SAFE; -ALTER FUNCTION gseg_compress(internal) PARALLEL SAFE; -ALTER FUNCTION gseg_decompress(internal) PARALLEL SAFE; -ALTER FUNCTION gseg_penalty(internal, internal, internal) PARALLEL SAFE; -ALTER FUNCTION gseg_picksplit(internal, internal) PARALLEL SAFE; -ALTER FUNCTION gseg_union(internal, internal) PARALLEL SAFE; -ALTER FUNCTION gseg_same(seg, seg, internal) PARALLEL SAFE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fseg%2Fseg--1.2--1.3.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fseg%2Fseg--1.2--1.3.sql deleted file mode 100644 index 578e98953c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fseg%2Fseg--1.2--1.3.sql +++ /dev/null @@ -1,58 +0,0 @@ -/* contrib/seg/seg--1.2--1.3.sql */ - --- complain if script is sourced in psql, rather than via ALTER EXTENSION -\echo Use "ALTER EXTENSION seg UPDATE TO '1.3'" to load this file. \quit - --- --- Get rid of unnecessary compress and decompress support functions. --- --- To be allowed to drop the opclass entry for a support function, --- we must change the entry's dependency type from 'internal' to 'auto', --- as though it were a loose member of the opfamily rather than being --- bound into a particular opclass. There's no SQL command for that, --- so fake it with a manual update on pg_depend. --- -DO LANGUAGE plpgsql -$$ -DECLARE - my_schema pg_catalog.text := pg_catalog.quote_ident(pg_catalog.current_schema()); - old_path pg_catalog.text := pg_catalog.current_setting('search_path'); -BEGIN --- for safety, transiently set search_path to just pg_catalog+pg_temp -PERFORM pg_catalog.set_config('search_path', 'pg_catalog, pg_temp', true); - -UPDATE pg_catalog.pg_depend -SET deptype = 'a' -WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND objid = - (SELECT objid - FROM pg_catalog.pg_depend - WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass - AND (refobjid = (my_schema || '.gseg_compress(internal)')::pg_catalog.regprocedure)) - AND refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass - AND deptype = 'i'; - -UPDATE pg_catalog.pg_depend -SET deptype = 'a' -WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND objid = - (SELECT objid - FROM pg_catalog.pg_depend - WHERE classid = 'pg_catalog.pg_amproc'::pg_catalog.regclass - AND refclassid = 'pg_catalog.pg_proc'::pg_catalog.regclass - AND (refobjid = (my_schema || '.gseg_decompress(internal)')::pg_catalog.regprocedure)) - AND refclassid = 'pg_catalog.pg_opclass'::pg_catalog.regclass - AND deptype = 'i'; - -PERFORM pg_catalog.set_config('search_path', old_path, true); -END -$$; - -ALTER OPERATOR FAMILY gist_seg_ops USING gist drop function 3 (seg); -ALTER EXTENSION seg DROP function gseg_compress(pg_catalog.internal); -DROP function gseg_compress(pg_catalog.internal); - -ALTER OPERATOR FAMILY gist_seg_ops USING gist drop function 4 (seg); -ALTER EXTENSION seg DROP function gseg_decompress(pg_catalog.internal); -DROP function gseg_decompress(pg_catalog.internal); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Falter.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Falter.sql deleted file mode 100644 index f114449232..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Falter.sql +++ /dev/null @@ -1,197 +0,0 @@ --- --- Test for various ALTER statements --- - --- clean-up in case a prior regression run failed -SET client_min_messages TO 'warning'; -DROP DATABASE IF EXISTS sepgsql_test_regression_1; -DROP DATABASE IF EXISTS sepgsql_test_regression; -DROP USER IF EXISTS regress_sepgsql_test_user; -RESET client_min_messages; - --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0 - --- --- CREATE Objects to be altered (with debug_audit being silent) --- -CREATE DATABASE sepgsql_test_regression_1; - -CREATE USER regress_sepgsql_test_user; - -CREATE SCHEMA regtest_schema_1; -CREATE SCHEMA regtest_schema_2; - -GRANT ALL ON SCHEMA regtest_schema_1 TO public; -GRANT ALL ON SCHEMA regtest_schema_2 TO public; - -SET search_path = regtest_schema_1, regtest_schema_2, public; - -CREATE TABLE regtest_table_1 (a int, b text); - -CREATE TABLE regtest_table_2 (c text) inherits (regtest_table_1); - -CREATE TABLE regtest_table_3 (x int primary key, y text); - ---- --- partitioned table parent -CREATE TABLE regtest_ptable_1 (o int, p text) PARTITION BY RANGE (o); - --- partitioned table children -CREATE TABLE regtest_ptable_1_ones PARTITION OF regtest_ptable_1 FOR VALUES FROM ('0') TO ('10'); -CREATE TABLE regtest_ptable_1_tens PARTITION OF regtest_ptable_1 FOR VALUES FROM ('10') TO ('100'); ---- - -CREATE SEQUENCE regtest_seq_1; - -CREATE VIEW regtest_view_1 AS SELECT * FROM regtest_table_1 WHERE a > 0; - -CREATE FUNCTION regtest_func_1 (text) RETURNS bool - AS 'BEGIN RETURN true; END' LANGUAGE 'plpgsql'; - --- switch on debug_audit -SET sepgsql.debug_audit = true; -SET client_min_messages = LOG; - --- --- ALTER xxx OWNER TO --- --- XXX: It should take db_xxx:{setattr} permission checks even if --- owner is not actually changed. --- -ALTER DATABASE sepgsql_test_regression_1 OWNER TO regress_sepgsql_test_user; -ALTER DATABASE sepgsql_test_regression_1 OWNER TO regress_sepgsql_test_user; -ALTER SCHEMA regtest_schema_1 OWNER TO regress_sepgsql_test_user; -ALTER SCHEMA regtest_schema_1 OWNER TO regress_sepgsql_test_user; -ALTER TABLE regtest_table_1 OWNER TO regress_sepgsql_test_user; -ALTER TABLE regtest_table_1 OWNER TO regress_sepgsql_test_user; -ALTER TABLE regtest_ptable_1 OWNER TO regress_sepgsql_test_user; -ALTER TABLE regtest_ptable_1_ones OWNER TO regress_sepgsql_test_user; -ALTER SEQUENCE regtest_seq_1 OWNER TO regress_sepgsql_test_user; -ALTER SEQUENCE regtest_seq_1 OWNER TO regress_sepgsql_test_user; -ALTER VIEW regtest_view_1 OWNER TO regress_sepgsql_test_user; -ALTER VIEW regtest_view_1 OWNER TO regress_sepgsql_test_user; -ALTER FUNCTION regtest_func_1(text) OWNER TO regress_sepgsql_test_user; -ALTER FUNCTION regtest_func_1(text) OWNER TO regress_sepgsql_test_user; - --- --- ALTER xxx SET SCHEMA --- -ALTER TABLE regtest_table_1 SET SCHEMA regtest_schema_2; -ALTER TABLE regtest_ptable_1 SET SCHEMA regtest_schema_2; -ALTER TABLE regtest_ptable_1_ones SET SCHEMA regtest_schema_2; -ALTER SEQUENCE regtest_seq_1 SET SCHEMA regtest_schema_2; -ALTER VIEW regtest_view_1 SET SCHEMA regtest_schema_2; -ALTER FUNCTION regtest_func_1(text) SET SCHEMA regtest_schema_2; - --- --- ALTER xxx RENAME TO --- -ALTER DATABASE sepgsql_test_regression_1 RENAME TO sepgsql_test_regression; -ALTER SCHEMA regtest_schema_1 RENAME TO regtest_schema; -ALTER TABLE regtest_table_1 RENAME TO regtest_table; - ---- --- partitioned table parent -ALTER TABLE regtest_ptable_1 RENAME TO regtest_ptable; --- partitioned table child -ALTER TABLE regtest_ptable_1_ones RENAME TO regtest_table_part; ---- - -ALTER SEQUENCE regtest_seq_1 RENAME TO regtest_seq; -ALTER VIEW regtest_view_1 RENAME TO regtest_view; -ALTER FUNCTION regtest_func_1(text) RENAME TO regtest_func; - -SET search_path = regtest_schema, regtest_schema_2, public; - --- --- misc ALTER commands --- -ALTER DATABASE sepgsql_test_regression CONNECTION LIMIT 999; -ALTER DATABASE sepgsql_test_regression SET search_path TO regtest_schema, public; -- not supported yet - -ALTER TABLE regtest_table ADD COLUMN d float; -ALTER TABLE regtest_table DROP COLUMN d; -ALTER TABLE regtest_table ALTER b SET DEFAULT 'abcd'; -- not supported yet -ALTER TABLE regtest_table ALTER b SET DEFAULT 'XYZ'; -- not supported yet -ALTER TABLE regtest_table ALTER b DROP DEFAULT; -- not supported yet -ALTER TABLE regtest_table ALTER b SET NOT NULL; -ALTER TABLE regtest_table ALTER b DROP NOT NULL; -ALTER TABLE regtest_table ALTER b SET STATISTICS -1; -ALTER TABLE regtest_table ALTER b SET (n_distinct = 999); -ALTER TABLE regtest_table ALTER b SET STORAGE PLAIN; -ALTER TABLE regtest_table ADD CONSTRAINT test_fk FOREIGN KEY (a) REFERENCES regtest_table_3(x); -- not supported -ALTER TABLE regtest_table ADD CONSTRAINT test_ck CHECK (b like '%abc%') NOT VALID; -- not supported -ALTER TABLE regtest_table VALIDATE CONSTRAINT test_ck; -- not supported -ALTER TABLE regtest_table DROP CONSTRAINT test_ck; -- not supported - -CREATE TRIGGER regtest_test_trig BEFORE UPDATE ON regtest_table - FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger(); - -ALTER TABLE regtest_table DISABLE TRIGGER regtest_test_trig; -- not supported -ALTER TABLE regtest_table ENABLE TRIGGER regtest_test_trig; -- not supported - -CREATE RULE regtest_test_rule AS ON INSERT TO regtest_table_3 DO ALSO NOTHING; -ALTER TABLE regtest_table_3 DISABLE RULE regtest_test_rule; -- not supported -ALTER TABLE regtest_table_3 ENABLE RULE regtest_test_rule; -- not supported - -ALTER TABLE regtest_table SET (fillfactor = 75); -ALTER TABLE regtest_table RESET (fillfactor); -ALTER TABLE regtest_table_2 NO INHERIT regtest_table; -- not supported -ALTER TABLE regtest_table_2 INHERIT regtest_table; -- not supported -ALTER TABLE regtest_table SET TABLESPACE pg_default; - ---- --- partitioned table parent -ALTER TABLE regtest_ptable ADD COLUMN d float; -ALTER TABLE regtest_ptable DROP COLUMN d; -ALTER TABLE regtest_ptable ALTER p SET DEFAULT 'abcd'; -- not supported by sepgsql -ALTER TABLE regtest_ptable ALTER p SET DEFAULT 'XYZ'; -- not supported by sepgsql -ALTER TABLE regtest_ptable ALTER p DROP DEFAULT; -- not supported by sepgsql -ALTER TABLE regtest_ptable ALTER p SET NOT NULL; -ALTER TABLE regtest_ptable ALTER p DROP NOT NULL; -ALTER TABLE regtest_ptable ALTER p SET STATISTICS -1; -ALTER TABLE regtest_ptable ALTER p SET (n_distinct = 999); -ALTER TABLE regtest_ptable ALTER p SET STORAGE PLAIN; -ALTER TABLE regtest_ptable ADD CONSTRAINT test_ck CHECK (p like '%abc%') NOT VALID; -- not supported by sepgsql -ALTER TABLE regtest_ptable DROP CONSTRAINT test_ck; -- not supported by sepgsql - -ALTER TABLE regtest_ptable SET TABLESPACE pg_default; - --- partitioned table child -ALTER TABLE regtest_table_part ALTER p SET DEFAULT 'abcd'; -- not supported by sepgsql -ALTER TABLE regtest_table_part ALTER p SET DEFAULT 'XYZ'; -- not supported by sepgsql -ALTER TABLE regtest_table_part ALTER p DROP DEFAULT; -- not supported by sepgsql -ALTER TABLE regtest_table_part ALTER p SET NOT NULL; -ALTER TABLE regtest_table_part ALTER p DROP NOT NULL; -ALTER TABLE regtest_table_part ALTER p SET STATISTICS -1; -ALTER TABLE regtest_table_part ALTER p SET (n_distinct = 999); -ALTER TABLE regtest_table_part ALTER p SET STORAGE PLAIN; -ALTER TABLE regtest_table_part ADD CONSTRAINT test_ck CHECK (p like '%abc%') NOT VALID; -- not supported by sepgsql -ALTER TABLE regtest_table_part VALIDATE CONSTRAINT test_ck; -- not supported by sepgsql -ALTER TABLE regtest_table_part DROP CONSTRAINT test_ck; -- not supported by sepgsql - -CREATE TRIGGER regtest_part_test_trig BEFORE UPDATE ON regtest_table_part - FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger(); - -ALTER TABLE regtest_table_part DISABLE TRIGGER regtest_part_test_trig; -- not supported by sepgsql -ALTER TABLE regtest_table_part ENABLE TRIGGER regtest_part_test_trig; -- not supported by sepgsql - -ALTER TABLE regtest_table_part SET (fillfactor = 75); -ALTER TABLE regtest_table_part RESET (fillfactor); - -ALTER TABLE regtest_table_part SET TABLESPACE pg_default; ---- - -ALTER VIEW regtest_view SET (security_barrier); - -ALTER SEQUENCE regtest_seq INCREMENT BY 10 START WITH 1000; - --- --- clean-up objects --- -RESET sepgsql.debug_audit; -RESET client_min_messages; -DROP DATABASE sepgsql_test_regression; -DROP SCHEMA regtest_schema CASCADE; -DROP SCHEMA regtest_schema_2 CASCADE; -DROP USER regress_sepgsql_test_user; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Fddl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Fddl.sql deleted file mode 100644 index 3deadb6252..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Fddl.sql +++ /dev/null @@ -1,125 +0,0 @@ --- --- Regression Test for DDL of Object Permission Checks --- - --- clean-up in case a prior regression run failed -SET client_min_messages TO 'warning'; -DROP DATABASE IF EXISTS sepgsql_test_regression; -DROP USER IF EXISTS regress_sepgsql_test_user; -RESET client_min_messages; - --- confirm required permissions using audit messages --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0 -SET sepgsql.debug_audit = true; -SET client_min_messages = LOG; - --- --- CREATE Permission checks --- -CREATE DATABASE sepgsql_test_regression; - -CREATE USER regress_sepgsql_test_user; - -CREATE SCHEMA regtest_schema; - -GRANT ALL ON SCHEMA regtest_schema TO regress_sepgsql_test_user; - -SET search_path = regtest_schema, public; - -CREATE TABLE regtest_table (x serial primary key, y text); - -ALTER TABLE regtest_table ADD COLUMN z int; - -CREATE TABLE regtest_table_2 (a int); - -CREATE TABLE regtest_ptable (a int) PARTITION BY RANGE (a); -CREATE TABLE regtest_ptable_ones PARTITION OF regtest_ptable FOR VALUES FROM ('0') TO ('10'); -CREATE TABLE regtest_ptable_tens PARTITION OF regtest_ptable FOR VALUES FROM ('10') TO ('100'); - -ALTER TABLE regtest_ptable ADD COLUMN q int; - --- corresponding toast table should not have label and permission checks -ALTER TABLE regtest_table_2 ADD COLUMN b text; - --- VACUUM FULL internally create a new table and swap them later. -VACUUM FULL regtest_table; -VACUUM FULL regtest_ptable; - -CREATE VIEW regtest_view AS SELECT * FROM regtest_table WHERE x < 100; -CREATE VIEW regtest_pview AS SELECT * FROM regtest_ptable WHERE a < 99; - -CREATE SEQUENCE regtest_seq; - -CREATE TYPE regtest_comptype AS (a int, b text); - -CREATE FUNCTION regtest_func(text,int[]) RETURNS bool LANGUAGE plpgsql - AS 'BEGIN RAISE NOTICE ''regtest_func => %'', $1; RETURN true; END'; - -CREATE AGGREGATE regtest_agg ( - sfunc1 = int4pl, basetype = int4, stype1 = int4, initcond1 = '0' -); - --- CREATE objects owned by others -SET SESSION AUTHORIZATION regress_sepgsql_test_user; - -SET search_path = regtest_schema, public; - -CREATE TABLE regtest_table_3 (x int, y serial); -CREATE TABLE regtest_ptable_3 (o int, p serial) PARTITION BY RANGE (o); -CREATE TABLE regtest_ptable_3_ones PARTITION OF regtest_ptable_3 FOR VALUES FROM ('0') to ('10'); -CREATE TABLE regtest_ptable_3_tens PARTITION OF regtest_ptable_3 FOR VALUES FROM ('10') to ('100'); - -CREATE VIEW regtest_view_2 AS SELECT * FROM regtest_table_3 WHERE x < y; -CREATE VIEW regtest_pview_2 AS SELECT * FROM regtest_ptable_3 WHERE o < p; - -CREATE FUNCTION regtest_func_2(int) RETURNS bool LANGUAGE plpgsql - AS 'BEGIN RETURN $1 * $1 < 100; END'; - -RESET SESSION AUTHORIZATION; - --- --- ALTER and CREATE/DROP extra attribute permissions --- -CREATE TABLE regtest_table_4 (x int primary key, y int, z int); -CREATE INDEX regtest_index_tbl4_y ON regtest_table_4(y); -CREATE INDEX regtest_index_tbl4_z ON regtest_table_4(z); -ALTER TABLE regtest_table_4 ALTER COLUMN y TYPE float; -DROP INDEX regtest_index_tbl4_y; -ALTER TABLE regtest_table_4 - ADD CONSTRAINT regtest_tbl4_con EXCLUDE USING btree (z WITH =); -DROP TABLE regtest_table_4 CASCADE; - --- For partitioned tables -CREATE TABLE regtest_ptable_4 (x int, y int, z int) PARTITION BY RANGE (x); -CREATE TABLE regtest_ptable_4_ones PARTITION OF regtest_ptable_4 FOR VALUES FROM ('0') TO ('10'); - -CREATE INDEX regtest_pindex_tbl4_y ON regtest_ptable_4_ones(y); -CREATE INDEX regtest_pindex_tbl4_z ON regtest_ptable_4_ones(z); -ALTER TABLE regtest_ptable_4 ALTER COLUMN y TYPE float; -DROP INDEX regtest_pindex_tbl4_y; -ALTER TABLE regtest_ptable_4_ones - ADD CONSTRAINT regtest_ptbl4_con EXCLUDE USING btree (z WITH =); -DROP TABLE regtest_ptable_4 CASCADE; - --- --- DROP Permission checks (with clean-up) --- - -DROP FUNCTION regtest_func(text,int[]); -DROP AGGREGATE regtest_agg(int); - -DROP SEQUENCE regtest_seq; -DROP VIEW regtest_view; - -ALTER TABLE regtest_table DROP COLUMN y; - -ALTER TABLE regtest_ptable DROP COLUMN q CASCADE; - -DROP TABLE regtest_table; -DROP TABLE regtest_ptable CASCADE; - -DROP OWNED BY regress_sepgsql_test_user; - -DROP DATABASE sepgsql_test_regression; -DROP USER regress_sepgsql_test_user; -DROP SCHEMA IF EXISTS regtest_schema CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Flabel.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Flabel.sql deleted file mode 100644 index 76e261bee8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Fsepgsql%2Fsql%2Flabel.sql +++ /dev/null @@ -1,294 +0,0 @@ --- --- Regression Tests for Label Management --- - --- --- Setup --- -CREATE TABLE t1 (a int, b text); -INSERT INTO t1 VALUES (1, 'aaa'), (2, 'bbb'), (3, 'ccc'); -CREATE TABLE t2 AS SELECT * FROM t1 WHERE a % 2 = 0; - -CREATE FUNCTION f1 () RETURNS text - AS 'SELECT sepgsql_getcon()' - LANGUAGE sql; - -CREATE FUNCTION f2 () RETURNS text - AS 'SELECT sepgsql_getcon()' - LANGUAGE sql; -SECURITY LABEL ON FUNCTION f2() - IS 'system_u:object_r:sepgsql_trusted_proc_exec_t:s0'; - -CREATE FUNCTION f3 () RETURNS text - AS 'BEGIN - RAISE EXCEPTION ''an exception from f3()''; - RETURN NULL; - END;' LANGUAGE plpgsql; -SECURITY LABEL ON FUNCTION f3() - IS 'system_u:object_r:sepgsql_trusted_proc_exec_t:s0'; - -CREATE FUNCTION f4 () RETURNS text - AS 'SELECT sepgsql_getcon()' - LANGUAGE sql; -SECURITY LABEL ON FUNCTION f4() - IS 'system_u:object_r:sepgsql_nosuch_trusted_proc_exec_t:s0'; - -CREATE FUNCTION f5 (text) RETURNS bool - AS 'SELECT sepgsql_setcon($1)' - LANGUAGE sql; -SECURITY LABEL ON FUNCTION f5(text) - IS 'system_u:object_r:sepgsql_regtest_trusted_proc_exec_t:s0'; - -CREATE TABLE auth_tbl(uname text, credential text, label text); -INSERT INTO auth_tbl - VALUES ('foo', 'acbd18db4cc2f85cedef654fccc4a4d8', 'sepgsql_regtest_foo_t:s0'), - ('var', 'b2145aac704ce76dbe1ac7adac535b23', 'sepgsql_regtest_var_t:s0'), - ('baz', 'b2145aac704ce76dbe1ac7adac535b23', 'sepgsql_regtest_baz_t:s0'); -SECURITY LABEL ON TABLE auth_tbl - IS 'system_u:object_r:sepgsql_secret_table_t:s0'; - -CREATE FUNCTION auth_func(text, text) RETURNS bool - LANGUAGE sql - AS 'SELECT sepgsql_setcon(regexp_replace(sepgsql_getcon(), ''_r:.*$'', ''_r:'' || label)) - FROM auth_tbl WHERE uname = $1 AND credential = $2'; -SECURITY LABEL ON FUNCTION auth_func(text,text) - IS 'system_u:object_r:sepgsql_regtest_trusted_proc_exec_t:s0'; - -CREATE TABLE foo_tbl(a int, b text); -INSERT INTO foo_tbl VALUES (1, 'aaa'), (2,'bbb'), (3,'ccc'), (4,'ddd'); -SECURITY LABEL ON TABLE foo_tbl - IS 'system_u:object_r:sepgsql_regtest_foo_table_t:s0'; - -CREATE TABLE var_tbl(x int, y text); -INSERT INTO var_tbl VALUES (2,'xxx'), (3,'yyy'), (4,'zzz'), (5,'xyz'); -SECURITY LABEL ON TABLE var_tbl - IS 'system_u:object_r:sepgsql_regtest_var_table_t:s0'; - -CREATE TABLE foo_ptbl(o int, p text) PARTITION BY RANGE (o); -CREATE TABLE foo_ptbl_ones PARTITION OF foo_ptbl FOR VALUES FROM ('0') TO ('10'); -CREATE TABLE foo_ptbl_tens PARTITION OF foo_ptbl FOR VALUES FROM ('10') TO ('100'); - -INSERT INTO foo_ptbl VALUES (0, 'aaa'), (9,'bbb'), (10,'ccc'), (99,'ddd'); -SECURITY LABEL ON TABLE foo_ptbl - IS 'system_u:object_r:sepgsql_regtest_foo_table_t:s0'; - -CREATE TABLE var_ptbl(q int, r text) PARTITION BY RANGE (q); -CREATE TABLE var_ptbl_ones PARTITION OF var_ptbl FOR VALUES FROM ('0') TO ('10'); -CREATE TABLE var_ptbl_tens PARTITION OF var_ptbl FOR VALUES FROM ('10') TO ('100'); - -INSERT INTO var_ptbl VALUES (0,'xxx'), (9,'yyy'), (10,'zzz'), (99,'xyz'); -SECURITY LABEL ON TABLE var_ptbl - IS 'system_u:object_r:sepgsql_regtest_var_table_t:s0'; - --- --- Tests for default labeling behavior --- --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0 -CREATE TABLE t3 (s int, t text); -INSERT INTO t3 VALUES (1, 'sss'), (2, 'ttt'), (3, 'uuu'); - --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_dba_t:s0 -CREATE TABLE t4 (m int, n text); -INSERT INTO t4 VALUES (1,'mmm'), (2,'nnn'), (3,'ooo'); - --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0 -CREATE TABLE tpart (o int, p text) PARTITION BY RANGE (o); - -CREATE TABLE tpart_ones PARTITION OF tpart FOR VALUES FROM ('0') TO ('10'); --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_dba_t:s0 -CREATE TABLE tpart_tens PARTITION OF tpart FOR VALUES FROM ('10') TO ('100'); - -INSERT INTO tpart VALUES (0, 'aaa'); -INSERT INTO tpart VALUES (9, 'bbb'); -INSERT INTO tpart VALUES (99, 'ccc'); - -SELECT objtype, objname, label FROM pg_seclabels - WHERE provider = 'selinux' AND objtype = 'table' AND objname in ('t1', 't2', 't3', - 'tpart', - 'tpart_ones', - 'tpart_tens') - ORDER BY objname COLLATE "C" ASC; -SELECT objtype, objname, label FROM pg_seclabels - WHERE provider = 'selinux' AND objtype = 'column' AND (objname like 't3.%' - OR objname like 't4.%' - OR objname like 'tpart.%' - OR objname like 'tpart_ones.%' - OR objname like 'tpart_tens.%') - ORDER BY objname COLLATE "C" ASC; - --- --- Tests for SECURITY LABEL --- --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_dba_t:s0 -SECURITY LABEL ON TABLE t1 - IS 'system_u:object_r:sepgsql_ro_table_t:s0'; -- ok -SECURITY LABEL ON TABLE t2 - IS 'invalid security context'; -- be failed -SECURITY LABEL ON COLUMN t2 - IS 'system_u:object_r:sepgsql_ro_table_t:s0'; -- be failed -SECURITY LABEL ON COLUMN t2.b - IS 'system_u:object_r:sepgsql_ro_table_t:s0'; -- ok -SECURITY LABEL ON TABLE tpart - IS 'system_u:object_r:sepgsql_ro_table_t:s0'; -- ok -SECURITY LABEL ON TABLE tpart - IS 'invalid security context'; -- failed -SECURITY LABEL ON COLUMN tpart - IS 'system_u:object_r:sepgsql_ro_table_t:s0'; -- failed -SECURITY LABEL ON COLUMN tpart.o - IS 'system_u:object_r:sepgsql_ro_table_t:s0'; -- ok - --- --- Tests for Trusted Procedures --- --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0 -SET sepgsql.debug_audit = true; -SET client_min_messages = log; -SELECT f1(); -- normal procedure -SELECT f2(); -- trusted procedure -SELECT f3(); -- trusted procedure that raises an error -SELECT f4(); -- failed on domain transition -SELECT sepgsql_getcon(); -- client's label must be restored - --- --- Test for Dynamic Domain Transition --- - --- validation of transaction aware dynamic-transition --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c25 -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c15'); -SELECT sepgsql_getcon(); - -SELECT sepgsql_setcon(NULL); -- failed to reset -SELECT sepgsql_getcon(); - -BEGIN; -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c12'); -SELECT sepgsql_getcon(); - -SAVEPOINT svpt_1; -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c9'); -SELECT sepgsql_getcon(); - -SAVEPOINT svpt_2; -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c6'); -SELECT sepgsql_getcon(); - -SAVEPOINT svpt_3; -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c3'); -SELECT sepgsql_getcon(); - -ROLLBACK TO SAVEPOINT svpt_2; -SELECT sepgsql_getcon(); -- should be 's0:c0.c9' - -ROLLBACK TO SAVEPOINT svpt_1; -SELECT sepgsql_getcon(); -- should be 's0:c0.c12' - -ABORT; -SELECT sepgsql_getcon(); -- should be 's0:c0.c15' - -BEGIN; -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c8'); -SELECT sepgsql_getcon(); - -SAVEPOINT svpt_1; -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c4'); -SELECT sepgsql_getcon(); - -ROLLBACK TO SAVEPOINT svpt_1; -SELECT sepgsql_getcon(); -- should be 's0:c0.c8' -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0:c0.c6'); - -COMMIT; -SELECT sepgsql_getcon(); -- should be 's0:c0.c6' - --- sepgsql_regtest_user_t is not available dynamic-transition, --- unless sepgsql_setcon() is called inside of trusted-procedure --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0:c0.c15 - --- sepgsql_regtest_user_t has no permission to switch current label -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0'); -- failed -SELECT sepgsql_getcon(); - --- trusted procedure allows to switch, but unavailable to override MCS rules -SELECT f5('unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0:c0.c7'); -- OK -SELECT sepgsql_getcon(); - -SELECT f5('unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0:c0.c31'); -- Failed -SELECT sepgsql_getcon(); - -SELECT f5(NULL); -- Failed -SELECT sepgsql_getcon(); - -BEGIN; -SELECT f5('unconfined_u:unconfined_r:sepgsql_regtest_user_t:s0:c0.c3'); -- OK -SELECT sepgsql_getcon(); - -ABORT; -SELECT sepgsql_getcon(); - --- --- Test for simulation of typical connection pooling server --- --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_pool_t:s0 - --- we shouldn't allow to switch client label without trusted procedure -SELECT sepgsql_setcon('unconfined_u:unconfined_r:sepgsql_regtest_foo_t:s0'); - -SELECT * FROM auth_tbl; -- failed, no permission to reference - --- switch to "foo" -SELECT auth_func('foo', 'acbd18db4cc2f85cedef654fccc4a4d8'); - -SELECT sepgsql_getcon(); - -SELECT * FROM foo_tbl; -- OK -SELECT * FROM foo_ptbl; -- OK - -SELECT * FROM var_tbl; -- failed -SELECT * FROM var_ptbl; -- failed - -SELECT * FROM auth_tbl; -- failed - -SELECT sepgsql_setcon(NULL); -- end of session -SELECT sepgsql_getcon(); - --- the pooler cannot touch these tables directly -SELECT * FROM foo_tbl; -- failed -SELECT * FROM foo_ptbl; -- failed - -SELECT * FROM var_tbl; -- failed -SELECT * FROM var_ptbl; -- failed - --- switch to "var" -SELECT auth_func('var', 'b2145aac704ce76dbe1ac7adac535b23'); - -SELECT sepgsql_getcon(); - -SELECT * FROM foo_tbl; -- failed -SELECT * FROM foo_ptbl; -- failed - -SELECT * FROM var_tbl; -- OK -SELECT * FROM var_ptbl; -- OK - -SELECT * FROM auth_tbl; -- failed - -SELECT sepgsql_setcon(NULL); -- end of session - --- misc checks -SELECT auth_func('var', 'invalid credential'); -- not works -SELECT sepgsql_getcon(); - --- --- Clean up --- --- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0-s0:c0.c255 -DROP TABLE IF EXISTS t1 CASCADE; -DROP TABLE IF EXISTS t2 CASCADE; -DROP TABLE IF EXISTS t3 CASCADE; -DROP TABLE IF EXISTS t4 CASCADE; -DROP TABLE IF EXISTS tpart CASCADE; -DROP FUNCTION IF EXISTS f1() CASCADE; -DROP FUNCTION IF EXISTS f2() CASCADE; -DROP FUNCTION IF EXISTS f3() CASCADE; -DROP FUNCTION IF EXISTS f4() CASCADE; -DROP FUNCTION IF EXISTS f5(text) CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fddl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fddl.sql deleted file mode 100644 index 4f76bed72c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fddl.sql +++ /dev/null @@ -1,439 +0,0 @@ --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); --- fail because of an already existing slot -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); --- fail because of an invalid name -SELECT 'init' FROM pg_create_logical_replication_slot('Invalid Name', 'test_decoding'); - --- fail twice because of an invalid parameter values -SELECT 'init' FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', 'frakbar'); -SELECT 'init' FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'nonexistent-option', 'frakbar'); -SELECT 'init' FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', 'frakbar'); - --- succeed once -SELECT pg_drop_replication_slot('regression_slot'); --- fail -SELECT pg_drop_replication_slot('regression_slot'); - --- check that we're detecting a streaming rep slot used for logical decoding -SELECT 'init' FROM pg_create_physical_replication_slot('repl'); -SELECT data FROM pg_logical_slot_get_changes('repl', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -SELECT pg_drop_replication_slot('repl'); - - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -/* check whether status function reports us, only reproduceable columns */ -SELECT slot_name, plugin, slot_type, active, - NOT catalog_xmin IS NULL AS catalog_xmin_set, - xmin IS NULl AS data_xmin_not_set, - pg_wal_lsn_diff(restart_lsn, '0/01000000') > 0 AS some_wal -FROM pg_replication_slots; - -/* - * Check that changes are handled correctly when interleaved with ddl - */ -CREATE TABLE replication_example(id SERIAL PRIMARY KEY, somedata int, text varchar(120)); -BEGIN; -INSERT INTO replication_example(somedata, text) VALUES (1, 1); -INSERT INTO replication_example(somedata, text) VALUES (1, 2); -COMMIT; - -ALTER TABLE replication_example ADD COLUMN bar int; - -INSERT INTO replication_example(somedata, text, bar) VALUES (2, 1, 4); - -BEGIN; -INSERT INTO replication_example(somedata, text, bar) VALUES (2, 2, 4); -INSERT INTO replication_example(somedata, text, bar) VALUES (2, 3, 4); -INSERT INTO replication_example(somedata, text, bar) VALUES (2, 4, NULL); -COMMIT; - -ALTER TABLE replication_example DROP COLUMN bar; -INSERT INTO replication_example(somedata, text) VALUES (3, 1); - -BEGIN; -INSERT INTO replication_example(somedata, text) VALUES (3, 2); -INSERT INTO replication_example(somedata, text) VALUES (3, 3); -COMMIT; - -ALTER TABLE replication_example RENAME COLUMN text TO somenum; - -INSERT INTO replication_example(somedata, somenum) VALUES (4, 1); - --- collect all changes -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -ALTER TABLE replication_example ALTER COLUMN somenum TYPE int4 USING (somenum::int4); --- check that this doesn't produce any changes from the heap rewrite -SELECT count(data) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -INSERT INTO replication_example(somedata, somenum) VALUES (5, 1); - -BEGIN; -INSERT INTO replication_example(somedata, somenum) VALUES (6, 1); -ALTER TABLE replication_example ADD COLUMN zaphod1 int; -INSERT INTO replication_example(somedata, somenum, zaphod1) VALUES (6, 2, 1); -ALTER TABLE replication_example ADD COLUMN zaphod2 int; -INSERT INTO replication_example(somedata, somenum, zaphod2) VALUES (6, 3, 1); -INSERT INTO replication_example(somedata, somenum, zaphod1) VALUES (6, 4, 2); -COMMIT; - --- show changes -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- ON CONFLICT DO UPDATE support -BEGIN; -INSERT INTO replication_example(id, somedata, somenum) SELECT i, i, i FROM generate_series(-15, 15) i - ON CONFLICT (id) DO UPDATE SET somenum = excluded.somenum + 1; -COMMIT; - -/* display results */ -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- MERGE support -BEGIN; -MERGE INTO replication_example t - USING (SELECT i as id, i as data, i as num FROM generate_series(-20, 5) i) s - ON t.id = s.id - WHEN MATCHED AND t.id < 0 THEN - UPDATE SET somenum = somenum + 1 - WHEN MATCHED AND t.id >= 0 THEN - DELETE - WHEN NOT MATCHED THEN - INSERT VALUES (s.*); -COMMIT; - -/* display results */ -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -CREATE TABLE tr_unique(id2 serial unique NOT NULL, data int); -INSERT INTO tr_unique(data) VALUES(10); -ALTER TABLE tr_unique RENAME TO tr_pkey; -ALTER TABLE tr_pkey ADD COLUMN id serial primary key; -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'include-rewrites', '1'); - -INSERT INTO tr_pkey(data) VALUES(1); ---show deletion with primary key -DELETE FROM tr_pkey; - -/* display results */ -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -/* - * check that disk spooling works (also for logical messages) - */ -BEGIN; -CREATE TABLE tr_etoomuch (id serial primary key, data int); -INSERT INTO tr_etoomuch(data) SELECT g.i FROM generate_series(1, 10234) g(i); -SELECT 'tx logical msg' FROM pg_logical_emit_message(true, 'test', 'tx logical msg'); -DELETE FROM tr_etoomuch WHERE id < 5000; -UPDATE tr_etoomuch SET data = - data WHERE id > 5000; -CREATE TABLE tr_oddlength (id text primary key, data text); -INSERT INTO tr_oddlength VALUES('ab', 'foo'); -COMMIT; - -/* display results, but hide most of the output */ -SELECT count(*), min(data), max(data) -FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1') -GROUP BY substring(data, 1, 24) -ORDER BY 1,2; - --- check updates of primary keys work correctly -BEGIN; -CREATE TABLE spoolme AS SELECT g.i FROM generate_series(1, 5000) g(i); -UPDATE tr_etoomuch SET id = -id WHERE id = 5000; -UPDATE tr_oddlength SET id = 'x', data = 'quux'; -UPDATE tr_oddlength SET id = 'yy', data = 'a'; -DELETE FROM spoolme; -DROP TABLE spoolme; -COMMIT; - -SELECT data -FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1') -WHERE data ~ 'UPDATE'; - --- check that a large, spooled, upsert works -INSERT INTO tr_etoomuch (id, data) -SELECT g.i, -g.i FROM generate_series(8000, 12000) g(i) -ON CONFLICT(id) DO UPDATE SET data = EXCLUDED.data; - -SELECT substring(data, 1, 29), count(*) -FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1') WITH ORDINALITY -GROUP BY 1 -ORDER BY min(ordinality); - -/* - * check whether we decode subtransactions correctly in relation with each - * other - */ -CREATE TABLE tr_sub (id serial primary key, path text); - --- toplevel, subtxn, toplevel, subtxn, subtxn -BEGIN; -INSERT INTO tr_sub(path) VALUES ('1-top-#1'); - -SAVEPOINT a; -INSERT INTO tr_sub(path) VALUES ('1-top-1-#1'); -INSERT INTO tr_sub(path) VALUES ('1-top-1-#2'); -RELEASE SAVEPOINT a; - -SAVEPOINT b; -SAVEPOINT c; -INSERT INTO tr_sub(path) VALUES ('1-top-2-1-#1'); -INSERT INTO tr_sub(path) VALUES ('1-top-2-1-#2'); -RELEASE SAVEPOINT c; -INSERT INTO tr_sub(path) VALUES ('1-top-2-#1'); -RELEASE SAVEPOINT b; -COMMIT; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- check that we handle xlog assignments correctly -BEGIN; --- nest 80 subtxns -SAVEPOINT subtop;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; -SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a;SAVEPOINT a; --- assign xid by inserting -INSERT INTO tr_sub(path) VALUES ('2-top-1...--#1'); -INSERT INTO tr_sub(path) VALUES ('2-top-1...--#2'); -INSERT INTO tr_sub(path) VALUES ('2-top-1...--#3'); -RELEASE SAVEPOINT subtop; -INSERT INTO tr_sub(path) VALUES ('2-top-#1'); -COMMIT; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- make sure rollbacked subtransactions aren't decoded -BEGIN; -INSERT INTO tr_sub(path) VALUES ('3-top-2-#1'); -SAVEPOINT a; -INSERT INTO tr_sub(path) VALUES ('3-top-2-1-#1'); -SAVEPOINT b; -INSERT INTO tr_sub(path) VALUES ('3-top-2-2-#1'); -ROLLBACK TO SAVEPOINT b; -INSERT INTO tr_sub(path) VALUES ('3-top-2-#2'); -COMMIT; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- test whether a known, but not yet logged toplevel xact, followed by a --- subxact commit is handled correctly -BEGIN; -SELECT pg_current_xact_id() != '0'; -- so no fixed xid apears in the outfile -SAVEPOINT a; -INSERT INTO tr_sub(path) VALUES ('4-top-1-#1'); -RELEASE SAVEPOINT a; -COMMIT; - --- test whether a change in a subtransaction, in an unknown toplevel --- xact is handled correctly. -BEGIN; -SAVEPOINT a; -INSERT INTO tr_sub(path) VALUES ('5-top-1-#1'); -COMMIT; - - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- check that DDL in aborted subtransactions handled correctly -CREATE TABLE tr_sub_ddl(data int); -BEGIN; -SAVEPOINT a; -ALTER TABLE tr_sub_ddl ALTER COLUMN data TYPE text; -INSERT INTO tr_sub_ddl VALUES ('blah-blah'); -ROLLBACK TO SAVEPOINT a; -ALTER TABLE tr_sub_ddl ALTER COLUMN data TYPE bigint; -INSERT INTO tr_sub_ddl VALUES(43); -COMMIT; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - - -/* - * Check whether treating a table as a catalog table works somewhat - */ -CREATE TABLE replication_metadata ( - id serial primary key, - relation name NOT NULL, - options text[] -) -WITH (user_catalog_table = true) -; -\d+ replication_metadata - -INSERT INTO replication_metadata(relation, options) -VALUES ('foo', ARRAY['a', 'b']); - -ALTER TABLE replication_metadata RESET (user_catalog_table); -\d+ replication_metadata - -INSERT INTO replication_metadata(relation, options) -VALUES ('bar', ARRAY['a', 'b']); - -ALTER TABLE replication_metadata SET (user_catalog_table = true); -\d+ replication_metadata - -INSERT INTO replication_metadata(relation, options) -VALUES ('blub', NULL); - --- make sure rewrites don't work -ALTER TABLE replication_metadata ADD COLUMN rewritemeornot int; -ALTER TABLE replication_metadata ALTER COLUMN rewritemeornot TYPE text; - -ALTER TABLE replication_metadata SET (user_catalog_table = false); -\d+ replication_metadata - -INSERT INTO replication_metadata(relation, options) -VALUES ('zaphod', NULL); - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -/* - * check whether we handle updates/deletes correct with & without a pkey - */ - -/* we should handle the case without a key at all more gracefully */ -CREATE TABLE table_without_key(id serial, data int); -INSERT INTO table_without_key(data) VALUES(1),(2); -DELETE FROM table_without_key WHERE data = 1; --- won't log old keys -UPDATE table_without_key SET data = 3 WHERE data = 2; -UPDATE table_without_key SET id = -id; -UPDATE table_without_key SET id = -id; --- should log the full old row now -ALTER TABLE table_without_key REPLICA IDENTITY FULL; -UPDATE table_without_key SET data = 3 WHERE data = 2; -UPDATE table_without_key SET id = -id; -UPDATE table_without_key SET id = -id; --- ensure that FULL correctly deals with new columns -ALTER TABLE table_without_key ADD COLUMN new_column text; -UPDATE table_without_key SET id = -id; -UPDATE table_without_key SET id = -id, new_column = 'someval'; -DELETE FROM table_without_key WHERE data = 3; - -CREATE TABLE table_with_pkey(id serial primary key, data int); -INSERT INTO table_with_pkey(data) VALUES(1), (2); -DELETE FROM table_with_pkey WHERE data = 1; --- should log the old pkey -UPDATE table_with_pkey SET data = 3 WHERE data = 2; -UPDATE table_with_pkey SET id = -id; -UPDATE table_with_pkey SET id = -id; --- check that we log nothing despite having a pkey -ALTER TABLE table_without_key REPLICA IDENTITY NOTHING; -UPDATE table_with_pkey SET id = -id; --- check that we log everything despite having a pkey -ALTER TABLE table_without_key REPLICA IDENTITY FULL; -UPDATE table_with_pkey SET id = -id; -DELETE FROM table_with_pkey WHERE data = 3; - -CREATE TABLE table_with_unique_not_null(id serial unique, data int); -ALTER TABLE table_with_unique_not_null ALTER COLUMN id SET NOT NULL; --already set --- won't log anything, replica identity not setup -INSERT INTO table_with_unique_not_null(data) VALUES(1), (2); -DELETE FROM table_with_unique_not_null WHERE data = 1; -UPDATE table_with_unique_not_null SET data = 3 WHERE data = 2; -UPDATE table_with_unique_not_null SET id = -id; -UPDATE table_with_unique_not_null SET id = -id; -DELETE FROM table_with_unique_not_null WHERE data = 3; --- should log old key -ALTER TABLE table_with_unique_not_null REPLICA IDENTITY USING INDEX table_with_unique_not_null_id_key; -INSERT INTO table_with_unique_not_null(data) VALUES(1), (2); -DELETE FROM table_with_unique_not_null WHERE data = 1; -UPDATE table_with_unique_not_null SET data = 3 WHERE data = 2; -UPDATE table_with_unique_not_null SET id = -id; -UPDATE table_with_unique_not_null SET id = -id; -DELETE FROM table_with_unique_not_null WHERE data = 3; - --- check tables with dropped indexes used in REPLICA IDENTITY --- table with primary key -CREATE TABLE table_dropped_index_with_pk (a int PRIMARY KEY, b int, c int); -CREATE UNIQUE INDEX table_dropped_index_with_pk_idx - ON table_dropped_index_with_pk(a); -ALTER TABLE table_dropped_index_with_pk REPLICA IDENTITY - USING INDEX table_dropped_index_with_pk_idx; -DROP INDEX table_dropped_index_with_pk_idx; -INSERT INTO table_dropped_index_with_pk VALUES (1,1,1), (2,2,2), (3,3,3); -UPDATE table_dropped_index_with_pk SET a = 4 WHERE a = 1; -UPDATE table_dropped_index_with_pk SET b = 5 WHERE a = 2; -UPDATE table_dropped_index_with_pk SET b = 6, c = 7 WHERE a = 3; -DELETE FROM table_dropped_index_with_pk WHERE b = 1; -DELETE FROM table_dropped_index_with_pk WHERE a = 3; -DROP TABLE table_dropped_index_with_pk; - --- table without primary key -CREATE TABLE table_dropped_index_no_pk (a int NOT NULL, b int, c int); -CREATE UNIQUE INDEX table_dropped_index_no_pk_idx - ON table_dropped_index_no_pk(a); -ALTER TABLE table_dropped_index_no_pk REPLICA IDENTITY - USING INDEX table_dropped_index_no_pk_idx; -DROP INDEX table_dropped_index_no_pk_idx; -INSERT INTO table_dropped_index_no_pk VALUES (1,1,1), (2,2,2), (3,3,3); -UPDATE table_dropped_index_no_pk SET a = 4 WHERE a = 1; -UPDATE table_dropped_index_no_pk SET b = 5 WHERE a = 2; -UPDATE table_dropped_index_no_pk SET b = 6, c = 7 WHERE a = 3; -DELETE FROM table_dropped_index_no_pk WHERE b = 1; -DELETE FROM table_dropped_index_no_pk WHERE a = 3; -DROP TABLE table_dropped_index_no_pk; - --- check toast support -BEGIN; -CREATE SEQUENCE toasttable_rand_seq START 79 INCREMENT 1499; -- portable "random" -CREATE TABLE toasttable( - id serial primary key, - toasted_col1 text, - rand1 float8 DEFAULT nextval('toasttable_rand_seq'), - toasted_col2 text, - rand2 float8 DEFAULT nextval('toasttable_rand_seq') - ); -COMMIT; --- uncompressed external toast data -INSERT INTO toasttable(toasted_col1) SELECT string_agg(g.i::text, '') FROM generate_series(1, 2000) g(i); - --- compressed external toast data -INSERT INTO toasttable(toasted_col2) SELECT repeat(string_agg(to_char(g.i, 'FM0000'), ''), 50) FROM generate_series(1, 500) g(i); - --- update of existing column -UPDATE toasttable - SET toasted_col1 = (SELECT string_agg(g.i::text, '') FROM generate_series(1, 2000) g(i)) -WHERE id = 1; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -INSERT INTO toasttable(toasted_col1) SELECT string_agg(g.i::text, '') FROM generate_series(1, 2000) g(i); - --- update of second column, first column unchanged -UPDATE toasttable - SET toasted_col2 = (SELECT string_agg(g.i::text, '') FROM generate_series(1, 2000) g(i)) -WHERE id = 1; - --- make sure we decode correctly even if the toast table is gone -DROP TABLE toasttable; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- done, free logical replication slot -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT pg_drop_replication_slot('regression_slot'); - -/* check that the slot is gone */ -\x -SELECT * FROM pg_replication_slots; -\x diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fdecoding_in_xact.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fdecoding_in_xact.sql deleted file mode 100644 index 108782dc2e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fdecoding_in_xact.sql +++ /dev/null @@ -1,41 +0,0 @@ --- predictability -SET synchronous_commit = on; - --- fail because we're creating a slot while in an xact with xid -BEGIN; -SELECT pg_current_xact_id() = '0'; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); -ROLLBACK; - --- fail because we're creating a slot while in a subxact whose topxact has an xid -BEGIN; -SELECT pg_current_xact_id() = '0'; -SAVEPOINT barf; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); -ROLLBACK TO SAVEPOINT barf; -ROLLBACK; - --- succeed, outside tx. -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); -SELECT 'stop' FROM pg_drop_replication_slot('regression_slot'); - --- succeed, in tx without xid. -BEGIN; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); -COMMIT; - -CREATE TABLE nobarf(id serial primary key, data text); -INSERT INTO nobarf(data) VALUES('1'); - --- decoding works in transaction with xid -BEGIN; -SELECT pg_current_xact_id() = '0'; --- don't show yet, haven't committed -INSERT INTO nobarf(data) VALUES('2'); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -COMMIT; - -INSERT INTO nobarf(data) VALUES('3'); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT 'stop' FROM pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fdecoding_into_rel.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fdecoding_into_rel.sql deleted file mode 100644 index 1068cec588..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fdecoding_into_rel.sql +++ /dev/null @@ -1,42 +0,0 @@ --- test that we can insert the result of a get_changes call into a --- logged relation. That's really not a good idea in practical terms, --- but provides a nice test. - --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - --- slot works -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- create some changes -CREATE TABLE somechange(id serial primary key); -INSERT INTO somechange DEFAULT VALUES; - -CREATE TABLE changeresult AS - SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT * FROM changeresult; - -INSERT INTO changeresult - SELECT data FROM pg_logical_slot_peek_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -INSERT INTO changeresult - SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT * FROM changeresult; -DROP TABLE changeresult; -DROP TABLE somechange; - --- check calling logical decoding from pl/pgsql -CREATE FUNCTION slot_changes_wrapper(slot_name name) RETURNS SETOF TEXT AS $$ -BEGIN - RETURN QUERY - SELECT data FROM pg_logical_slot_peek_changes(slot_name, NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -END$$ LANGUAGE plpgsql; - -SELECT * FROM slot_changes_wrapper('regression_slot'); - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT 'stop' FROM pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fmessages.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fmessages.sql deleted file mode 100644 index cf3f7738e5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fmessages.sql +++ /dev/null @@ -1,34 +0,0 @@ --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -SELECT 'msg1' FROM pg_logical_emit_message(true, 'test', 'msg1'); -SELECT 'msg2' FROM pg_logical_emit_message(false, 'test', 'msg2'); - -BEGIN; -SELECT 'msg3' FROM pg_logical_emit_message(true, 'test', 'msg3'); -SELECT 'msg4' FROM pg_logical_emit_message(false, 'test', 'msg4'); -ROLLBACK; - -BEGIN; -SELECT 'msg5' FROM pg_logical_emit_message(true, 'test', 'msg5'); -SELECT 'msg6' FROM pg_logical_emit_message(false, 'test', 'msg6'); -SELECT 'msg7' FROM pg_logical_emit_message(true, 'test', 'msg7'); -COMMIT; - -SELECT 'ignorethis' FROM pg_logical_emit_message(true, 'test', 'czechtastic'); - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'force-binary', '0', 'skip-empty-xacts', '1'); - --- test db filtering -\set prevdb :DBNAME -\c template1 - -SELECT 'otherdb1' FROM pg_logical_emit_message(false, 'test', 'otherdb1'); -SELECT 'otherdb2' FROM pg_logical_emit_message(true, 'test', 'otherdb2'); - -\c :prevdb -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'force-binary', '0', 'skip-empty-xacts', '1'); - -SELECT 'cleanup' FROM pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fprepared.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fprepared.sql deleted file mode 100644 index e72639767e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fprepared.sql +++ /dev/null @@ -1,50 +0,0 @@ --- predictability -SET synchronous_commit = on; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -CREATE TABLE test_prepared1(id int); -CREATE TABLE test_prepared2(id int); - --- test simple successful use of a prepared xact -BEGIN; -INSERT INTO test_prepared1 VALUES (1); -PREPARE TRANSACTION 'test_prepared#1'; -COMMIT PREPARED 'test_prepared#1'; -INSERT INTO test_prepared1 VALUES (2); - --- test abort of a prepared xact -BEGIN; -INSERT INTO test_prepared1 VALUES (3); -PREPARE TRANSACTION 'test_prepared#2'; -ROLLBACK PREPARED 'test_prepared#2'; - -INSERT INTO test_prepared1 VALUES (4); - --- test prepared xact containing ddl -BEGIN; -INSERT INTO test_prepared1 VALUES (5); -ALTER TABLE test_prepared1 ADD COLUMN data text; -INSERT INTO test_prepared1 VALUES (6, 'frakbar'); -PREPARE TRANSACTION 'test_prepared#3'; - --- test that we decode correctly while an uncommitted prepared xact --- with ddl exists. - --- separate table because of the lock from the ALTER --- this will come before the '5' row above, as this commits before it. -INSERT INTO test_prepared2 VALUES (7); - -COMMIT PREPARED 'test_prepared#3'; - --- make sure stuff still works -INSERT INTO test_prepared1 VALUES (8); -INSERT INTO test_prepared2 VALUES (9); - --- cleanup -DROP TABLE test_prepared1; -DROP TABLE test_prepared2; - --- show results -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Freplorigin.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Freplorigin.sql deleted file mode 100644 index 2e28a48777..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Freplorigin.sql +++ /dev/null @@ -1,121 +0,0 @@ --- predictability -SET synchronous_commit = on; - --- superuser required by default -CREATE ROLE regress_origin_replication REPLICATION; -SET ROLE regress_origin_replication; -SELECT pg_replication_origin_advance('regress_test_decoding: perm', '0/1'); -SELECT pg_replication_origin_create('regress_test_decoding: perm'); -SELECT pg_replication_origin_drop('regress_test_decoding: perm'); -SELECT pg_replication_origin_oid('regress_test_decoding: perm'); -SELECT pg_replication_origin_progress('regress_test_decoding: perm', false); -SELECT pg_replication_origin_session_is_setup(); -SELECT pg_replication_origin_session_progress(false); -SELECT pg_replication_origin_session_reset(); -SELECT pg_replication_origin_session_setup('regress_test_decoding: perm'); -SELECT pg_replication_origin_xact_reset(); -SELECT pg_replication_origin_xact_setup('0/1', '2013-01-01 00:00'); -SELECT pg_show_replication_origin_status(); -RESET ROLE; -DROP ROLE regress_origin_replication; - -CREATE TABLE origin_tbl(id serial primary key, data text); -CREATE TABLE target_tbl(id serial primary key, data text); - -SELECT pg_replication_origin_create('regress_test_decoding: regression_slot'); --- ensure duplicate creations fail -SELECT pg_replication_origin_create('regress_test_decoding: regression_slot'); - ---ensure deletions work (once) -SELECT pg_replication_origin_create('regress_test_decoding: temp'); -SELECT pg_replication_origin_drop('regress_test_decoding: temp'); -SELECT pg_replication_origin_drop('regress_test_decoding: temp'); - --- various failure checks for undefined slots -select pg_replication_origin_advance('regress_test_decoding: temp', '0/1'); -select pg_replication_origin_session_setup('regress_test_decoding: temp'); -select pg_replication_origin_progress('regress_test_decoding: temp', true); - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - --- origin tx -INSERT INTO origin_tbl(data) VALUES ('will be replicated and decoded and decoded again'); -INSERT INTO target_tbl(data) -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- as is normal, the insert into target_tbl shows up -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -INSERT INTO origin_tbl(data) VALUES ('will be replicated, but not decoded again'); - --- mark session as replaying -SELECT pg_replication_origin_session_setup('regress_test_decoding: regression_slot'); - --- ensure we prevent duplicate setup -SELECT pg_replication_origin_session_setup('regress_test_decoding: regression_slot'); - -SELECT '' FROM pg_logical_emit_message(false, 'test', 'this message will not be decoded'); - -BEGIN; --- setup transaction origin -SELECT pg_replication_origin_xact_setup('0/aabbccdd', '2013-01-01 00:00'); -INSERT INTO target_tbl(data) -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'only-local', '1'); -COMMIT; - --- check replication progress for the session is correct -SELECT pg_replication_origin_session_progress(false); -SELECT pg_replication_origin_session_progress(true); - -SELECT pg_replication_origin_session_reset(); - -SELECT local_id, external_id, remote_lsn, local_lsn <> '0/0' FROM pg_replication_origin_status; - --- check replication progress identified by name is correct -SELECT pg_replication_origin_progress('regress_test_decoding: regression_slot', false); -SELECT pg_replication_origin_progress('regress_test_decoding: regression_slot', true); - --- ensure reset requires previously setup state -SELECT pg_replication_origin_session_reset(); - --- and magically the replayed xact will be filtered! -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'only-local', '1'); - ---but new original changes still show up -INSERT INTO origin_tbl(data) VALUES ('will be replicated'); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'only-local', '1'); - -SELECT pg_drop_replication_slot('regression_slot'); -SELECT pg_replication_origin_drop('regress_test_decoding: regression_slot'); - --- Set of transactions with no origin LSNs and commit timestamps set for --- this session. -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot_no_lsn', 'test_decoding'); -SELECT pg_replication_origin_create('regress_test_decoding: regression_slot_no_lsn'); --- mark session as replaying -SELECT pg_replication_origin_session_setup('regress_test_decoding: regression_slot_no_lsn'); --- Simple transactions -BEGIN; -INSERT INTO origin_tbl(data) VALUES ('no_lsn, commit'); -COMMIT; -BEGIN; -INSERT INTO origin_tbl(data) VALUES ('no_lsn, rollback'); -ROLLBACK; --- 2PC transactions -BEGIN; -INSERT INTO origin_tbl(data) VALUES ('no_lsn, commit prepared'); -PREPARE TRANSACTION 'replorigin_prepared'; -COMMIT PREPARED 'replorigin_prepared'; -BEGIN; -INSERT INTO origin_tbl(data) VALUES ('no_lsn, rollback prepared'); -PREPARE TRANSACTION 'replorigin_prepared'; -ROLLBACK PREPARED 'replorigin_prepared'; -SELECT local_id, external_id, - remote_lsn <> '0/0' AS valid_remote_lsn, - local_lsn <> '0/0' AS valid_local_lsn - FROM pg_replication_origin_status; -SELECT data FROM pg_logical_slot_get_changes('regression_slot_no_lsn', NULL, NULL, 'skip-empty-xacts', '1', 'include-xids', '0'); --- Clean up -SELECT pg_replication_origin_session_reset(); -SELECT pg_drop_replication_slot('regression_slot_no_lsn'); -SELECT pg_replication_origin_drop('regress_test_decoding: regression_slot_no_lsn'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Frewrite.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Frewrite.sql deleted file mode 100644 index 62dead3a9b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Frewrite.sql +++ /dev/null @@ -1,107 +0,0 @@ --- predictability -SET synchronous_commit = on; - -DROP TABLE IF EXISTS replication_example; - --- Ensure there's tables with toast datums. To do so, we dynamically --- create a function returning a large textblob. We want tables of --- different kinds: mapped catalog table, unmapped catalog table, --- shared catalog table and usertable. -CREATE FUNCTION exec(text) returns void language plpgsql volatile - AS $f$ - BEGIN - EXECUTE $1; - END; -$f$; -CREATE ROLE regress_justforcomments NOLOGIN; - -SELECT exec( - format($outer$CREATE FUNCTION iamalongfunction() RETURNS TEXT IMMUTABLE LANGUAGE SQL AS $f$SELECT text %L$f$$outer$, - (SELECT repeat(string_agg(to_char(g.i, 'FM0000'), ''), 50) FROM generate_series(1, 500) g(i)))); -SELECT exec( - format($outer$COMMENT ON FUNCTION iamalongfunction() IS %L$outer$, - iamalongfunction())); -SELECT exec( - format($outer$COMMENT ON ROLE REGRESS_JUSTFORCOMMENTS IS %L$outer$, - iamalongfunction())); -CREATE TABLE iamalargetable AS SELECT iamalongfunction() longfunctionoutput; - --- verify toast usage -SELECT pg_relation_size((SELECT reltoastrelid FROM pg_class WHERE oid = 'pg_proc'::regclass)) > 0; -SELECT pg_relation_size((SELECT reltoastrelid FROM pg_class WHERE oid = 'pg_description'::regclass)) > 0; -SELECT pg_relation_size((SELECT reltoastrelid FROM pg_class WHERE oid = 'pg_shdescription'::regclass)) > 0; - - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); -CREATE TABLE replication_example(id SERIAL PRIMARY KEY, somedata int, text varchar(120)); -INSERT INTO replication_example(somedata) VALUES (1); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -BEGIN; -INSERT INTO replication_example(somedata) VALUES (2); -ALTER TABLE replication_example ADD COLUMN testcolumn1 int; -INSERT INTO replication_example(somedata, testcolumn1) VALUES (3, 1); -COMMIT; - -BEGIN; -INSERT INTO replication_example(somedata) VALUES (3); -ALTER TABLE replication_example ADD COLUMN testcolumn2 int; -INSERT INTO replication_example(somedata, testcolumn1, testcolumn2) VALUES (4, 2, 1); -COMMIT; - -VACUUM FULL pg_am; -VACUUM FULL pg_amop; -VACUUM FULL pg_proc; -VACUUM FULL pg_opclass; -VACUUM FULL pg_type; -VACUUM FULL pg_index; -VACUUM FULL pg_database; - --- repeated rewrites that fail -BEGIN; -CLUSTER pg_class USING pg_class_oid_index; -CLUSTER pg_class USING pg_class_oid_index; -ROLLBACK; - --- repeated rewrites that succeed -BEGIN; -CLUSTER pg_class USING pg_class_oid_index; -CLUSTER pg_class USING pg_class_oid_index; -CLUSTER pg_class USING pg_class_oid_index; -COMMIT; - - -- repeated rewrites in different transactions -VACUUM FULL pg_class; -VACUUM FULL pg_class; - --- reindexing of important relations / indexes -REINDEX TABLE pg_class; -REINDEX INDEX pg_class_oid_index; -REINDEX INDEX pg_class_tblspc_relfilenode_index; - -INSERT INTO replication_example(somedata, testcolumn1) VALUES (5, 3); - -BEGIN; -INSERT INTO replication_example(somedata, testcolumn1) VALUES (6, 4); -ALTER TABLE replication_example ADD COLUMN testcolumn3 int; -INSERT INTO replication_example(somedata, testcolumn1, testcolumn3) VALUES (7, 5, 1); -COMMIT; - --- make old files go away -CHECKPOINT; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- trigger repeated rewrites of a system catalog with a toast table, --- that previously was buggy: 20180914021046.oi7dm4ra3ot2g2kt@alap3.anarazel.de -VACUUM FULL pg_proc; VACUUM FULL pg_description; VACUUM FULL pg_shdescription; VACUUM FULL iamalargetable; -INSERT INTO replication_example(somedata, testcolumn1, testcolumn3) VALUES (8, 6, 1); -VACUUM FULL pg_proc; VACUUM FULL pg_description; VACUUM FULL pg_shdescription; VACUUM FULL iamalargetable; -INSERT INTO replication_example(somedata, testcolumn1, testcolumn3) VALUES (9, 7, 1); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT pg_drop_replication_slot('regression_slot'); -DROP TABLE IF EXISTS replication_example; -DROP FUNCTION iamalongfunction(); -DROP FUNCTION exec(text); -DROP ROLE regress_justforcomments; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fslot.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fslot.sql deleted file mode 100644 index 1aa27c5667..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fslot.sql +++ /dev/null @@ -1,178 +0,0 @@ --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot_p', 'test_decoding'); -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot_t', 'test_decoding', true); - -SELECT pg_drop_replication_slot('regression_slot_p'); -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot_p', 'test_decoding', false); - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot_t2', 'test_decoding', true); - -SELECT pg_create_logical_replication_slot('foo', 'nonexistent'); - --- here we want to start a new session and wait till old one is gone -select pg_backend_pid() as oldpid \gset -\c - -SET synchronous_commit = on; - -do 'declare c int = 0; -begin - while (select count(*) from pg_replication_slots where active_pid = ' - :'oldpid' - ') > 0 loop c := c + 1; perform pg_sleep(0.01); end loop; - raise log ''slot test looped % times'', c; -end'; - --- should fail because the temporary slots were dropped automatically -SELECT pg_drop_replication_slot('regression_slot_t'); -SELECT pg_drop_replication_slot('regression_slot_t2'); - --- monitoring functions for slot directories -SELECT count(*) >= 0 AS ok FROM pg_ls_logicalmapdir(); -SELECT count(*) >= 0 AS ok FROM pg_ls_logicalsnapdir(); -SELECT count(*) >= 0 AS ok FROM pg_ls_replslotdir('regression_slot_p'); -SELECT count(*) >= 0 AS ok FROM pg_ls_replslotdir('not_existing_slot'); -- fails - --- permanent slot has survived -SELECT pg_drop_replication_slot('regression_slot_p'); - --- test switching between slots in a session -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot1', 'test_decoding', true); - -CREATE TABLE replication_example(id SERIAL PRIMARY KEY, somedata int, text varchar(120)); -BEGIN; -INSERT INTO replication_example(somedata, text) VALUES (1, 1); -INSERT INTO replication_example(somedata, text) VALUES (1, 2); -COMMIT; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot2', 'test_decoding', true); - -INSERT INTO replication_example(somedata, text) VALUES (1, 3); - -SELECT data FROM pg_logical_slot_get_changes('regression_slot1', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -SELECT data FROM pg_logical_slot_get_changes('regression_slot2', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -INSERT INTO replication_example(somedata, text) VALUES (1, 4); -INSERT INTO replication_example(somedata, text) VALUES (1, 5); - -SELECT pg_current_wal_lsn() AS wal_lsn \gset - -INSERT INTO replication_example(somedata, text) VALUES (1, 6); - -SELECT end_lsn FROM pg_replication_slot_advance('regression_slot1', :'wal_lsn') \gset -SELECT slot_name FROM pg_replication_slot_advance('regression_slot2', pg_current_wal_lsn()); - -SELECT :'wal_lsn' = :'end_lsn'; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot1', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -SELECT data FROM pg_logical_slot_get_changes('regression_slot2', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -DROP TABLE replication_example; - --- error -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot1', 'test_decoding', true); - --- both should error as they should be dropped on error -SELECT pg_drop_replication_slot('regression_slot1'); -SELECT pg_drop_replication_slot('regression_slot2'); - --- slot advance with physical slot, error with non-reserved slot -SELECT slot_name FROM pg_create_physical_replication_slot('regression_slot3'); -SELECT pg_replication_slot_advance('regression_slot3', '0/0'); -- invalid LSN -SELECT pg_replication_slot_advance('regression_slot3', '0/1'); -- error -SELECT pg_drop_replication_slot('regression_slot3'); - --- --- Test copy functions for logical replication slots --- - --- Create and copy logical slots -SELECT 'init' FROM pg_create_logical_replication_slot('orig_slot1', 'test_decoding', false); -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot1', 'copied_slot1_no_change'); -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot1', 'copied_slot1_change_plugin', false, 'pgoutput'); -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot1', 'copied_slot1_change_plugin_temp', true, 'pgoutput'); - --- Check all copied slots status -SELECT - o.slot_name, o.plugin, o.temporary, c.slot_name, c.plugin, c.temporary -FROM - (SELECT * FROM pg_replication_slots WHERE slot_name LIKE 'orig%') as o - LEFT JOIN pg_replication_slots as c ON o.restart_lsn = c.restart_lsn AND o.confirmed_flush_lsn = c.confirmed_flush_lsn -WHERE - o.slot_name != c.slot_name -ORDER BY o.slot_name, c.slot_name; - --- Now we have maximum 4 replication slots. Check slots are properly --- released even when raise error during creating the target slot. -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot1', 'failed'); -- error - --- temporary slots were dropped automatically -SELECT pg_drop_replication_slot('orig_slot1'); -SELECT pg_drop_replication_slot('copied_slot1_no_change'); -SELECT pg_drop_replication_slot('copied_slot1_change_plugin'); - --- Test based on the temporary logical slot -SELECT 'init' FROM pg_create_logical_replication_slot('orig_slot2', 'test_decoding', true); -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot2', 'copied_slot2_no_change'); -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot2', 'copied_slot2_change_plugin', true, 'pgoutput'); -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot2', 'copied_slot2_change_plugin_temp', false, 'pgoutput'); - --- Check all copied slots status -SELECT - o.slot_name, o.plugin, o.temporary, c.slot_name, c.plugin, c.temporary -FROM - (SELECT * FROM pg_replication_slots WHERE slot_name LIKE 'orig%') as o - LEFT JOIN pg_replication_slots as c ON o.restart_lsn = c.restart_lsn AND o.confirmed_flush_lsn = c.confirmed_flush_lsn -WHERE - o.slot_name != c.slot_name -ORDER BY o.slot_name, c.slot_name; - --- Cannot copy a logical slot to a physical slot -SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot2', 'failed'); -- error - --- temporary slots were dropped automatically -SELECT pg_drop_replication_slot('copied_slot2_change_plugin_temp'); - --- --- Test copy functions for physical replication slots --- - --- Create and copy physical slots -SELECT 'init' FROM pg_create_physical_replication_slot('orig_slot1', true); -SELECT 'init' FROM pg_create_physical_replication_slot('orig_slot2', false); -SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot1', 'copied_slot1_no_change'); -SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot1', 'copied_slot1_temp', true); - --- Check all copied slots status. Since all slots don't reserve WAL we check only other fields. -SELECT slot_name, slot_type, temporary FROM pg_replication_slots; - --- Cannot copy a physical slot to a logical slot -SELECT 'copy' FROM pg_copy_logical_replication_slot('orig_slot1', 'failed'); -- error - --- Cannot copy a physical slot that doesn't reserve WAL -SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot2', 'failed'); -- error - --- temporary slots were dropped automatically -SELECT pg_drop_replication_slot('orig_slot1'); -SELECT pg_drop_replication_slot('orig_slot2'); -SELECT pg_drop_replication_slot('copied_slot1_no_change'); - --- Test based on the temporary physical slot -SELECT 'init' FROM pg_create_physical_replication_slot('orig_slot2', true, true); -SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot2', 'copied_slot2_no_change'); -SELECT 'copy' FROM pg_copy_physical_replication_slot('orig_slot2', 'copied_slot2_notemp', false); - --- Check all copied slots status -SELECT - o.slot_name, o.temporary, c.slot_name, c.temporary -FROM - (SELECT * FROM pg_replication_slots WHERE slot_name LIKE 'orig%') as o - LEFT JOIN pg_replication_slots as c ON o.restart_lsn = c.restart_lsn -WHERE - o.slot_name != c.slot_name -ORDER BY o.slot_name, c.slot_name; - -SELECT pg_drop_replication_slot('orig_slot2'); -SELECT pg_drop_replication_slot('copied_slot2_no_change'); -SELECT pg_drop_replication_slot('copied_slot2_notemp'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fspill.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fspill.sql deleted file mode 100644 index e638cacd3f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fspill.sql +++ /dev/null @@ -1,179 +0,0 @@ --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -CREATE TABLE spill_test(data text); - --- consume DDL -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- spilling main xact -BEGIN; -INSERT INTO spill_test SELECT 'serialize-topbig--1:'||g.i FROM generate_series(1, 5000) g(i); -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, nothing in main -BEGIN; -SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig--1:'||g.i FROM generate_series(1, 5000) g(i); -RELEASE SAVEPOINT s; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, spilling main xact -BEGIN; -SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig-topbig--1:'||g.i FROM generate_series(1, 5000) g(i); -RELEASE SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig-topbig--2:'||g.i FROM generate_series(5001, 10000) g(i); -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, non-spilling main xact -BEGIN; -SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig-topsmall--1:'||g.i FROM generate_series(1, 5000) g(i); -RELEASE SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig-topsmall--2:'||g.i FROM generate_series(5001, 5001) g(i); -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- not-spilling subxact, spilling main xact -BEGIN; -SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig-topbig--1:'||g.i FROM generate_series(1, 5000) g(i); -RELEASE SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-subbig-topbig--2:'||g.i FROM generate_series(5001, 10000) g(i); -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling main xact, spilling subxact -BEGIN; -INSERT INTO spill_test SELECT 'serialize-topbig-subbig--1:'||g.i FROM generate_series(1, 5000) g(i); -SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-topbig-subbig--2:'||g.i FROM generate_series(5001, 10000) g(i); -RELEASE SAVEPOINT s; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling main xact, not spilling subxact -BEGIN; -INSERT INTO spill_test SELECT 'serialize-topbig-subsmall--1:'||g.i FROM generate_series(1, 5000) g(i); -SAVEPOINT s; -INSERT INTO spill_test SELECT 'serialize-topbig-subsmall--2:'||g.i FROM generate_series(5001, 5001) g(i); -RELEASE SAVEPOINT s; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, followed by another spilling subxact -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-subbig-subbig--1:'||g.i FROM generate_series(1, 5000) g(i); -RELEASE SAVEPOINT s1; -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-subbig-subbig--2:'||g.i FROM generate_series(5001, 10000) g(i); -RELEASE SAVEPOINT s2; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, followed by not spilling subxact -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-subbig-subsmall--1:'||g.i FROM generate_series(1, 5000) g(i); -RELEASE SAVEPOINT s1; -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-subbig-subsmall--2:'||g.i FROM generate_series(5001, 5001) g(i); -RELEASE SAVEPOINT s2; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4], COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- not spilling subxact, followed by spilling subxact -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-subsmall-subbig--1:'||g.i FROM generate_series(1, 1) g(i); -RELEASE SAVEPOINT s1; -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-subsmall-subbig--2:'||g.i FROM generate_series(2, 5001) g(i); -RELEASE SAVEPOINT s2; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4] COLLATE "C", COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, containing another spilling subxact -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subbig--1:'||g.i FROM generate_series(1, 5000) g(i); -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subbig--2:'||g.i FROM generate_series(5001, 10000) g(i); -RELEASE SAVEPOINT s2; -RELEASE SAVEPOINT s1; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4] COLLATE "C", COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- spilling subxact, containing a not spilling subxact -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subsmall--1:'||g.i FROM generate_series(1, 5000) g(i); -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subsmall--2:'||g.i FROM generate_series(5001, 5001) g(i); -RELEASE SAVEPOINT s2; -RELEASE SAVEPOINT s1; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4] COLLATE "C", COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- not spilling subxact, containing a spilling subxact -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-nested-subsmall-subbig--1:'||g.i FROM generate_series(1, 1) g(i); -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-nested-subsmall-subbig--2:'||g.i FROM generate_series(2, 5001) g(i); -RELEASE SAVEPOINT s2; -RELEASE SAVEPOINT s1; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4] COLLATE "C", COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - --- not spilling subxact, containing a spilling subxact that aborts and one that commits -BEGIN; -SAVEPOINT s1; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subbigabort--1:'||g.i FROM generate_series(1, 5000) g(i); -SAVEPOINT s2; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subbigabort--2:'||g.i FROM generate_series(5001, 10000) g(i); -ROLLBACK TO SAVEPOINT s2; -SAVEPOINT s3; -INSERT INTO spill_test SELECT 'serialize-nested-subbig-subbigabort-subbig-3:'||g.i FROM generate_series(5001, 10000) g(i); -RELEASE SAVEPOINT s1; -COMMIT; -SELECT (regexp_split_to_array(data, ':'))[4] COLLATE "C", COUNT(*), (array_agg(data))[1], (array_agg(data))[count(*)] -FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL) WHERE data ~ 'INSERT' -GROUP BY 1 ORDER BY 1; - -DROP TABLE spill_test; - -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fstats.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fstats.sql deleted file mode 100644 index 630371f147..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fstats.sql +++ /dev/null @@ -1,56 +0,0 @@ --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM - pg_create_logical_replication_slot('regression_slot_stats1', 'test_decoding') s1, - pg_create_logical_replication_slot('regression_slot_stats2', 'test_decoding') s2, - pg_create_logical_replication_slot('regression_slot_stats3', 'test_decoding') s3; - -CREATE TABLE stats_test(data text); - --- non-spilled xact -SET logical_decoding_work_mem to '64MB'; -INSERT INTO stats_test values(1); -SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot_stats1', NULL, NULL, 'skip-empty-xacts', '1'); -SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot_stats2', NULL, NULL, 'skip-empty-xacts', '1'); -SELECT count(*) FROM pg_logical_slot_get_changes('regression_slot_stats3', NULL, NULL, 'skip-empty-xacts', '1'); -SELECT pg_stat_force_next_flush(); -SELECT slot_name, spill_txns = 0 AS spill_txns, spill_count = 0 AS spill_count, total_txns > 0 AS total_txns, total_bytes > 0 AS total_bytes FROM pg_stat_replication_slots ORDER BY slot_name; -RESET logical_decoding_work_mem; - --- reset stats for one slot, others should be unaffected -SELECT pg_stat_reset_replication_slot('regression_slot_stats1'); -SELECT slot_name, spill_txns = 0 AS spill_txns, spill_count = 0 AS spill_count, total_txns > 0 AS total_txns, total_bytes > 0 AS total_bytes FROM pg_stat_replication_slots ORDER BY slot_name; - --- reset stats for all slots -SELECT pg_stat_reset_replication_slot(NULL); -SELECT slot_name, spill_txns = 0 AS spill_txns, spill_count = 0 AS spill_count, total_txns > 0 AS total_txns, total_bytes > 0 AS total_bytes FROM pg_stat_replication_slots ORDER BY slot_name; - --- verify accessing/resetting stats for non-existent slot does something reasonable -SELECT * FROM pg_stat_get_replication_slot('do-not-exist'); -SELECT pg_stat_reset_replication_slot('do-not-exist'); -SELECT * FROM pg_stat_get_replication_slot('do-not-exist'); - --- spilling the xact -BEGIN; -INSERT INTO stats_test SELECT 'serialize-topbig--1:'||g.i FROM generate_series(1, 5000) g(i); -COMMIT; -SELECT count(*) FROM pg_logical_slot_peek_changes('regression_slot_stats1', NULL, NULL, 'skip-empty-xacts', '1'); - --- Check stats. We can't test the exact stats count as that can vary if any --- background transaction (say by autovacuum) happens in parallel to the main --- transaction. -SELECT pg_stat_force_next_flush(); -SELECT slot_name, spill_txns > 0 AS spill_txns, spill_count > 0 AS spill_count FROM pg_stat_replication_slots; - --- Ensure stats can be repeatedly accessed using the same stats snapshot. See --- https://postgr.es/m/20210317230447.c7uc4g3vbs4wi32i%40alap3.anarazel.de -BEGIN; -SELECT slot_name FROM pg_stat_replication_slots; -SELECT slot_name FROM pg_stat_replication_slots; -COMMIT; - -DROP TABLE stats_test; -SELECT pg_drop_replication_slot('regression_slot_stats1'), - pg_drop_replication_slot('regression_slot_stats2'), - pg_drop_replication_slot('regression_slot_stats3'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fstream.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fstream.sql deleted file mode 100644 index 4feec62972..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fstream.sql +++ /dev/null @@ -1,48 +0,0 @@ -SET synchronous_commit = on; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -CREATE TABLE stream_test(data text); - --- consume DDL -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- streaming test with sub-transaction -BEGIN; -savepoint s1; -SELECT 'msg5' FROM pg_logical_emit_message(true, 'test', repeat('a', 50)); -INSERT INTO stream_test SELECT repeat('a', 2000) || g.i FROM generate_series(1, 35) g(i); -TRUNCATE table stream_test; -rollback to s1; -INSERT INTO stream_test SELECT repeat('a', 10) || g.i FROM generate_series(1, 20) g(i); -COMMIT; - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - --- streaming test for toast changes -ALTER TABLE stream_test ALTER COLUMN data set storage external; --- consume DDL -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -INSERT INTO stream_test SELECT repeat('a', 6000) || g.i FROM generate_series(1, 10) g(i); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - --- streaming test for toast with multi-insert -\COPY stream_test FROM STDIN -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -toasted-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -\. - -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - -DROP TABLE stream_test; -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftoast.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftoast.sql deleted file mode 100644 index d1c560a174..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftoast.sql +++ /dev/null @@ -1,327 +0,0 @@ --- predictability -SET synchronous_commit = on; - -DROP TABLE IF EXISTS xpto; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -CREATE SEQUENCE xpto_rand_seq START 79 INCREMENT 1499; -- portable "random" -CREATE TABLE xpto ( - id serial primary key, - toasted_col1 text, - rand1 float8 DEFAULT nextval('xpto_rand_seq'), - toasted_col2 text, - rand2 float8 DEFAULT nextval('xpto_rand_seq') -); - --- uncompressed external toast data -INSERT INTO xpto (toasted_col1, toasted_col2) SELECT string_agg(g.i::text, ''), string_agg((g.i*2)::text, '') FROM generate_series(1, 2000) g(i); - --- compressed external toast data -INSERT INTO xpto (toasted_col2) SELECT repeat(string_agg(to_char(g.i, 'FM0000'), ''), 50) FROM generate_series(1, 500) g(i); - --- update of existing column -UPDATE xpto SET toasted_col1 = (SELECT string_agg(g.i::text, '') FROM generate_series(1, 2000) g(i)) WHERE id = 1; - -UPDATE xpto SET rand1 = 123.456 WHERE id = 1; - --- updating external via INSERT ... ON CONFLICT DO UPDATE -INSERT INTO xpto(id, toasted_col2) VALUES (2, 'toasted2-upsert') -ON CONFLICT (id) -DO UPDATE SET toasted_col2 = EXCLUDED.toasted_col2 || xpto.toasted_col2; - -DELETE FROM xpto WHERE id = 1; - -DROP TABLE IF EXISTS toasted_key; -CREATE TABLE toasted_key ( - id serial, - toasted_key text PRIMARY KEY, - toasted_col1 text, - toasted_col2 text -); - -ALTER TABLE toasted_key ALTER COLUMN toasted_key SET STORAGE EXTERNAL; -ALTER TABLE toasted_key ALTER COLUMN toasted_col1 SET STORAGE EXTERNAL; - -INSERT INTO toasted_key(toasted_key, toasted_col1) VALUES(repeat('1234567890', 200), repeat('9876543210', 200)); - --- test update of a toasted key without changing it -UPDATE toasted_key SET toasted_col2 = toasted_col1; --- test update of a toasted key, changing it -UPDATE toasted_key SET toasted_key = toasted_key || '1'; - -DELETE FROM toasted_key; - --- Test that HEAP2_MULTI_INSERT insertions with and without toasted --- columns are handled correctly -CREATE TABLE toasted_copy ( - id int primary key, -- no default, copy didn't use to handle that with multi inserts - data text -); -ALTER TABLE toasted_copy ALTER COLUMN data SET STORAGE EXTERNAL; -\copy toasted_copy FROM STDIN -1 untoasted1 -2 toasted1-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -3 untoasted2 -4 toasted2-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -5 untoasted3 -6 untoasted4 -7 untoasted5 -8 untoasted6 -9 untoasted7 -10 untoasted8 -11 untoasted9 -12 untoasted10 -13 untoasted11 -14 untoasted12 -15 untoasted13 -16 untoasted14 -17 untoasted15 -18 untoasted16 -19 untoasted17 -20 untoasted18 -21 untoasted19 -22 untoasted20 -23 untoasted21 -24 untoasted22 -25 untoasted23 -26 untoasted24 -27 untoasted25 -28 untoasted26 -29 untoasted27 -30 untoasted28 -31 untoasted29 -32 untoasted30 -33 untoasted31 -34 untoasted32 -35 untoasted33 -36 untoasted34 -37 untoasted35 -38 untoasted36 -39 untoasted37 -40 untoasted38 -41 untoasted39 -42 untoasted40 -43 untoasted41 -44 untoasted42 -45 untoasted43 -46 untoasted44 -47 untoasted45 -48 untoasted46 -49 untoasted47 -50 untoasted48 -51 untoasted49 -52 untoasted50 -53 untoasted51 -54 untoasted52 -55 untoasted53 -56 untoasted54 -57 untoasted55 -58 untoasted56 -59 untoasted57 -60 untoasted58 -61 untoasted59 -62 untoasted60 -63 untoasted61 -64 untoasted62 -65 untoasted63 -66 untoasted64 -67 untoasted65 -68 untoasted66 -69 untoasted67 -70 untoasted68 -71 untoasted69 -72 untoasted70 -73 untoasted71 -74 untoasted72 -75 untoasted73 -76 untoasted74 -77 untoasted75 -78 untoasted76 -79 untoasted77 -80 untoasted78 -81 untoasted79 -82 untoasted80 -83 untoasted81 -84 untoasted82 -85 untoasted83 -86 untoasted84 -87 untoasted85 -88 untoasted86 -89 untoasted87 -90 untoasted88 -91 untoasted89 -92 untoasted90 -93 untoasted91 -94 untoasted92 -95 untoasted93 -96 untoasted94 -97 untoasted95 -98 untoasted96 -99 untoasted97 -100 untoasted98 -101 untoasted99 -102 untoasted100 -103 untoasted101 -104 untoasted102 -105 untoasted103 -106 untoasted104 -107 untoasted105 -108 untoasted106 -109 untoasted107 -110 untoasted108 -111 untoasted109 -112 untoasted110 -113 untoasted111 -114 untoasted112 -115 untoasted113 -116 untoasted114 -117 untoasted115 -118 untoasted116 -119 untoasted117 -120 untoasted118 -121 untoasted119 -122 untoasted120 -123 untoasted121 -124 untoasted122 -125 untoasted123 -126 untoasted124 -127 untoasted125 -128 untoasted126 -129 untoasted127 -130 untoasted128 -131 untoasted129 -132 untoasted130 -133 untoasted131 -134 untoasted132 -135 untoasted133 -136 untoasted134 -137 untoasted135 -138 untoasted136 -139 untoasted137 -140 untoasted138 -141 untoasted139 -142 untoasted140 -143 untoasted141 -144 untoasted142 -145 untoasted143 -146 untoasted144 -147 untoasted145 -148 untoasted146 -149 untoasted147 -150 untoasted148 -151 untoasted149 -152 untoasted150 -153 untoasted151 -154 untoasted152 -155 untoasted153 -156 untoasted154 -157 untoasted155 -158 untoasted156 -159 untoasted157 -160 untoasted158 -161 untoasted159 -162 untoasted160 -163 untoasted161 -164 untoasted162 -165 untoasted163 -166 untoasted164 -167 untoasted165 -168 untoasted166 -169 untoasted167 -170 untoasted168 -171 untoasted169 -172 untoasted170 -173 untoasted171 -174 untoasted172 -175 untoasted173 -176 untoasted174 -177 untoasted175 -178 untoasted176 -179 untoasted177 -180 untoasted178 -181 untoasted179 -182 untoasted180 -183 untoasted181 -184 untoasted182 -185 untoasted183 -186 untoasted184 -187 untoasted185 -188 untoasted186 -189 untoasted187 -190 untoasted188 -191 untoasted189 -192 untoasted190 -193 untoasted191 -194 untoasted192 -195 untoasted193 -196 untoasted194 -197 untoasted195 -198 untoasted196 -199 untoasted197 -200 untoasted198 -201 toasted3-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 -202 untoasted199 -203 untoasted200 -\. -SELECT substr(data, 1, 200) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- test we can decode "old" tuples bigger than the max heap tuple size correctly -DROP TABLE IF EXISTS toasted_several; -CREATE TABLE toasted_several ( - id serial unique not null, - toasted_key text primary key, - toasted_col1 text, - toasted_col2 text -); -ALTER TABLE toasted_several REPLICA IDENTITY FULL; -ALTER TABLE toasted_several ALTER COLUMN toasted_key SET STORAGE EXTERNAL; -ALTER TABLE toasted_several ALTER COLUMN toasted_col1 SET STORAGE EXTERNAL; -ALTER TABLE toasted_several ALTER COLUMN toasted_col2 SET STORAGE EXTERNAL; - --- Change the storage of the index back to EXTENDED, separately from --- the table. This is currently not doable via DDL, but it is --- supported internally. -UPDATE pg_attribute SET attstorage = 'x' WHERE attrelid = 'toasted_several_pkey'::regclass AND attname = 'toasted_key'; - -INSERT INTO toasted_several(toasted_key) VALUES(repeat('9876543210', 10000)); -SELECT pg_column_size(toasted_key) > 2^16 FROM toasted_several; - -SELECT regexp_replace(data, '^(.{100}).*(.{100})$', '\1..\2') FROM pg_logical_slot_peek_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- test update of a toasted key without changing it -UPDATE toasted_several SET toasted_col1 = toasted_key; -UPDATE toasted_several SET toasted_col2 = toasted_col1; - -SELECT regexp_replace(data, '^(.{100}).*(.{100})$', '\1..\2') FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -/* - * update with large tuplebuf, in a transaction large enough to force to spool to disk - */ -BEGIN; -INSERT INTO toasted_several(toasted_key) SELECT * FROM generate_series(1, 10234); -UPDATE toasted_several SET toasted_col1 = toasted_col2 WHERE id = 1; -DELETE FROM toasted_several WHERE id = 1; -COMMIT; - -DROP TABLE toasted_several; - -SELECT regexp_replace(data, '^(.{100}).*(.{100})$', '\1..\2') FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1') -WHERE data NOT LIKE '%INSERT: %'; - -/* - * Test decoding relation rewrite with toast. The insert into tbl2 within the - * same transaction is there to check that there is no remaining toast_hash not - * being reset. - */ -CREATE TABLE tbl1 (a INT, b TEXT); -CREATE TABLE tbl2 (a INT); -ALTER TABLE tbl1 ALTER COLUMN b SET STORAGE EXTERNAL; -BEGIN; -INSERT INTO tbl1 VALUES(1, repeat('a', 4000)) ; -ALTER TABLE tbl1 ADD COLUMN id serial primary key; -INSERT INTO tbl2 VALUES(1); -commit; -SELECT substr(data, 1, 200) FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftwophase.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftwophase.sql deleted file mode 100644 index aff5114eb1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftwophase.sql +++ /dev/null @@ -1,114 +0,0 @@ --- Test prepared transactions. When two-phase-commit is enabled, transactions are --- decoded at PREPARE time rather than at COMMIT PREPARED time. -SET synchronous_commit = on; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding', false, true); - -CREATE TABLE test_prepared1(id integer primary key); -CREATE TABLE test_prepared2(id integer primary key); - --- Test that decoding happens at PREPARE time when two-phase-commit is enabled. --- Decoding after COMMIT PREPARED must have all the commands in the transaction. -BEGIN; -INSERT INTO test_prepared1 VALUES (1); -INSERT INTO test_prepared1 VALUES (2); --- should show nothing because the xact has not been prepared yet. -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -PREPARE TRANSACTION 'test_prepared#1'; --- should show both the above inserts and the PREPARE TRANSACTION. -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -COMMIT PREPARED 'test_prepared#1'; -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Test that rollback of a prepared xact is decoded. -BEGIN; -INSERT INTO test_prepared1 VALUES (3); -PREPARE TRANSACTION 'test_prepared#2'; -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -ROLLBACK PREPARED 'test_prepared#2'; -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Test prepare of a xact containing ddl. Leaving xact uncommitted for next test. -BEGIN; -ALTER TABLE test_prepared1 ADD COLUMN data text; -INSERT INTO test_prepared1 VALUES (4, 'frakbar'); -PREPARE TRANSACTION 'test_prepared#3'; --- confirm that exclusive lock from the ALTER command is held on test_prepared1 table -SELECT 'test_prepared_1' AS relation, locktype, mode -FROM pg_locks -WHERE locktype = 'relation' - AND relation = 'test_prepared1'::regclass; --- The insert should show the newly altered column but not the DDL. -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Test that we decode correctly while an uncommitted prepared xact --- with ddl exists. --- --- Use a separate table for the concurrent transaction because the lock from --- the ALTER will stop us inserting into the other one. --- -INSERT INTO test_prepared2 VALUES (5); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -COMMIT PREPARED 'test_prepared#3'; -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); --- make sure stuff still works -INSERT INTO test_prepared1 VALUES (6); -INSERT INTO test_prepared2 VALUES (7); -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Check 'CLUSTER' (as operation that hold exclusive lock) doesn't block --- logical decoding. -BEGIN; -INSERT INTO test_prepared1 VALUES (8, 'othercol'); -CLUSTER test_prepared1 USING test_prepared1_pkey; -INSERT INTO test_prepared1 VALUES (9, 'othercol2'); -PREPARE TRANSACTION 'test_prepared_lock'; - -SELECT 'test_prepared1' AS relation, locktype, mode -FROM pg_locks -WHERE locktype = 'relation' - AND relation = 'test_prepared1'::regclass; --- The above CLUSTER command shouldn't cause a timeout on 2pc decoding. -\set env_timeout '' -\getenv env_timeout PG_TEST_TIMEOUT_DEFAULT -SELECT COALESCE(NULLIF(:'env_timeout', ''), '180') || 's' AS timeout \gset -SET statement_timeout = :'timeout'; -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -RESET statement_timeout; -COMMIT PREPARED 'test_prepared_lock'; --- consume the commit -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Test savepoints and sub-xacts. Creating savepoints will create --- sub-xacts implicitly. -BEGIN; -CREATE TABLE test_prepared_savepoint (a int); -INSERT INTO test_prepared_savepoint VALUES (1); -SAVEPOINT test_savepoint; -INSERT INTO test_prepared_savepoint VALUES (2); -ROLLBACK TO SAVEPOINT test_savepoint; -PREPARE TRANSACTION 'test_prepared_savepoint'; --- should show only 1, not 2 -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -COMMIT PREPARED 'test_prepared_savepoint'; --- consume the commit -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Test that a GID containing "_nodecode" gets decoded at commit prepared time. -BEGIN; -INSERT INTO test_prepared1 VALUES (20); -PREPARE TRANSACTION 'test_prepared_nodecode'; --- should show nothing -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); -COMMIT PREPARED 'test_prepared_nodecode'; --- should be decoded now -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- Test 8: --- cleanup and make sure results are also empty -DROP TABLE test_prepared1; -DROP TABLE test_prepared2; --- show results. There should be nothing to show -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftwophase_stream.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftwophase_stream.sql deleted file mode 100644 index 646076da20..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Ftwophase_stream.sql +++ /dev/null @@ -1,45 +0,0 @@ --- Test streaming of two-phase commits - -SET synchronous_commit = on; -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding', false, true); - -CREATE TABLE stream_test(data text); - --- consume DDL -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- streaming test with sub-transaction and PREPARE/COMMIT PREPARED -BEGIN; -SAVEPOINT s1; -SELECT 'msg5' FROM pg_logical_emit_message(true, 'test', repeat('a', 50)); -INSERT INTO stream_test SELECT repeat('a', 2000) || g.i FROM generate_series(1, 35) g(i); -TRUNCATE table stream_test; -ROLLBACK TO s1; -INSERT INTO stream_test SELECT repeat('a', 10) || g.i FROM generate_series(1, 20) g(i); -PREPARE TRANSACTION 'test1'; --- should show the inserts after a ROLLBACK -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - -COMMIT PREPARED 'test1'; ---should show the COMMIT PREPARED and the other changes in the transaction -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - --- streaming test with sub-transaction and PREPARE/COMMIT PREPARED but with --- filtered gid. gids with '_nodecode' will not be decoded at prepare time. -BEGIN; -SAVEPOINT s1; -SELECT 'msg5' FROM pg_logical_emit_message(true, 'test', repeat('a', 50)); -INSERT INTO stream_test SELECT repeat('a', 2000) || g.i FROM generate_series(1, 35) g(i); -TRUNCATE table stream_test; -ROLLBACK to s1; -INSERT INTO stream_test SELECT repeat('a', 10) || g.i FROM generate_series(1, 20) g(i); -PREPARE TRANSACTION 'test1_nodecode'; --- should NOT show inserts after a ROLLBACK -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - -COMMIT PREPARED 'test1_nodecode'; --- should show the inserts but not show a COMMIT PREPARED but a COMMIT -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL,NULL, 'include-xids', '0', 'skip-empty-xacts', '1', 'stream-changes', '1'); - -DROP TABLE stream_test; -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fxact.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fxact.sql deleted file mode 100644 index aa555911e8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fcontrib%2Ftest_decoding%2Fsql%2Fxact.sql +++ /dev/null @@ -1,33 +0,0 @@ --- predictability -SET synchronous_commit = on; - -SELECT 'init' FROM pg_create_logical_replication_slot('regression_slot', 'test_decoding'); - -CREATE TABLE xact_test(data text); -INSERT INTO xact_test VALUES ('before-test'); - --- bug #13844, xids in non-decoded records need to be inspected -BEGIN; --- perform operation in xact that creates and logs xid, but isn't decoded -SELECT * FROM xact_test FOR UPDATE; -SAVEPOINT foo; --- and now actually insert in subxact, xid is expected to be known -INSERT INTO xact_test VALUES ('after-assignment'); -COMMIT; --- and now show those changes -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - --- bug #14279, do not propagate null snapshot from subtransaction -BEGIN; --- first insert -INSERT INTO xact_test VALUES ('main-txn'); -SAVEPOINT foo; --- now perform operation in subxact that creates and logs xid, but isn't decoded -SELECT 1 FROM xact_test FOR UPDATE LIMIT 1; -COMMIT; --- and now show those changes -SELECT data FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL, 'include-xids', '0', 'skip-empty-xacts', '1'); - -DROP TABLE xact_test; - -SELECT pg_drop_replication_slot('regression_slot'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl.sql deleted file mode 100644 index bb0b8ce4cb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl.sql +++ /dev/null @@ -1,523 +0,0 @@ --- --- Test result value processing --- - -CREATE OR REPLACE FUNCTION perl_int(int) RETURNS INTEGER AS $$ -return undef; -$$ LANGUAGE plperl; - -SELECT perl_int(11); -SELECT * FROM perl_int(42); - -CREATE OR REPLACE FUNCTION perl_int(int) RETURNS INTEGER AS $$ -return $_[0] + 1; -$$ LANGUAGE plperl; - -SELECT perl_int(11); -SELECT * FROM perl_int(42); - - -CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$ -return undef; -$$ LANGUAGE plperl; - -SELECT perl_set_int(5); -SELECT * FROM perl_set_int(5); - -CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$ -return [0..$_[0]]; -$$ LANGUAGE plperl; - -SELECT perl_set_int(5); -SELECT * FROM perl_set_int(5); - - -CREATE TYPE testnestperl AS (f5 integer[]); -CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text, f4 testnestperl); - -CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$ - return undef; -$$ LANGUAGE plperl; - -SELECT perl_row(); -SELECT * FROM perl_row(); - - -CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$ - return {f2 => 'hello', f1 => 1, f3 => 'world', 'f4' => { 'f5' => [[1]] } }; -$$ LANGUAGE plperl; - -SELECT perl_row(); -SELECT * FROM perl_row(); - --- test returning a composite literal -CREATE OR REPLACE FUNCTION perl_row_lit() RETURNS testrowperl AS $$ - return '(1,hello,world,"({{1}})")'; -$$ LANGUAGE plperl; - -SELECT perl_row_lit(); - - -CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$ - return undef; -$$ LANGUAGE plperl; - -SELECT perl_set(); -SELECT * FROM perl_set(); - -CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$ - return [ - { f1 => 1, f2 => 'Hello', f3 => 'World' }, - undef, - { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => {} }, - { f1 => 4, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => { 'f5' => undef }}, - { f1 => 5, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => { 'f5' => '{1}' }}, - { f1 => 6, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => { 'f5' => [1] }}, - ]; -$$ LANGUAGE plperl; - -SELECT perl_set(); -SELECT * FROM perl_set(); - -CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$ - return [ - { f1 => 1, f2 => 'Hello', f3 => 'World' }, - { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL', 'f4' => undef }, - { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => {} }, - { f1 => 4, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => { 'f5' => undef }}, - { f1 => 5, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => { 'f5' => '{1}' }}, - { f1 => 6, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => { 'f5' => [1] }}, - { f1 => 7, f2 => 'Hello', f3 => 'PL/Perl', 'f4' => '({1})' }, - ]; -$$ LANGUAGE plperl; - -SELECT perl_set(); -SELECT * FROM perl_set(); - -CREATE OR REPLACE FUNCTION perl_record() RETURNS record AS $$ - return undef; -$$ LANGUAGE plperl; - -SELECT perl_record(); -SELECT * FROM perl_record(); -SELECT * FROM perl_record() AS (f1 integer, f2 text, f3 text, f4 testnestperl); - -CREATE OR REPLACE FUNCTION perl_record() RETURNS record AS $$ - return {f2 => 'hello', f1 => 1, f3 => 'world', 'f4' => { 'f5' => [1] } }; -$$ LANGUAGE plperl; - -SELECT perl_record(); -SELECT * FROM perl_record(); -SELECT * FROM perl_record() AS (f1 integer, f2 text, f3 text, f4 testnestperl); - - -CREATE OR REPLACE FUNCTION perl_record_set() RETURNS SETOF record AS $$ - return undef; -$$ LANGUAGE plperl; - -SELECT perl_record_set(); -SELECT * FROM perl_record_set(); -SELECT * FROM perl_record_set() AS (f1 integer, f2 text, f3 text); - -CREATE OR REPLACE FUNCTION perl_record_set() RETURNS SETOF record AS $$ - return [ - { f1 => 1, f2 => 'Hello', f3 => 'World' }, - undef, - { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' } - ]; -$$ LANGUAGE plperl; - -SELECT perl_record_set(); -SELECT * FROM perl_record_set(); -SELECT * FROM perl_record_set() AS (f1 integer, f2 text, f3 text); - -CREATE OR REPLACE FUNCTION perl_record_set() RETURNS SETOF record AS $$ - return [ - { f1 => 1, f2 => 'Hello', f3 => 'World' }, - { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' }, - { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' } - ]; -$$ LANGUAGE plperl; - -SELECT perl_record_set(); -SELECT * FROM perl_record_set(); -SELECT * FROM perl_record_set() AS (f1 integer, f2 text, f3 text); - -CREATE OR REPLACE FUNCTION -perl_out_params(f1 out integer, f2 out text, f3 out text) AS $$ - return {f2 => 'hello', f1 => 1, f3 => 'world'}; -$$ LANGUAGE plperl; - -SELECT perl_out_params(); -SELECT * FROM perl_out_params(); -SELECT (perl_out_params()).f2; - -CREATE OR REPLACE FUNCTION -perl_out_params_set(out f1 integer, out f2 text, out f3 text) -RETURNS SETOF record AS $$ - return [ - { f1 => 1, f2 => 'Hello', f3 => 'World' }, - { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' }, - { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' } - ]; -$$ LANGUAGE plperl; - -SELECT perl_out_params_set(); -SELECT * FROM perl_out_params_set(); -SELECT (perl_out_params_set()).f3; - --- --- Check behavior with erroneous return values --- - -CREATE TYPE footype AS (x INTEGER, y INTEGER); - -CREATE OR REPLACE FUNCTION foo_good() RETURNS SETOF footype AS $$ -return [ - {x => 1, y => 2}, - {x => 3, y => 4} -]; -$$ LANGUAGE plperl; - -SELECT * FROM foo_good(); - -CREATE OR REPLACE FUNCTION foo_bad() RETURNS footype AS $$ - return {y => 3, z => 4}; -$$ LANGUAGE plperl; - -SELECT * FROM foo_bad(); - -CREATE OR REPLACE FUNCTION foo_bad() RETURNS footype AS $$ -return 42; -$$ LANGUAGE plperl; - -SELECT * FROM foo_bad(); - -CREATE OR REPLACE FUNCTION foo_bad() RETURNS footype AS $$ -return [ - [1, 2], - [3, 4] -]; -$$ LANGUAGE plperl; - -SELECT * FROM foo_bad(); - -CREATE OR REPLACE FUNCTION foo_set_bad() RETURNS SETOF footype AS $$ - return 42; -$$ LANGUAGE plperl; - -SELECT * FROM foo_set_bad(); - -CREATE OR REPLACE FUNCTION foo_set_bad() RETURNS SETOF footype AS $$ - return {y => 3, z => 4}; -$$ LANGUAGE plperl; - -SELECT * FROM foo_set_bad(); - -CREATE OR REPLACE FUNCTION foo_set_bad() RETURNS SETOF footype AS $$ -return [ - [1, 2], - [3, 4] -]; -$$ LANGUAGE plperl; - -SELECT * FROM foo_set_bad(); - -CREATE OR REPLACE FUNCTION foo_set_bad() RETURNS SETOF footype AS $$ -return [ - {y => 3, z => 4} -]; -$$ LANGUAGE plperl; - -SELECT * FROM foo_set_bad(); - -CREATE DOMAIN orderedfootype AS footype CHECK ((VALUE).x <= (VALUE).y); - -CREATE OR REPLACE FUNCTION foo_ordered() RETURNS orderedfootype AS $$ - return {x => 3, y => 4}; -$$ LANGUAGE plperl; - -SELECT * FROM foo_ordered(); - -CREATE OR REPLACE FUNCTION foo_ordered() RETURNS orderedfootype AS $$ - return {x => 5, y => 4}; -$$ LANGUAGE plperl; - -SELECT * FROM foo_ordered(); -- fail - -CREATE OR REPLACE FUNCTION foo_ordered_set() RETURNS SETOF orderedfootype AS $$ -return [ - {x => 3, y => 4}, - {x => 4, y => 7} -]; -$$ LANGUAGE plperl; - -SELECT * FROM foo_ordered_set(); - -CREATE OR REPLACE FUNCTION foo_ordered_set() RETURNS SETOF orderedfootype AS $$ -return [ - {x => 3, y => 4}, - {x => 9, y => 7} -]; -$$ LANGUAGE plperl; - -SELECT * FROM foo_ordered_set(); -- fail - --- --- Check passing a tuple argument --- - -CREATE OR REPLACE FUNCTION perl_get_field(footype, text) RETURNS integer AS $$ - return $_[0]->{$_[1]}; -$$ LANGUAGE plperl; - -SELECT perl_get_field((11,12), 'x'); -SELECT perl_get_field((11,12), 'y'); -SELECT perl_get_field((11,12), 'z'); - -CREATE OR REPLACE FUNCTION perl_get_cfield(orderedfootype, text) RETURNS integer AS $$ - return $_[0]->{$_[1]}; -$$ LANGUAGE plperl; - -SELECT perl_get_cfield((11,12), 'x'); -SELECT perl_get_cfield((11,12), 'y'); -SELECT perl_get_cfield((12,11), 'x'); -- fail - -CREATE OR REPLACE FUNCTION perl_get_rfield(record, text) RETURNS integer AS $$ - return $_[0]->{$_[1]}; -$$ LANGUAGE plperl; - -SELECT perl_get_rfield((11,12), 'f1'); -SELECT perl_get_rfield((11,12)::footype, 'y'); -SELECT perl_get_rfield((11,12)::orderedfootype, 'x'); -SELECT perl_get_rfield((12,11)::orderedfootype, 'x'); -- fail - --- --- Test return_next --- - -CREATE OR REPLACE FUNCTION perl_srf_rn() RETURNS SETOF RECORD AS $$ -my $i = 0; -for ("World", "PostgreSQL", "PL/Perl") { - return_next({f1=>++$i, f2=>'Hello', f3=>$_}); -} -return; -$$ language plperl; -SELECT * from perl_srf_rn() AS (f1 INTEGER, f2 TEXT, f3 TEXT); - --- --- Test spi_query/spi_fetchrow --- - -CREATE OR REPLACE FUNCTION perl_spi_func() RETURNS SETOF INTEGER AS $$ -my $x = spi_query("select 1 as a union select 2 as a"); -while (defined (my $y = spi_fetchrow($x))) { - return_next($y->{a}); -} -return; -$$ LANGUAGE plperl; -SELECT * from perl_spi_func(); - --- --- Test spi_fetchrow abort --- -CREATE OR REPLACE FUNCTION perl_spi_func2() RETURNS INTEGER AS $$ -my $x = spi_query("select 1 as a union select 2 as a"); -spi_cursor_close( $x); -return 0; -$$ LANGUAGE plperl; -SELECT * from perl_spi_func2(); - - ---- ---- Test recursion via SPI ---- - - -CREATE OR REPLACE FUNCTION recurse(i int) RETURNS SETOF TEXT LANGUAGE plperl -AS $$ - - my $i = shift; - foreach my $x (1..$i) - { - return_next "hello $x"; - } - if ($i > 2) - { - my $z = $i-1; - my $cursor = spi_query("select * from recurse($z)"); - while (defined(my $row = spi_fetchrow($cursor))) - { - return_next "recurse $i: $row->{recurse}"; - } - } - return undef; - -$$; - -SELECT * FROM recurse(2); -SELECT * FROM recurse(3); - - ---- ---- Test array return ---- -CREATE OR REPLACE FUNCTION array_of_text() RETURNS TEXT[][] -LANGUAGE plperl as $$ - return [['a"b',undef,'c,d'],['e\\f',undef,'g']]; -$$; - -SELECT array_of_text(); - --- --- Test spi_prepare/spi_exec_prepared/spi_freeplan --- -CREATE OR REPLACE FUNCTION perl_spi_prepared(INTEGER) RETURNS INTEGER AS $$ - my $x = spi_prepare('select $1 AS a', 'INTEGER'); - my $q = spi_exec_prepared( $x, $_[0] + 1); - spi_freeplan($x); -return $q->{rows}->[0]->{a}; -$$ LANGUAGE plperl; -SELECT * from perl_spi_prepared(42); - --- --- Test spi_prepare/spi_query_prepared/spi_freeplan --- -CREATE OR REPLACE FUNCTION perl_spi_prepared_set(INTEGER, INTEGER) RETURNS SETOF INTEGER AS $$ - my $x = spi_prepare('SELECT $1 AS a union select $2 as a', 'INT4', 'INT4'); - my $q = spi_query_prepared( $x, 1+$_[0], 2+$_[1]); - while (defined (my $y = spi_fetchrow($q))) { - return_next $y->{a}; - } - spi_freeplan($x); - return; -$$ LANGUAGE plperl; -SELECT * from perl_spi_prepared_set(1,2); - --- --- Test prepare with a type with spaces --- -CREATE OR REPLACE FUNCTION perl_spi_prepared_double(double precision) RETURNS double precision AS $$ - my $x = spi_prepare('SELECT 10.0 * $1 AS a', 'DOUBLE PRECISION'); - my $q = spi_query_prepared($x,$_[0]); - my $result; - while (defined (my $y = spi_fetchrow($q))) { - $result = $y->{a}; - } - spi_freeplan($x); - return $result; -$$ LANGUAGE plperl; -SELECT perl_spi_prepared_double(4.35) as "double precision"; - --- --- Test with a bad type --- -CREATE OR REPLACE FUNCTION perl_spi_prepared_bad(double precision) RETURNS double precision AS $$ - my $x = spi_prepare('SELECT 10.0 * $1 AS a', 'does_not_exist'); - my $q = spi_query_prepared($x,$_[0]); - my $result; - while (defined (my $y = spi_fetchrow($q))) { - $result = $y->{a}; - } - spi_freeplan($x); - return $result; -$$ LANGUAGE plperl; -SELECT perl_spi_prepared_bad(4.35) as "double precision"; - --- Test with a row type -CREATE OR REPLACE FUNCTION perl_spi_prepared() RETURNS INTEGER AS $$ - my $x = spi_prepare('select $1::footype AS a', 'footype'); - my $q = spi_exec_prepared( $x, '(1, 2)'); - spi_freeplan($x); -return $q->{rows}->[0]->{a}->{x}; -$$ LANGUAGE plperl; -SELECT * from perl_spi_prepared(); - -CREATE OR REPLACE FUNCTION perl_spi_prepared_row(footype) RETURNS footype AS $$ - my $footype = shift; - my $x = spi_prepare('select $1 AS a', 'footype'); - my $q = spi_exec_prepared( $x, {}, $footype ); - spi_freeplan($x); -return $q->{rows}->[0]->{a}; -$$ LANGUAGE plperl; -SELECT * from perl_spi_prepared_row('(1, 2)'); - --- simple test of a DO block -DO $$ - $a = 'This is a test'; - elog(NOTICE, $a); -$$ LANGUAGE plperl; - --- check that restricted operations are rejected in a plperl DO block -DO $$ system("/nonesuch"); $$ LANGUAGE plperl; -DO $$ qx("/nonesuch"); $$ LANGUAGE plperl; -DO $$ open my $fh, " qw(void) ; my @y; sort @y; 1; $do$ LANGUAGE plperl; - --- make sure functions marked as VOID without an explicit return work -CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$ - $_SHARED{myquote} = sub { - my $arg = shift; - $arg =~ s/(['\\])/\\$1/g; - return "'$arg'"; - }; -$$ LANGUAGE plperl; - -SELECT myfuncs(); - --- make sure we can't return an array as a scalar -CREATE OR REPLACE FUNCTION text_arrayref() RETURNS text AS $$ - return ['array']; -$$ LANGUAGE plperl; - -SELECT text_arrayref(); - ---- make sure we can't return a hash as a scalar -CREATE OR REPLACE FUNCTION text_hashref() RETURNS text AS $$ - return {'hash'=>1}; -$$ LANGUAGE plperl; - -SELECT text_hashref(); - ----- make sure we can't return a blessed object as a scalar -CREATE OR REPLACE FUNCTION text_obj() RETURNS text AS $$ - return bless({}, 'Fake::Object'); -$$ LANGUAGE plperl; - -SELECT text_obj(); - --- test looking through a scalar ref -CREATE OR REPLACE FUNCTION text_scalarref() RETURNS text AS $$ - my $str = 'str'; - return \$str; -$$ LANGUAGE plperl; - -SELECT text_scalarref(); - --- check safe behavior when a function body is replaced during execution -CREATE OR REPLACE FUNCTION self_modify(INTEGER) RETURNS INTEGER AS $$ - spi_exec_query('CREATE OR REPLACE FUNCTION self_modify(INTEGER) RETURNS INTEGER AS \'return $_[0] * 3;\' LANGUAGE plperl;'); - spi_exec_query('select self_modify(42) AS a'); - return $_[0] * 2; -$$ LANGUAGE plperl; - -SELECT self_modify(42); -SELECT self_modify(42); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_array.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_array.sql deleted file mode 100644 index 66179294ce..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_array.sql +++ /dev/null @@ -1,171 +0,0 @@ -CREATE OR REPLACE FUNCTION plperl_sum_array(INTEGER[]) RETURNS text AS $$ - my $array_arg = shift; - my $result = 0; - my @arrays; - - push @arrays, @$array_arg; - - while (@arrays > 0) { - my $el = shift @arrays; - if (is_array_ref($el)) { - push @arrays, @$el; - } else { - $result += $el; - } - } - return $result.' '.$array_arg; -$$ LANGUAGE plperl; - -select plperl_sum_array('{1,2,NULL}'); -select plperl_sum_array('{}'); -select plperl_sum_array('{{1,2,3}, {4,5,6}}'); -select plperl_sum_array('{{{1,2,3}, {4,5,6}}, {{7,8,9}, {10,11,12}}}'); - --- check whether we can handle arrays of maximum dimension (6) -select plperl_sum_array(ARRAY[[[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]], -[[13,14],[15,16]]]], -[[[[17,18],[19,20]],[[21,22],[23,24]]],[[[25,26],[27,28]],[[29,30],[31,32]]]]], -[[[[[1,2],[3,4]],[[5,6],[7,8]]],[[[9,10],[11,12]],[[13,14],[15,16]]]], -[[[[17,18],[19,20]],[[21,22],[23,24]]],[[[25,26],[27,28]],[[29,30],[31,32]]]]]]); - --- what would we do with the arrays exceeding maximum dimension (7) -select plperl_sum_array('{{{{{{{1,2},{3,4}},{{5,6},{7,8}}},{{{9,10},{11,12}}, -{{13,14},{15,16}}}}, -{{{{17,18},{19,20}},{{21,22},{23,24}}},{{{25,26},{27,28}},{{29,30},{31,32}}}}}, -{{{{{1,2},{3,4}},{{5,6},{7,8}}},{{{9,10},{11,12}},{{13,14},{15,16}}}}, -{{{{17,18},{19,20}},{{21,22},{23,24}}},{{{25,26},{27,28}},{{29,30},{31,32}}}}}}, -{{{{{{1,2},{3,4}},{{5,6},{7,8}}},{{{9,10},{11,12}},{{13,14},{15,16}}}}, -{{{{17,18},{19,20}},{{21,22},{23,24}}},{{{25,26},{27,28}},{{29,30},{31,32}}}}}, -{{{{{1,2},{3,4}},{{5,6},{7,8}}},{{{9,10},{11,12}},{{13,14},{15,16}}}}, -{{{{17,18},{19,20}},{{21,22},{23,24}}},{{{25,26},{27,28}},{{29,30},{31,32}}}}}}}' -); - -select plperl_sum_array('{{{1,2,3}, {4,5,6,7}}, {{7,8,9}, {10, 11, 12}}}'); - -CREATE OR REPLACE FUNCTION plperl_concat(TEXT[]) RETURNS TEXT AS $$ - my $array_arg = shift; - my $result = ""; - my @arrays; - - push @arrays, @$array_arg; - while (@arrays > 0) { - my $el = shift @arrays; - if (is_array_ref($el)) { - push @arrays, @$el; - } else { - $result .= $el; - } - } - return $result.' '.$array_arg; -$$ LANGUAGE plperl; - -select plperl_concat('{"NULL","NULL","NULL''"}'); -select plperl_concat('{{NULL,NULL,NULL}}'); -select plperl_concat('{"hello"," ","world!"}'); - --- array of rows -- -CREATE TYPE foo AS (bar INTEGER, baz TEXT); -CREATE OR REPLACE FUNCTION plperl_array_of_rows(foo[]) RETURNS TEXT AS $$ - my $array_arg = shift; - my $result = ""; - - for my $row_ref (@$array_arg) { - die "not a hash reference" unless (ref $row_ref eq "HASH"); - $result .= $row_ref->{bar}." items of ".$row_ref->{baz}.";"; - } - return $result .' '. $array_arg; -$$ LANGUAGE plperl; - -select plperl_array_of_rows(ARRAY[ ROW(2, 'coffee'), ROW(0, 'sugar')]::foo[]); - --- composite type containing arrays -CREATE TYPE rowfoo AS (bar INTEGER, baz INTEGER[]); - -CREATE OR REPLACE FUNCTION plperl_sum_row_elements(rowfoo) RETURNS TEXT AS $$ - my $row_ref = shift; - my $result; - - if (ref $row_ref ne 'HASH') { - $result = 0; - } - else { - $result = $row_ref->{bar}; - die "not an array reference".ref ($row_ref->{baz}) - unless (is_array_ref($row_ref->{baz})); - # process a single-dimensional array - foreach my $elem (@{$row_ref->{baz}}) { - $result += $elem unless ref $elem; - } - } - return $result; -$$ LANGUAGE plperl; - -select plperl_sum_row_elements(ROW(1, ARRAY[2,3,4,5,6,7,8,9,10])::rowfoo); - --- composite type containing array of another composite type, which, in order, --- contains an array of integers. -CREATE TYPE rowbar AS (foo rowfoo[]); - -CREATE OR REPLACE FUNCTION plperl_sum_array_of_rows(rowbar) RETURNS TEXT AS $$ - my $rowfoo_ref = shift; - my $result = 0; - - if (ref $rowfoo_ref eq 'HASH') { - my $row_array_ref = $rowfoo_ref->{foo}; - if (is_array_ref($row_array_ref)) { - foreach my $row_ref (@{$row_array_ref}) { - if (ref $row_ref eq 'HASH') { - $result += $row_ref->{bar}; - die "not an array reference".ref ($row_ref->{baz}) - unless (is_array_ref($row_ref->{baz})); - foreach my $elem (@{$row_ref->{baz}}) { - $result += $elem unless ref $elem; - } - } - else { - die "element baz is not a reference to a rowfoo"; - } - } - } else { - die "not a reference to an array of rowfoo elements" - } - } else { - die "not a reference to type rowbar"; - } - return $result; -$$ LANGUAGE plperl; - -select plperl_sum_array_of_rows(ROW(ARRAY[ROW(1, ARRAY[2,3,4,5,6,7,8,9,10])::rowfoo, -ROW(11, ARRAY[12,13,14,15,16,17,18,19,20])::rowfoo])::rowbar); - --- check arrays as out parameters -CREATE OR REPLACE FUNCTION plperl_arrays_out(OUT INTEGER[]) AS $$ - return [[1,2,3],[4,5,6]]; -$$ LANGUAGE plperl; - -select plperl_arrays_out(); - --- check that we can return the array we passed in -CREATE OR REPLACE FUNCTION plperl_arrays_inout(INTEGER[]) returns INTEGER[] AS $$ - return shift; -$$ LANGUAGE plperl; - -select plperl_arrays_inout('{{1}, {2}, {3}}'); - --- check that we can return an array literal -CREATE OR REPLACE FUNCTION plperl_arrays_inout_l(INTEGER[]) returns INTEGER[] AS $$ - return shift.''; # stringify it -$$ LANGUAGE plperl; - -select plperl_arrays_inout_l('{{1}, {2}, {3}}'); - --- make sure setof works -create or replace function perl_setof_array(integer[]) returns setof integer[] language plperl as $$ - my $arr = shift; - for my $r (@$arr) { - return_next $r; - } - return undef; -$$; - -select perl_setof_array('{{1}, {2}, {3}}'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_call.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_call.sql deleted file mode 100644 index bbea85fc9f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_call.sql +++ /dev/null @@ -1,78 +0,0 @@ -CREATE PROCEDURE test_proc1() -LANGUAGE plperl -AS $$ -undef; -$$; - -CALL test_proc1(); - - -CREATE PROCEDURE test_proc2() -LANGUAGE plperl -AS $$ -return 5 -$$; - -CALL test_proc2(); - - -CREATE TABLE test1 (a int); - -CREATE PROCEDURE test_proc3(x int) -LANGUAGE plperl -AS $$ -spi_exec_query("INSERT INTO test1 VALUES ($_[0])"); -$$; - -CALL test_proc3(55); - -SELECT * FROM test1; - - --- output arguments - -CREATE PROCEDURE test_proc5(INOUT a text) -LANGUAGE plperl -AS $$ -my ($a) = @_; -return { a => "$a+$a" }; -$$; - -CALL test_proc5('abc'); - - -CREATE PROCEDURE test_proc6(a int, INOUT b int, INOUT c int) -LANGUAGE plperl -AS $$ -my ($a, $b, $c) = @_; -return { b => $b * $a, c => $c * $a }; -$$; - -CALL test_proc6(2, 3, 4); - - --- OUT parameters - -CREATE PROCEDURE test_proc9(IN a int, OUT b int) -LANGUAGE plperl -AS $$ -my ($a, $b) = @_; -elog(NOTICE, "a: $a, b: $b"); -return { b => $a * 2 }; -$$; - -DO $$ -DECLARE _a int; _b int; -BEGIN - _a := 10; _b := 30; - CALL test_proc9(_a, _b); - RAISE NOTICE '_a: %, _b: %', _a, _b; -END -$$; - - -DROP PROCEDURE test_proc1; -DROP PROCEDURE test_proc2; -DROP PROCEDURE test_proc3; - -DROP TABLE test1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_elog.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_elog.sql deleted file mode 100644 index 9ea1350069..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_elog.sql +++ /dev/null @@ -1,93 +0,0 @@ --- test warnings and errors from plperl - -create or replace function perl_elog(text) returns void language plperl as $$ - - my $msg = shift; - elog(NOTICE,$msg); - -$$; - -select perl_elog('explicit elog'); - -create or replace function perl_warn(text) returns void language plperl as $$ - - my $msg = shift; - warn($msg); - -$$; - -select perl_warn('implicit elog via warn'); - --- test strict mode on/off - -SET plperl.use_strict = true; - -create or replace function uses_global() returns text language plperl as $$ - - $global = 1; - $other_global = 2; - return 'uses_global worked'; - -$$; - -select uses_global(); - -SET plperl.use_strict = false; - -create or replace function uses_global() returns text language plperl as $$ - - $global = 1; - $other_global=2; - return 'uses_global worked'; - -$$; - -select uses_global(); - --- make sure we don't choke on readonly values -do language plperl $$ elog(NOTICE, ${^TAINT}); $$; - --- test recovery after "die" - -create or replace function just_die() returns void language plperl AS $$ -die "just die"; -$$; - -select just_die(); - -create or replace function die_caller() returns int language plpgsql as $$ -BEGIN - BEGIN - PERFORM just_die(); - EXCEPTION WHEN OTHERS THEN - RAISE NOTICE 'caught die'; - END; - RETURN 1; -END; -$$; - -select die_caller(); - -create or replace function indirect_die_caller() returns int language plperl as $$ -my $prepared = spi_prepare('SELECT die_caller() AS fx'); -my $a = spi_exec_prepared($prepared)->{rows}->[0]->{fx}; -my $b = spi_exec_prepared($prepared)->{rows}->[0]->{fx}; -return $a + $b; -$$; - -select indirect_die_caller(); - --- Test non-ASCII error messages --- --- Note: this test case is known to fail if the database encoding is --- EUC_CN, EUC_JP, EUC_KR, or EUC_TW, for lack of any equivalent to --- U+00A0 (no-break space) in those encodings. However, testing with --- plain ASCII data would be rather useless, so we must live with that. - -SET client_encoding TO UTF8; - -create or replace function error_with_nbsp() returns void language plperl as $$ - elog(ERROR, "this message contains a no-break space"); -$$; - -select error_with_nbsp(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_lc.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_lc.sql deleted file mode 100644 index a4a06e722f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_lc.sql +++ /dev/null @@ -1,8 +0,0 @@ --- --- Make sure strings are validated --- Should fail for all encodings, as nul bytes are never permitted. --- -CREATE OR REPLACE FUNCTION perl_zerob() RETURNS TEXT AS $$ - return "abcd\0efg"; -$$ LANGUAGE plperl; -SELECT perl_zerob(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_plperlu.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_plperlu.sql deleted file mode 100644 index bbd79b662e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_plperlu.sql +++ /dev/null @@ -1,58 +0,0 @@ --- test plperl/plperlu interaction - --- the language and call ordering of this test sequence is useful - -CREATE OR REPLACE FUNCTION bar() RETURNS integer AS $$ - #die 'BANG!'; # causes server process to exit(2) - # alternative - causes server process to exit(255) - spi_exec_query("invalid sql statement"); -$$ language plperl; -- compile plperl code - -CREATE OR REPLACE FUNCTION foo() RETURNS integer AS $$ - spi_exec_query("SELECT * FROM bar()"); - return 1; -$$ LANGUAGE plperlu; -- compile plperlu code - -SELECT * FROM bar(); -- throws exception normally (running plperl) -SELECT * FROM foo(); -- used to cause backend crash (after switching to plperlu) - --- test redefinition of specific SP switching languages --- http://archives.postgresql.org/pgsql-bugs/2010-01/msg00116.php - --- plperl first -create or replace function foo(text) returns text language plperl as 'shift'; -select foo('hey'); -create or replace function foo(text) returns text language plperlu as 'shift'; -select foo('hey'); -create or replace function foo(text) returns text language plperl as 'shift'; -select foo('hey'); - --- plperlu first -create or replace function bar(text) returns text language plperlu as 'shift'; -select bar('hey'); -create or replace function bar(text) returns text language plperl as 'shift'; -select bar('hey'); -create or replace function bar(text) returns text language plperlu as 'shift'; -select bar('hey'); - --- --- Make sure we can't use/require things in plperl --- - -CREATE OR REPLACE FUNCTION use_plperlu() RETURNS void LANGUAGE plperlu -AS $$ -use Errno; -$$; - -CREATE OR REPLACE FUNCTION use_plperl() RETURNS void LANGUAGE plperl -AS $$ -use Errno; -$$; - --- make sure our overloaded require op gets restored/set correctly -select use_plperlu(); - -CREATE OR REPLACE FUNCTION use_plperl() RETURNS void LANGUAGE plperl -AS $$ -use Errno; -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_shared.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_shared.sql deleted file mode 100644 index b60e114faf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_shared.sql +++ /dev/null @@ -1,41 +0,0 @@ --- test plperl.on_plperl_init via the shared hash --- (must be done before plperl is first used) - --- This test tests setting on_plperl_init before loading plperl - --- testing on_plperl_init gets run, and that it can alter %_SHARED -SET plperl.on_plperl_init = '$_SHARED{on_init} = 42'; - --- test the shared hash - -create function setme(key text, val text) returns void language plperl as $$ - - my $key = shift; - my $val = shift; - $_SHARED{$key}= $val; - -$$; - -create function getme(key text) returns text language plperl as $$ - - my $key = shift; - return $_SHARED{$key}; - -$$; - -select setme('ourkey','ourval'); - -select getme('ourkey'); - -select getme('on_init'); - --- verify that we can use $_SHARED in strict mode -create or replace function perl_shared() returns int as $$ -use strict; -my $val = $_SHARED{'stuff'}; -$_SHARED{'stuff'} = '1'; -return $val; -$$ language plperl; - -select perl_shared(); -select perl_shared(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_transaction.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_transaction.sql deleted file mode 100644 index d10c8bee89..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_transaction.sql +++ /dev/null @@ -1,195 +0,0 @@ -CREATE TABLE test1 (a int, b text); - - -CREATE PROCEDURE transaction_test1() -LANGUAGE plperl -AS $$ -foreach my $i (0..9) { - spi_exec_query("INSERT INTO test1 (a) VALUES ($i)"); - if ($i % 2 == 0) { - spi_commit(); - } else { - spi_rollback(); - } -} -$$; - -CALL transaction_test1(); - -SELECT * FROM test1; - - -TRUNCATE test1; - -DO -LANGUAGE plperl -$$ -foreach my $i (0..9) { - spi_exec_query("INSERT INTO test1 (a) VALUES ($i)"); - if ($i % 2 == 0) { - spi_commit(); - } else { - spi_rollback(); - } -} -$$; - -SELECT * FROM test1; - - -TRUNCATE test1; - --- not allowed in a function -CREATE FUNCTION transaction_test2() RETURNS int -LANGUAGE plperl -AS $$ -foreach my $i (0..9) { - spi_exec_query("INSERT INTO test1 (a) VALUES ($i)"); - if ($i % 2 == 0) { - spi_commit(); - } else { - spi_rollback(); - } -} -return 1; -$$; - -SELECT transaction_test2(); - -SELECT * FROM test1; - - --- also not allowed if procedure is called from a function -CREATE FUNCTION transaction_test3() RETURNS int -LANGUAGE plperl -AS $$ -spi_exec_query("CALL transaction_test1()"); -return 1; -$$; - -SELECT transaction_test3(); - -SELECT * FROM test1; - - --- DO block inside function -CREATE FUNCTION transaction_test4() RETURNS int -LANGUAGE plperl -AS $$ -spi_exec_query('DO LANGUAGE plperl $x$ spi_commit(); $x$'); -return 1; -$$; - -SELECT transaction_test4(); - - --- commit inside cursor loop -CREATE TABLE test2 (x int); -INSERT INTO test2 VALUES (0), (1), (2), (3), (4); - -TRUNCATE test1; - -DO LANGUAGE plperl $$ -my $sth = spi_query("SELECT * FROM test2 ORDER BY x"); -my $row; -while (defined($row = spi_fetchrow($sth))) { - spi_exec_query("INSERT INTO test1 (a) VALUES (" . $row->{x} . ")"); - spi_commit(); -} -$$; - -SELECT * FROM test1; - --- check that this doesn't leak a holdable portal -SELECT * FROM pg_cursors; - - --- error in cursor loop with commit -TRUNCATE test1; - -DO LANGUAGE plperl $$ -my $sth = spi_query("SELECT * FROM test2 ORDER BY x"); -my $row; -while (defined($row = spi_fetchrow($sth))) { - spi_exec_query("INSERT INTO test1 (a) VALUES (12/(" . $row->{x} . "-2))"); - spi_commit(); -} -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plperl $$ -my $sth = spi_query("SELECT * FROM test2 ORDER BY x"); -my $row; -while (defined($row = spi_fetchrow($sth))) { - spi_exec_query("INSERT INTO test1 (a) VALUES (" . $row->{x} . ")"); - spi_rollback(); -} -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- first commit then rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plperl $$ -my $sth = spi_query("SELECT * FROM test2 ORDER BY x"); -my $row; -while (defined($row = spi_fetchrow($sth))) { - spi_exec_query("INSERT INTO test1 (a) VALUES (" . $row->{x} . ")"); - if ($row->{x} % 2 == 0) { - spi_commit(); - } else { - spi_rollback(); - } -} -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- check handling of an error during COMMIT -CREATE TABLE testpk (id int PRIMARY KEY); -CREATE TABLE testfk(f1 int REFERENCES testpk DEFERRABLE INITIALLY DEFERRED); - -DO LANGUAGE plperl $$ -# this insert will fail during commit: -spi_exec_query("INSERT INTO testfk VALUES (0)"); -spi_commit(); -elog(WARNING, 'should not get here'); -$$; - -SELECT * FROM testpk; -SELECT * FROM testfk; - -DO LANGUAGE plperl $$ -# this insert will fail during commit: -spi_exec_query("INSERT INTO testfk VALUES (0)"); -eval { - spi_commit(); -}; -if ($@) { - elog(INFO, $@); -} -# these inserts should work: -spi_exec_query("INSERT INTO testpk VALUES (1)"); -spi_exec_query("INSERT INTO testfk VALUES (1)"); -$$; - -SELECT * FROM testpk; -SELECT * FROM testfk; - - -DROP TABLE test1; -DROP TABLE test2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_trigger.sql deleted file mode 100644 index 4adddeb80a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_trigger.sql +++ /dev/null @@ -1,259 +0,0 @@ --- test plperl triggers - -CREATE TYPE rowcomp as (i int); -CREATE TYPE rowcompnest as (rfoo rowcomp); -CREATE TABLE trigger_test ( - i int, - v varchar, - foo rowcompnest -); - -CREATE TABLE trigger_test_generated ( - i int, - j int GENERATED ALWAYS AS (i * 2) STORED -); - -CREATE OR REPLACE FUNCTION trigger_data() RETURNS trigger LANGUAGE plperl AS $$ - - # make sure keys are sorted for consistent results - perl no longer - # hashes in repeatable fashion across runs - - sub str { - my $val = shift; - - if (!defined $val) - { - return 'NULL'; - } - elsif (ref $val eq 'HASH') - { - my $str = ''; - foreach my $rowkey (sort keys %$val) - { - $str .= ", " if $str; - my $rowval = str($val->{$rowkey}); - $str .= "'$rowkey' => $rowval"; - } - return '{'. $str .'}'; - } - elsif (ref $val eq 'ARRAY') - { - my $str = ''; - for my $argval (@$val) - { - $str .= ", " if $str; - $str .= str($argval); - } - return '['. $str .']'; - } - else - { - return "'$val'"; - } - } - - foreach my $key (sort keys %$_TD) - { - - my $val = $_TD->{$key}; - - # relid is variable, so we can not use it repeatably - $val = "bogus:12345" if $key eq 'relid'; - - elog(NOTICE, "\$_TD->\{$key\} = ". str($val)); - } - return undef; # allow statement to proceed; -$$; - -CREATE TRIGGER show_trigger_data_trig -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -insert into trigger_test values(1,'insert', '("(1)")'); -update trigger_test set v = 'update' where i = 1; -delete from trigger_test; - -DROP TRIGGER show_trigger_data_trig on trigger_test; - -CREATE TRIGGER show_trigger_data_trig_before -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE trigger_data(); - -CREATE TRIGGER show_trigger_data_trig_after -AFTER INSERT OR UPDATE OR DELETE ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE trigger_data(); - -insert into trigger_test_generated (i) values (1); -update trigger_test_generated set i = 11 where i = 1; -delete from trigger_test_generated; - -DROP TRIGGER show_trigger_data_trig_before ON trigger_test_generated; -DROP TRIGGER show_trigger_data_trig_after ON trigger_test_generated; - -insert into trigger_test values(1,'insert', '("(1)")'); -CREATE VIEW trigger_test_view AS SELECT * FROM trigger_test; - -CREATE TRIGGER show_trigger_data_trig -INSTEAD OF INSERT OR UPDATE OR DELETE ON trigger_test_view -FOR EACH ROW EXECUTE PROCEDURE trigger_data(24,'skidoo view'); - -insert into trigger_test_view values(2,'insert', '("(2)")'); -update trigger_test_view set v = 'update', foo = '("(3)")' where i = 1; -delete from trigger_test_view; - -DROP VIEW trigger_test_view; -delete from trigger_test; - -DROP FUNCTION trigger_data(); - -CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS $$ - - if (($_TD->{new}{i}>=100) || ($_TD->{new}{i}<=0)) - { - return "SKIP"; # Skip INSERT/UPDATE command - } - elsif ($_TD->{new}{v} ne "immortal") - { - $_TD->{new}{v} .= "(modified by trigger)"; - $_TD->{new}{foo}{rfoo}{i}++; - return "MODIFY"; # Modify tuple and proceed INSERT/UPDATE command - } - else - { - return; # Proceed INSERT/UPDATE command - } -$$ LANGUAGE plperl; - -CREATE TRIGGER "test_valid_id_trig" BEFORE INSERT OR UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE "valid_id"(); - -INSERT INTO trigger_test (i, v, foo) VALUES (1,'first line', '("(1)")'); -INSERT INTO trigger_test (i, v, foo) VALUES (2,'second line', '("(2)")'); -INSERT INTO trigger_test (i, v, foo) VALUES (3,'third line', '("(3)")'); -INSERT INTO trigger_test (i, v, foo) VALUES (4,'immortal', '("(4)")'); - -INSERT INTO trigger_test (i, v) VALUES (101,'bad id'); - -SELECT * FROM trigger_test; - -UPDATE trigger_test SET i = 5 where i=3; - -UPDATE trigger_test SET i = 100 where i=1; - -SELECT * FROM trigger_test; - -DROP TRIGGER "test_valid_id_trig" ON trigger_test; - -CREATE OR REPLACE FUNCTION trigger_recurse() RETURNS trigger AS $$ - use strict; - - if ($_TD->{new}{i} == 10000) - { - spi_exec_query("insert into trigger_test (i, v) values (20000, 'child');"); - - if ($_TD->{new}{i} != 10000) - { - die "recursive trigger modified: ". $_TD->{new}{i}; - } - } - return; -$$ LANGUAGE plperl; - -CREATE TRIGGER "test_trigger_recurse" BEFORE INSERT ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE "trigger_recurse"(); - -INSERT INTO trigger_test (i, v) values (10000, 'top'); - -SELECT * FROM trigger_test; - -CREATE OR REPLACE FUNCTION immortal() RETURNS trigger AS $$ - if ($_TD->{old}{v} eq $_TD->{args}[0]) - { - return "SKIP"; # Skip DELETE command - } - else - { - return; # Proceed DELETE command - }; -$$ LANGUAGE plperl; - -CREATE TRIGGER "immortal_trig" BEFORE DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE immortal('immortal'); - -DELETE FROM trigger_test; - -SELECT * FROM trigger_test; - -CREATE FUNCTION direct_trigger() RETURNS trigger AS $$ - return; -$$ LANGUAGE plperl; - -SELECT direct_trigger(); - --- check that SQL run in trigger code can see transition tables - -CREATE TABLE transition_table_test (id int, name text); -INSERT INTO transition_table_test VALUES (1, 'a'); - -CREATE FUNCTION transition_table_test_f() RETURNS trigger LANGUAGE plperl AS -$$ - my $cursor = spi_query("SELECT * FROM old_table"); - my $row = spi_fetchrow($cursor); - defined($row) || die "expected a row"; - elog(INFO, "old: " . $row->{id} . " -> " . $row->{name}); - my $row = spi_fetchrow($cursor); - !defined($row) || die "expected no more rows"; - - my $cursor = spi_query("SELECT * FROM new_table"); - my $row = spi_fetchrow($cursor); - defined($row) || die "expected a row"; - elog(INFO, "new: " . $row->{id} . " -> " . $row->{name}); - my $row = spi_fetchrow($cursor); - !defined($row) || die "expected no more rows"; - - return undef; -$$; - -CREATE TRIGGER a_t AFTER UPDATE ON transition_table_test - REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table - FOR EACH STATEMENT EXECUTE PROCEDURE transition_table_test_f(); -UPDATE transition_table_test SET name = 'b'; - -DROP TABLE transition_table_test; -DROP FUNCTION transition_table_test_f(); - --- test plperl command triggers -create or replace function perlsnitch() returns event_trigger language plperl as $$ - elog(NOTICE, "perlsnitch: " . $_TD->{event} . " " . $_TD->{tag} . " "); -$$; - -create event trigger perl_a_snitch on ddl_command_start - execute procedure perlsnitch(); -create event trigger perl_b_snitch on ddl_command_end - execute procedure perlsnitch(); - -create or replace function foobar() returns int language sql as $$select 1;$$; -alter function foobar() cost 77; -drop function foobar(); - -create table foo(); -drop table foo; - -drop event trigger perl_a_snitch; -drop event trigger perl_b_snitch; - --- dealing with generated columns - -CREATE FUNCTION generated_test_func1() RETURNS trigger -LANGUAGE plperl -AS $$ -$_TD->{new}{j} = 5; # not allowed -return 'MODIFY'; -$$; - -CREATE TRIGGER generated_test_trigger1 BEFORE INSERT ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE generated_test_func1(); - -TRUNCATE trigger_test_generated; -INSERT INTO trigger_test_generated (i) VALUES (1); -SELECT * FROM trigger_test_generated; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_util.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_util.sql deleted file mode 100644 index 5b31605ccd..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperl_util.sql +++ /dev/null @@ -1,121 +0,0 @@ --- test plperl utility functions (defined in Util.xs) - --- test quote_literal - -create or replace function perl_quote_literal() returns setof text language plperl as $$ - return_next "undef: ".quote_literal(undef); - return_next sprintf"$_: ".quote_literal($_) - for q{foo}, q{a'b}, q{a"b}, q{c''d}, q{e\f}, q{}; - return undef; -$$; - -select perl_quote_literal(); - --- test quote_nullable - -create or replace function perl_quote_nullable() returns setof text language plperl as $$ - return_next "undef: ".quote_nullable(undef); - return_next sprintf"$_: ".quote_nullable($_) - for q{foo}, q{a'b}, q{a"b}, q{c''d}, q{e\f}, q{}; - return undef; -$$; - -select perl_quote_nullable(); - --- test quote_ident - -create or replace function perl_quote_ident() returns setof text language plperl as $$ - return_next "undef: ".quote_ident(undef); # generates undef warning if warnings enabled - return_next "$_: ".quote_ident($_) - for q{foo}, q{a'b}, q{a"b}, q{c''d}, q{e\f}, q{g.h}, q{}; - return undef; -$$; - -select perl_quote_ident(); - --- test decode_bytea - -create or replace function perl_decode_bytea() returns setof text language plperl as $$ - return_next "undef: ".decode_bytea(undef); # generates undef warning if warnings enabled - return_next "$_: ".decode_bytea($_) - for q{foo}, q{a\047b}, q{}; - return undef; -$$; - -select perl_decode_bytea(); - --- test encode_bytea - -create or replace function perl_encode_bytea() returns setof text language plperl as $$ - return_next encode_bytea(undef); # generates undef warning if warnings enabled - return_next encode_bytea($_) - for q{@}, qq{@\x01@}, qq{@\x00@}, q{}; - return undef; -$$; - -select perl_encode_bytea(); - --- test encode_array_literal - -create or replace function perl_encode_array_literal() returns setof text language plperl as $$ - return_next encode_array_literal(undef); - return_next encode_array_literal(0); - return_next encode_array_literal(42); - return_next encode_array_literal($_) - for [], [0], [1..5], [[]], [[1,2,[3]],4]; - return_next encode_array_literal($_,'|') - for [], [0], [1..5], [[]], [[1,2,[3]],4]; - return undef; -$$; - -select perl_encode_array_literal(); - --- test encode_array_constructor - -create or replace function perl_encode_array_constructor() returns setof text language plperl as $$ - return_next encode_array_constructor(undef); - return_next encode_array_constructor(0); - return_next encode_array_constructor(42); - return_next encode_array_constructor($_) - for [], [0], [1..5], [[]], [[1,2,[3]],4]; - return undef; -$$; - -select perl_encode_array_constructor(); - --- test looks_like_number - -create or replace function perl_looks_like_number() returns setof text language plperl as $$ - return_next "undef is undef" if not defined looks_like_number(undef); - return_next quote_nullable($_).": ". (looks_like_number($_) ? "number" : "not number") - for 'foo', 0, 1, 1.3, '+3.e-4', - '42 x', # trailing garbage - '99 ', # trailing space - ' 99', # leading space - ' ', # only space - ''; # empty string - return undef; -$$; - -select perl_looks_like_number(); - --- test encode_typed_literal -create type perl_foo as (a integer, b text[]); -create type perl_bar as (c perl_foo[]); -create domain perl_foo_pos as perl_foo check((value).a > 0); - -create or replace function perl_encode_typed_literal() returns setof text language plperl as $$ - return_next encode_typed_literal(undef, 'text'); - return_next encode_typed_literal([[1,2,3],[3,2,1],[1,3,2]], 'integer[]'); - return_next encode_typed_literal({a => 1, b => ['PL','/','Perl']}, 'perl_foo'); - return_next encode_typed_literal({c => [{a => 9, b => ['PostgreSQL']}, {b => ['Postgres'], a => 1}]}, 'perl_bar'); - return_next encode_typed_literal({a => 1, b => ['PL','/','Perl']}, 'perl_foo_pos'); -$$; - -select perl_encode_typed_literal(); - -create or replace function perl_encode_typed_literal() returns setof text language plperl as $$ - return_next encode_typed_literal({a => 0, b => ['PL','/','Perl']}, 'perl_foo_pos'); -$$; - -select perl_encode_typed_literal(); -- fail diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperlu.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperlu.sql deleted file mode 100644 index be43df5d90..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplperl%2Fsql%2Fplperlu.sql +++ /dev/null @@ -1,17 +0,0 @@ --- Use ONLY plperlu tests here. For plperl/plerlu combined tests --- see plperl_plperlu.sql - --- This test tests setting on_plperlu_init after loading plperl -LOAD 'plperl'; - --- Test plperl.on_plperlu_init gets run -SET plperl.on_plperlu_init = '$_SHARED{init} = 42'; -DO $$ warn $_SHARED{init} $$ language plperlu; - --- --- Test compilation of unicode regex - regardless of locale. --- This code fails in plain plperl in a non-UTF8 database. --- -CREATE OR REPLACE FUNCTION perl_unicode_regex(text) RETURNS INTEGER AS $$ - return ($_[0] =~ /\x{263A}|happy/i) ? 1 : 0; # unicode smiley -$$ LANGUAGE plperlu; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fplpgsql--1.0.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fplpgsql--1.0.sql deleted file mode 100644 index 6e5b990fcc..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fplpgsql--1.0.sql +++ /dev/null @@ -1,20 +0,0 @@ -/* src/pl/plpgsql/src/plpgsql--1.0.sql */ - -CREATE FUNCTION plpgsql_call_handler() RETURNS language_handler - LANGUAGE c AS 'MODULE_PATHNAME'; - -CREATE FUNCTION plpgsql_inline_handler(internal) RETURNS void - STRICT LANGUAGE c AS 'MODULE_PATHNAME'; - -CREATE FUNCTION plpgsql_validator(oid) RETURNS void - STRICT LANGUAGE c AS 'MODULE_PATHNAME'; - -CREATE TRUSTED LANGUAGE plpgsql - HANDLER plpgsql_call_handler - INLINE plpgsql_inline_handler - VALIDATOR plpgsql_validator; - --- The language object, but not the functions, can be owned by a non-superuser. -ALTER LANGUAGE plpgsql OWNER TO @extowner@; - -COMMENT ON LANGUAGE plpgsql IS 'PL/pgSQL procedural language'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_cache.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_cache.sql deleted file mode 100644 index a48f9b2afa..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_cache.sql +++ /dev/null @@ -1,50 +0,0 @@ --- --- Cache-behavior-dependent test cases --- --- These tests logically belong in plpgsql_record.sql, and perhaps someday --- can be merged back into it. For now, however, their results are different --- depending on debug_discard_caches, so we must have two expected-output --- files to cover both cases. To minimize the maintenance effort resulting --- from that, this file should contain only tests that do have different --- results under debug_discard_caches. --- - --- check behavior with changes of a named rowtype -create table c_mutable(f1 int, f2 text); - -create function c_sillyaddone(int) returns int language plpgsql as -$$ declare r c_mutable; begin r.f1 := $1; return r.f1 + 1; end $$; -select c_sillyaddone(42); - -alter table c_mutable drop column f1; -alter table c_mutable add column f1 float8; - --- currently, this fails due to cached plan for "r.f1 + 1" expression --- (but if debug_discard_caches is on, it will succeed) -select c_sillyaddone(42); - --- but it's OK if we force plan rebuilding -discard plans; -select c_sillyaddone(42); - --- check behavior with changes in a record rowtype -create function show_result_type(text) returns text language plpgsql as -$$ - declare - r record; - t text; - begin - execute $1 into r; - select pg_typeof(r.a) into t; - return format('type %s value %s', t, r.a::text); - end; -$$; - -select show_result_type('select 1 as a'); --- currently this fails due to cached plan for pg_typeof expression --- (but if debug_discard_caches is on, it will succeed) -select show_result_type('select 2.0 as a'); - --- but it's OK if we force plan rebuilding -discard plans; -select show_result_type('select 2.0 as a'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_call.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_call.sql deleted file mode 100644 index 5028398348..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_call.sql +++ /dev/null @@ -1,438 +0,0 @@ --- --- Tests for procedures / CALL syntax --- - -CREATE PROCEDURE test_proc1() -LANGUAGE plpgsql -AS $$ -BEGIN - NULL; -END; -$$; - -CALL test_proc1(); - - --- error: can't return non-NULL -CREATE PROCEDURE test_proc2() -LANGUAGE plpgsql -AS $$ -BEGIN - RETURN 5; -END; -$$; - - -CREATE TABLE test1 (a int); - -CREATE PROCEDURE test_proc3(x int) -LANGUAGE plpgsql -AS $$ -BEGIN - INSERT INTO test1 VALUES (x); -END; -$$; - -CALL test_proc3(55); - -SELECT * FROM test1; - - --- nested CALL -TRUNCATE TABLE test1; - -CREATE PROCEDURE test_proc4(y int) -LANGUAGE plpgsql -AS $$ -BEGIN - CALL test_proc3(y); - CALL test_proc3($1); -END; -$$; - -CALL test_proc4(66); - -SELECT * FROM test1; - -CALL test_proc4(66); - -SELECT * FROM test1; - - --- output arguments - -CREATE PROCEDURE test_proc5(INOUT a text) -LANGUAGE plpgsql -AS $$ -BEGIN - a := a || '+' || a; -END; -$$; - -CALL test_proc5('abc'); - - -CREATE PROCEDURE test_proc6(a int, INOUT b int, INOUT c int) -LANGUAGE plpgsql -AS $$ -BEGIN - b := b * a; - c := c * a; -END; -$$; - -CALL test_proc6(2, 3, 4); - - -DO -LANGUAGE plpgsql -$$ -DECLARE - x int := 3; - y int := 4; -BEGIN - CALL test_proc6(2, x, y); - RAISE INFO 'x = %, y = %', x, y; - CALL test_proc6(2, c => y, b => x); - RAISE INFO 'x = %, y = %', x, y; -END; -$$; - - -DO -LANGUAGE plpgsql -$$ -DECLARE - x int := 3; - y int := 4; -BEGIN - CALL test_proc6(2, x + 1, y); -- error - RAISE INFO 'x = %, y = %', x, y; -END; -$$; - - -DO -LANGUAGE plpgsql -$$ -DECLARE - x constant int := 3; - y int := 4; -BEGIN - CALL test_proc6(2, x, y); -- error because x is constant -END; -$$; - - -DO -LANGUAGE plpgsql -$$ -DECLARE - x int := 3; - y int := 4; -BEGIN - FOR i IN 1..5 LOOP - CALL test_proc6(i, x, y); - RAISE INFO 'x = %, y = %', x, y; - END LOOP; -END; -$$; - - --- recursive with output arguments - -CREATE PROCEDURE test_proc7(x int, INOUT a int, INOUT b numeric) -LANGUAGE plpgsql -AS $$ -BEGIN -IF x > 1 THEN - a := x / 10; - b := x / 2; - CALL test_proc7(b::int, a, b); -END IF; -END; -$$; - -CALL test_proc7(100, -1, -1); - --- inner COMMIT with output arguments - -CREATE PROCEDURE test_proc7c(x int, INOUT a int, INOUT b numeric) -LANGUAGE plpgsql -AS $$ -BEGIN - a := x / 10; - b := x / 2; - COMMIT; -END; -$$; - -CREATE PROCEDURE test_proc7cc(_x int) -LANGUAGE plpgsql -AS $$ -DECLARE _a int; _b numeric; -BEGIN - CALL test_proc7c(_x, _a, _b); - RAISE NOTICE '_x: %,_a: %, _b: %', _x, _a, _b; -END -$$; - -CALL test_proc7cc(10); - - --- named parameters and defaults - -CREATE PROCEDURE test_proc8a(INOUT a int, INOUT b int) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'a: %, b: %', a, b; - a := a * 10; - b := b + 10; -END; -$$; - -CALL test_proc8a(10, 20); -CALL test_proc8a(b => 20, a => 10); - -DO $$ -DECLARE _a int; _b int; -BEGIN - _a := 10; _b := 30; - CALL test_proc8a(_a, _b); - RAISE NOTICE '_a: %, _b: %', _a, _b; - CALL test_proc8a(b => _b, a => _a); - RAISE NOTICE '_a: %, _b: %', _a, _b; -END -$$; - - -CREATE PROCEDURE test_proc8b(INOUT a int, INOUT b int, INOUT c int) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'a: %, b: %, c: %', a, b, c; - a := a * 10; - b := b + 10; - c := c * -10; -END; -$$; - -DO $$ -DECLARE _a int; _b int; _c int; -BEGIN - _a := 10; _b := 30; _c := 50; - CALL test_proc8b(_a, _b, _c); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - CALL test_proc8b(_a, c => _c, b => _b); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; -END -$$; - - -CREATE PROCEDURE test_proc8c(INOUT a int, INOUT b int, INOUT c int DEFAULT 11) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'a: %, b: %, c: %', a, b, c; - a := a * 10; - b := b + 10; - c := c * -10; -END; -$$; - -DO $$ -DECLARE _a int; _b int; _c int; -BEGIN - _a := 10; _b := 30; _c := 50; - CALL test_proc8c(_a, _b, _c); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - _a := 10; _b := 30; _c := 50; - CALL test_proc8c(_a, c => _c, b => _b); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - _a := 10; _b := 30; _c := 50; - CALL test_proc8c(c => _c, b => _b, a => _a); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; -END -$$; - -DO $$ -DECLARE _a int; _b int; _c int; -BEGIN - _a := 10; _b := 30; _c := 50; - CALL test_proc8c(_a, _b); -- fail, no output argument for c - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; -END -$$; - -DO $$ -DECLARE _a int; _b int; _c int; -BEGIN - _a := 10; _b := 30; _c := 50; - CALL test_proc8c(_a, b => _b); -- fail, no output argument for c - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; -END -$$; - - --- OUT parameters - -CREATE PROCEDURE test_proc9(IN a int, OUT b int) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'a: %, b: %', a, b; - b := a * 2; -END; -$$; - -DO $$ -DECLARE _a int; _b int; -BEGIN - _a := 10; _b := 30; - CALL test_proc9(_a, _b); - RAISE NOTICE '_a: %, _b: %', _a, _b; -END -$$; - -CREATE PROCEDURE test_proc10(IN a int, OUT b int, IN c int DEFAULT 11) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'a: %, b: %, c: %', a, b, c; - b := a - c; -END; -$$; - -DO $$ -DECLARE _a int; _b int; _c int; -BEGIN - _a := 10; _b := 30; _c := 7; - CALL test_proc10(_a, _b, _c); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - - _a := 10; _b := 30; _c := 7; - CALL test_proc10(_a, _b, c => _c); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - - _a := 10; _b := 30; _c := 7; - CALL test_proc10(a => _a, b => _b, c => _c); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - - _a := 10; _b := 30; _c := 7; - CALL test_proc10(_a, c => _c, b => _b); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - - _a := 10; _b := 30; _c := 7; - CALL test_proc10(_a, _b); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - - _a := 10; _b := 30; _c := 7; - CALL test_proc10(_a, b => _b); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; - - _a := 10; _b := 30; _c := 7; - CALL test_proc10(b => _b, a => _a); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; -END -$$; - --- OUT + VARIADIC - -CREATE PROCEDURE test_proc11(a OUT int, VARIADIC b int[]) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'a: %, b: %', a, b; - a := b[1] + b[2]; -END; -$$; - -DO $$ -DECLARE _a int; _b int; _c int; -BEGIN - _a := 10; _b := 30; _c := 7; - CALL test_proc11(_a, _b, _c); - RAISE NOTICE '_a: %, _b: %, _c: %', _a, _b, _c; -END -$$; - - --- transition variable assignment - -TRUNCATE test1; - -CREATE FUNCTION triggerfunc1() RETURNS trigger -LANGUAGE plpgsql -AS $$ -DECLARE - z int := 0; -BEGIN - CALL test_proc6(2, NEW.a, NEW.a); - RETURN NEW; -END; -$$; - -CREATE TRIGGER t1 BEFORE INSERT ON test1 EXECUTE PROCEDURE triggerfunc1(); - -INSERT INTO test1 VALUES (1), (2), (3); - -UPDATE test1 SET a = 22 WHERE a = 2; - -SELECT * FROM test1 ORDER BY a; - - -DROP PROCEDURE test_proc1; -DROP PROCEDURE test_proc3; -DROP PROCEDURE test_proc4; - -DROP TABLE test1; - - --- more checks for named-parameter handling - -CREATE PROCEDURE p1(v_cnt int, v_Text inout text = NULL) -AS $$ -BEGIN - v_Text := 'v_cnt = ' || v_cnt; -END -$$ LANGUAGE plpgsql; - -DO $$ -DECLARE - v_Text text; - v_cnt integer := 42; -BEGIN - CALL p1(v_cnt := v_cnt); -- error, must supply something for v_Text - RAISE NOTICE '%', v_Text; -END; -$$; - -DO $$ -DECLARE - v_Text text; - v_cnt integer := 42; -BEGIN - CALL p1(v_cnt := v_cnt, v_Text := v_Text); - RAISE NOTICE '%', v_Text; -END; -$$; - -DO $$ -DECLARE - v_Text text; -BEGIN - CALL p1(10, v_Text := v_Text); - RAISE NOTICE '%', v_Text; -END; -$$; - -DO $$ -DECLARE - v_Text text; - v_cnt integer; -BEGIN - CALL p1(v_Text := v_Text, v_cnt := v_cnt); - RAISE NOTICE '%', v_Text; -END; -$$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_control.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_control.sql deleted file mode 100644 index ed7231134f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_control.sql +++ /dev/null @@ -1,488 +0,0 @@ --- --- Tests for PL/pgSQL control structures --- - --- integer FOR loop - -do $$ -begin - -- basic case - for i in 1..3 loop - raise notice '1..3: i = %', i; - end loop; - -- with BY, end matches exactly - for i in 1..10 by 3 loop - raise notice '1..10 by 3: i = %', i; - end loop; - -- with BY, end does not match - for i in 1..11 by 3 loop - raise notice '1..11 by 3: i = %', i; - end loop; - -- zero iterations - for i in 1..0 by 3 loop - raise notice '1..0 by 3: i = %', i; - end loop; - -- REVERSE - for i in reverse 10..0 by 3 loop - raise notice 'reverse 10..0 by 3: i = %', i; - end loop; - -- potential overflow - for i in 2147483620..2147483647 by 10 loop - raise notice '2147483620..2147483647 by 10: i = %', i; - end loop; - -- potential overflow, reverse direction - for i in reverse -2147483620..-2147483647 by 10 loop - raise notice 'reverse -2147483620..-2147483647 by 10: i = %', i; - end loop; -end$$; - --- BY can't be zero or negative -do $$ -begin - for i in 1..3 by 0 loop - raise notice '1..3 by 0: i = %', i; - end loop; -end$$; - -do $$ -begin - for i in 1..3 by -1 loop - raise notice '1..3 by -1: i = %', i; - end loop; -end$$; - -do $$ -begin - for i in reverse 1..3 by -1 loop - raise notice 'reverse 1..3 by -1: i = %', i; - end loop; -end$$; - - --- CONTINUE statement - -create table conttesttbl(idx serial, v integer); -insert into conttesttbl(v) values(10); -insert into conttesttbl(v) values(20); -insert into conttesttbl(v) values(30); -insert into conttesttbl(v) values(40); - -create function continue_test1() returns void as $$ -declare _i integer = 0; _r record; -begin - raise notice '---1---'; - loop - _i := _i + 1; - raise notice '%', _i; - continue when _i < 10; - exit; - end loop; - - raise notice '---2---'; - <> - loop - _i := _i - 1; - loop - raise notice '%', _i; - continue lbl when _i > 0; - exit lbl; - end loop; - end loop; - - raise notice '---3---'; - <> - while _i < 10 loop - _i := _i + 1; - continue the_loop when _i % 2 = 0; - raise notice '%', _i; - end loop; - - raise notice '---4---'; - for _i in 1..10 loop - begin - -- applies to outer loop, not the nested begin block - continue when _i < 5; - raise notice '%', _i; - end; - end loop; - - raise notice '---5---'; - for _r in select * from conttesttbl loop - continue when _r.v <= 20; - raise notice '%', _r.v; - end loop; - - raise notice '---6---'; - for _r in execute 'select * from conttesttbl' loop - continue when _r.v <= 20; - raise notice '%', _r.v; - end loop; - - raise notice '---7---'; - <> - for _i in 1..3 loop - continue looplabel when _i = 2; - raise notice '%', _i; - end loop; - - raise notice '---8---'; - _i := 1; - while _i <= 3 loop - raise notice '%', _i; - _i := _i + 1; - continue when _i = 3; - end loop; - - raise notice '---9---'; - for _r in select * from conttesttbl order by v limit 1 loop - raise notice '%', _r.v; - continue; - end loop; - - raise notice '---10---'; - for _r in execute 'select * from conttesttbl order by v limit 1' loop - raise notice '%', _r.v; - continue; - end loop; - - raise notice '---11---'; - <> - for _i in 1..2 loop - raise notice 'outer %', _i; - <> - for _j in 1..3 loop - continue outerlooplabel when _j = 2; - raise notice 'inner %', _j; - end loop; - end loop; -end; $$ language plpgsql; - -select continue_test1(); - --- should fail: CONTINUE is only legal inside a loop -create function continue_error1() returns void as $$ -begin - begin - continue; - end; -end; -$$ language plpgsql; - --- should fail: unlabeled EXIT is only legal inside a loop -create function exit_error1() returns void as $$ -begin - begin - exit; - end; -end; -$$ language plpgsql; - --- should fail: no such label -create function continue_error2() returns void as $$ -begin - begin - loop - continue no_such_label; - end loop; - end; -end; -$$ language plpgsql; - --- should fail: no such label -create function exit_error2() returns void as $$ -begin - begin - loop - exit no_such_label; - end loop; - end; -end; -$$ language plpgsql; - --- should fail: CONTINUE can't reference the label of a named block -create function continue_error3() returns void as $$ -begin - <> - begin - loop - continue begin_block1; - end loop; - end; -end; -$$ language plpgsql; - --- On the other hand, EXIT *can* reference the label of a named block -create function exit_block1() returns void as $$ -begin - <> - begin - loop - exit begin_block1; - raise exception 'should not get here'; - end loop; - end; -end; -$$ language plpgsql; - -select exit_block1(); - --- verbose end block and end loop -create function end_label1() returns void as $$ -<> -begin - <> - for i in 1 .. 10 loop - raise notice 'i = %', i; - exit flbl1; - end loop flbl1; - <> - for j in 1 .. 10 loop - raise notice 'j = %', j; - exit flbl2; - end loop; -end blbl; -$$ language plpgsql; - -select end_label1(); - --- should fail: undefined end label -create function end_label2() returns void as $$ -begin - for _i in 1 .. 10 loop - exit; - end loop flbl1; -end; -$$ language plpgsql; - --- should fail: end label does not match start label -create function end_label3() returns void as $$ -<> -begin - <> - for _i in 1 .. 10 loop - exit; - end loop outer_label; -end; -$$ language plpgsql; - --- should fail: end label on a block without a start label -create function end_label4() returns void as $$ -<> -begin - for _i in 1 .. 10 loop - exit; - end loop outer_label; -end; -$$ language plpgsql; - --- unlabeled exit matches no blocks -do $$ -begin -for i in 1..10 loop - <> - begin - begin -- unlabeled block - exit; - raise notice 'should not get here'; - end; - raise notice 'should not get here, either'; - end; - raise notice 'nor here'; -end loop; -raise notice 'should get here'; -end$$; - --- check exit out of an unlabeled block to a labeled one -do $$ -<> -begin - <> - begin - <> - begin - begin -- unlabeled block - exit innerblock; - raise notice 'should not get here'; - end; - raise notice 'should not get here, either'; - end; - raise notice 'nor here'; - end; - raise notice 'should get here'; -end$$; - --- check exit out of outermost block -do $$ -<> -begin - <> - begin - exit outerblock; - raise notice 'should not get here'; - end; - raise notice 'should not get here, either'; -end$$; - --- unlabeled exit does match a while loop -do $$ -begin - <> - while 1 > 0 loop - <> - while 1 > 0 loop - <> - while 1 > 0 loop - exit; - raise notice 'should not get here'; - end loop; - raise notice 'should get here'; - exit outermostwhile; - raise notice 'should not get here, either'; - end loop; - raise notice 'nor here'; - end loop; - raise notice 'should get here, too'; -end$$; - --- check exit out of an unlabeled while to a labeled one -do $$ -begin - <> - while 1 > 0 loop - while 1 > 0 loop - exit outerwhile; - raise notice 'should not get here'; - end loop; - raise notice 'should not get here, either'; - end loop; - raise notice 'should get here'; -end$$; - --- continue to an outer while -do $$ -declare i int := 0; -begin - <> - while i < 2 loop - raise notice 'outermostwhile, i = %', i; - i := i + 1; - <> - while 1 > 0 loop - <> - while 1 > 0 loop - continue outermostwhile; - raise notice 'should not get here'; - end loop; - raise notice 'should not get here, either'; - end loop; - raise notice 'nor here'; - end loop; - raise notice 'out of outermostwhile, i = %', i; -end$$; - --- return out of a while -create function return_from_while() returns int language plpgsql as $$ -declare i int := 0; -begin - while i < 10 loop - if i > 2 then - return i; - end if; - i := i + 1; - end loop; - return null; -end$$; - -select return_from_while(); - --- using list of scalars in fori and fore stmts -create function for_vect() returns void as $proc$ -<>declare a integer; b varchar; c varchar; r record; -begin - -- fori - for i in 1 .. 3 loop - raise notice '%', i; - end loop; - -- fore with record var - for r in select gs as aa, 'BB' as bb, 'CC' as cc from generate_series(1,4) gs loop - raise notice '% % %', r.aa, r.bb, r.cc; - end loop; - -- fore with single scalar - for a in select gs from generate_series(1,4) gs loop - raise notice '%', a; - end loop; - -- fore with multiple scalars - for a,b,c in select gs, 'BB','CC' from generate_series(1,4) gs loop - raise notice '% % %', a, b, c; - end loop; - -- using qualified names in fors, fore is enabled, disabled only for fori - for lbl.a, lbl.b, lbl.c in execute $$select gs, 'bb','cc' from generate_series(1,4) gs$$ loop - raise notice '% % %', a, b, c; - end loop; -end; -$proc$ language plpgsql; - -select for_vect(); - --- CASE statement - -create or replace function case_test(bigint) returns text as $$ -declare a int = 10; - b int = 1; -begin - case $1 - when 1 then - return 'one'; - when 2 then - return 'two'; - when 3,4,3+5 then - return 'three, four or eight'; - when a then - return 'ten'; - when a+b, a+b+1 then - return 'eleven, twelve'; - end case; -end; -$$ language plpgsql immutable; - -select case_test(1); -select case_test(2); -select case_test(3); -select case_test(4); -select case_test(5); -- fails -select case_test(8); -select case_test(10); -select case_test(11); -select case_test(12); -select case_test(13); -- fails - -create or replace function catch() returns void as $$ -begin - raise notice '%', case_test(6); -exception - when case_not_found then - raise notice 'caught case_not_found % %', SQLSTATE, SQLERRM; -end -$$ language plpgsql; - -select catch(); - --- test the searched variant too, as well as ELSE -create or replace function case_test(bigint) returns text as $$ -declare a int = 10; -begin - case - when $1 = 1 then - return 'one'; - when $1 = a + 2 then - return 'twelve'; - else - return 'other'; - end case; -end; -$$ language plpgsql immutable; - -select case_test(1); -select case_test(2); -select case_test(12); -select case_test(13); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_copy.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_copy.sql deleted file mode 100644 index 37f1fa132b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_copy.sql +++ /dev/null @@ -1,58 +0,0 @@ --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR -\getenv abs_builddir PG_ABS_BUILDDIR - --- set up file names to use -\set srcfilename :abs_srcdir '/data/copy1.data' -\set destfilename :abs_builddir '/results/copy1.data' - -CREATE TABLE copy1 (a int, b float); - --- COPY TO/FROM not authorized from client. -DO LANGUAGE plpgsql $$ -BEGIN - COPY copy1 TO stdout; -END; -$$; -DO LANGUAGE plpgsql $$ -BEGIN - COPY copy1 FROM stdin; -END; -$$; -DO LANGUAGE plpgsql $$ -BEGIN - EXECUTE 'COPY copy1 TO stdout'; -END; -$$; -DO LANGUAGE plpgsql $$ -BEGIN - EXECUTE 'COPY copy1 FROM stdin'; -END; -$$; - --- Valid cases --- COPY FROM -\set dobody 'BEGIN COPY copy1 FROM ' :'srcfilename' '; END' -DO LANGUAGE plpgsql :'dobody'; -SELECT * FROM copy1 ORDER BY 1; -TRUNCATE copy1; -\set cmd 'COPY copy1 FROM ' :'srcfilename' -\set dobody 'BEGIN EXECUTE ' :'cmd' '; END' -DO LANGUAGE plpgsql :'dobody'; -SELECT * FROM copy1 ORDER BY 1; - --- COPY TO --- Copy the data externally once, then process it back to the table. -\set dobody 'BEGIN COPY copy1 TO ' :'destfilename' '; END' -DO LANGUAGE plpgsql :'dobody'; -TRUNCATE copy1; -\set dobody 'BEGIN COPY copy1 FROM ' :'destfilename' '; END' -DO LANGUAGE plpgsql :'dobody'; - -\set cmd 'COPY copy1 FROM ' :'destfilename' -\set dobody 'BEGIN EXECUTE ' :'cmd' '; END' -DO LANGUAGE plpgsql :'dobody'; - -SELECT * FROM copy1 ORDER BY 1; - -DROP TABLE copy1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_domain.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_domain.sql deleted file mode 100644 index 8f99aae5a9..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_domain.sql +++ /dev/null @@ -1,279 +0,0 @@ --- --- Tests for PL/pgSQL's behavior with domain types --- - -CREATE DOMAIN booltrue AS bool CHECK (VALUE IS TRUE OR VALUE IS NULL); - -CREATE FUNCTION test_argresult_booltrue(x booltrue, y bool) RETURNS booltrue AS $$ -begin -return y; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_argresult_booltrue(true, true); -SELECT * FROM test_argresult_booltrue(false, true); -SELECT * FROM test_argresult_booltrue(true, false); - -CREATE FUNCTION test_assign_booltrue(x bool, y bool) RETURNS booltrue AS $$ -declare v booltrue := x; -begin -v := y; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_booltrue(true, true); -SELECT * FROM test_assign_booltrue(false, true); -SELECT * FROM test_assign_booltrue(true, false); - - -CREATE DOMAIN uint2 AS int2 CHECK (VALUE >= 0); - -CREATE FUNCTION test_argresult_uint2(x uint2, y int) RETURNS uint2 AS $$ -begin -return y; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_argresult_uint2(100::uint2, 50); -SELECT * FROM test_argresult_uint2(100::uint2, -50); -SELECT * FROM test_argresult_uint2(null, 1); - -CREATE FUNCTION test_assign_uint2(x int, y int) RETURNS uint2 AS $$ -declare v uint2 := x; -begin -v := y; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_uint2(100, 50); -SELECT * FROM test_assign_uint2(100, -50); -SELECT * FROM test_assign_uint2(-100, 50); -SELECT * FROM test_assign_uint2(null, 1); - - -CREATE DOMAIN nnint AS int NOT NULL; - -CREATE FUNCTION test_argresult_nnint(x nnint, y int) RETURNS nnint AS $$ -begin -return y; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_argresult_nnint(10, 20); -SELECT * FROM test_argresult_nnint(null, 20); -SELECT * FROM test_argresult_nnint(10, null); - -CREATE FUNCTION test_assign_nnint(x int, y int) RETURNS nnint AS $$ -declare v nnint := x; -begin -v := y; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_nnint(10, 20); -SELECT * FROM test_assign_nnint(null, 20); -SELECT * FROM test_assign_nnint(10, null); - - --- --- Domains over arrays --- - -CREATE DOMAIN ordered_pair_domain AS integer[] CHECK (array_length(VALUE,1)=2 AND VALUE[1] < VALUE[2]); - -CREATE FUNCTION test_argresult_array_domain(x ordered_pair_domain) - RETURNS ordered_pair_domain AS $$ -begin -return x; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_argresult_array_domain(ARRAY[0, 100]::ordered_pair_domain); -SELECT * FROM test_argresult_array_domain(NULL::ordered_pair_domain); - -CREATE FUNCTION test_argresult_array_domain_check_violation() - RETURNS ordered_pair_domain AS $$ -begin -return array[2,1]; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_argresult_array_domain_check_violation(); - -CREATE FUNCTION test_assign_ordered_pair_domain(x int, y int, z int) RETURNS ordered_pair_domain AS $$ -declare v ordered_pair_domain := array[x, y]; -begin -v[2] := z; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_ordered_pair_domain(1,2,3); -SELECT * FROM test_assign_ordered_pair_domain(1,2,0); -SELECT * FROM test_assign_ordered_pair_domain(2,1,3); - - --- --- Arrays of domains --- - -CREATE FUNCTION test_read_uint2_array(x uint2[]) RETURNS uint2 AS $$ -begin -return x[1]; -end -$$ LANGUAGE plpgsql; - -select test_read_uint2_array(array[1::uint2]); - -CREATE FUNCTION test_build_uint2_array(x int2) RETURNS uint2[] AS $$ -begin -return array[x, x]; -end -$$ LANGUAGE plpgsql; - -select test_build_uint2_array(1::int2); -select test_build_uint2_array(-1::int2); -- fail - -CREATE FUNCTION test_argresult_domain_array(x integer[]) - RETURNS ordered_pair_domain[] AS $$ -begin -return array[x::ordered_pair_domain, x::ordered_pair_domain]; -end -$$ LANGUAGE plpgsql; - -select test_argresult_domain_array(array[2,4]); -select test_argresult_domain_array(array[4,2]); -- fail - -CREATE FUNCTION test_argresult_domain_array2(x ordered_pair_domain) - RETURNS integer AS $$ -begin -return x[1]; -end -$$ LANGUAGE plpgsql; - -select test_argresult_domain_array2(array[2,4]); -select test_argresult_domain_array2(array[4,2]); -- fail - -CREATE FUNCTION test_argresult_array_domain_array(x ordered_pair_domain[]) - RETURNS ordered_pair_domain AS $$ -begin -return x[1]; -end -$$ LANGUAGE plpgsql; - -select test_argresult_array_domain_array(array[array[2,4]::ordered_pair_domain]); - - --- --- Domains within composite --- - -CREATE TYPE nnint_container AS (f1 int, f2 nnint); - -CREATE FUNCTION test_result_nnint_container(x int, y int) - RETURNS nnint_container AS $$ -begin -return row(x, y)::nnint_container; -end -$$ LANGUAGE plpgsql; - -SELECT test_result_nnint_container(null, 3); -SELECT test_result_nnint_container(3, null); -- fail - -CREATE FUNCTION test_assign_nnint_container(x int, y int, z int) - RETURNS nnint_container AS $$ -declare v nnint_container := row(x, y); -begin -v.f2 := z; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_nnint_container(1,2,3); -SELECT * FROM test_assign_nnint_container(1,2,null); -SELECT * FROM test_assign_nnint_container(1,null,3); - --- Since core system allows this: -SELECT null::nnint_container; --- so should PL/PgSQL - -CREATE FUNCTION test_assign_nnint_container2(x int, y int, z int) - RETURNS nnint_container AS $$ -declare v nnint_container; -begin -v.f2 := z; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_nnint_container2(1,2,3); -SELECT * FROM test_assign_nnint_container2(1,2,null); - - --- --- Domains of composite --- - -CREATE TYPE named_pair AS ( - i integer, - j integer -); - -CREATE DOMAIN ordered_named_pair AS named_pair CHECK((VALUE).i <= (VALUE).j); - -CREATE FUNCTION read_ordered_named_pair(p ordered_named_pair) RETURNS integer AS $$ -begin -return p.i + p.j; -end -$$ LANGUAGE plpgsql; - -SELECT read_ordered_named_pair(row(1, 2)); -SELECT read_ordered_named_pair(row(2, 1)); -- fail - -CREATE FUNCTION build_ordered_named_pair(i int, j int) RETURNS ordered_named_pair AS $$ -begin -return row(i, j); -end -$$ LANGUAGE plpgsql; - -SELECT build_ordered_named_pair(1,2); -SELECT build_ordered_named_pair(2,1); -- fail - -CREATE FUNCTION test_assign_ordered_named_pair(x int, y int, z int) - RETURNS ordered_named_pair AS $$ -declare v ordered_named_pair := row(x, y); -begin -v.j := z; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_ordered_named_pair(1,2,3); -SELECT * FROM test_assign_ordered_named_pair(1,2,0); -SELECT * FROM test_assign_ordered_named_pair(2,1,3); - -CREATE FUNCTION build_ordered_named_pairs(i int, j int) RETURNS ordered_named_pair[] AS $$ -begin -return array[row(i, j), row(i, j+1)]; -end -$$ LANGUAGE plpgsql; - -SELECT build_ordered_named_pairs(1,2); -SELECT build_ordered_named_pairs(2,1); -- fail - -CREATE FUNCTION test_assign_ordered_named_pairs(x int, y int, z int) - RETURNS ordered_named_pair[] AS $$ -declare v ordered_named_pair[] := array[row(x, y)]; -begin --- ideally this would work, but it doesn't yet: --- v[1].j := z; -return v; -end -$$ LANGUAGE plpgsql; - -SELECT * FROM test_assign_ordered_named_pairs(1,2,3); -SELECT * FROM test_assign_ordered_named_pairs(2,1,3); -SELECT * FROM test_assign_ordered_named_pairs(1,2,0); -- should fail someday diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_record.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_record.sql deleted file mode 100644 index 535a3407a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_record.sql +++ /dev/null @@ -1,520 +0,0 @@ --- --- Tests for PL/pgSQL handling of composite (record) variables --- - -create type two_int4s as (f1 int4, f2 int4); -create type two_int8s as (q1 int8, q2 int8); -create type nested_int8s as (c1 two_int8s, c2 two_int8s); - --- base-case return of a composite type -create function retc(int) returns two_int8s language plpgsql as -$$ begin return row($1,1)::two_int8s; end $$; -select retc(42); - --- ok to return a matching record type -create or replace function retc(int) returns two_int8s language plpgsql as -$$ begin return row($1::int8, 1::int8); end $$; -select retc(42); - --- we don't currently support implicit casting -create or replace function retc(int) returns two_int8s language plpgsql as -$$ begin return row($1,1); end $$; -select retc(42); - --- nor extra columns -create or replace function retc(int) returns two_int8s language plpgsql as -$$ begin return row($1::int8, 1::int8, 42); end $$; -select retc(42); - --- same cases with an intermediate "record" variable -create or replace function retc(int) returns two_int8s language plpgsql as -$$ declare r record; begin r := row($1::int8, 1::int8); return r; end $$; -select retc(42); - -create or replace function retc(int) returns two_int8s language plpgsql as -$$ declare r record; begin r := row($1,1); return r; end $$; -select retc(42); - -create or replace function retc(int) returns two_int8s language plpgsql as -$$ declare r record; begin r := row($1::int8, 1::int8, 42); return r; end $$; -select retc(42); - --- but, for mostly historical reasons, we do convert when assigning --- to a named-composite-type variable -create or replace function retc(int) returns two_int8s language plpgsql as -$$ declare r two_int8s; begin r := row($1::int8, 1::int8, 42); return r; end $$; -select retc(42); - -do $$ declare c two_int8s; -begin c := row(1,2); raise notice 'c = %', c; end$$; - -do $$ declare c two_int8s; -begin for c in select 1,2 loop raise notice 'c = %', c; end loop; end$$; - -do $$ declare c4 two_int4s; c8 two_int8s; -begin - c8 := row(1,2); - c4 := c8; - c8 := c4; - raise notice 'c4 = %', c4; - raise notice 'c8 = %', c8; -end$$; - -do $$ declare c two_int8s; d nested_int8s; -begin - c := row(1,2); - d := row(c, row(c.q1, c.q2+1)); - raise notice 'c = %, d = %', c, d; - c.q1 := 10; - d.c1 := row(11,12); - d.c2.q2 := 42; - raise notice 'c = %, d = %', c, d; - raise notice 'c.q1 = %, d.c2 = %', c.q1, d.c2; - raise notice '(d).c2.q2 = %', (d).c2.q2; -- doesn't work without parens - raise notice '(d.c2).q2 = %', (d.c2).q2; -- doesn't work without parens -end$$; - --- block-qualified naming -do $$ <> declare c two_int8s; d nested_int8s; -begin - b.c := row(1,2); - b.d := row(b.c, row(b.c.q1, b.c.q2+1)); - raise notice 'b.c = %, b.d = %', b.c, b.d; - b.c.q1 := 10; - b.d.c1 := row(11,12); - b.d.c2.q2 := 42; - raise notice 'b.c = %, b.d = %', b.c, b.d; - raise notice 'b.c.q1 = %, b.d.c2 = %', b.c.q1, b.d.c2; - raise notice '(b.d).c2.q2 = %', (b.d).c2.q2; -- doesn't work without parens - raise notice '(b.d.c2).q2 = %', (b.d.c2).q2; -- doesn't work without parens -end$$; - --- error cases -do $$ declare c two_int8s; begin c.x = 1; end $$; -do $$ declare c nested_int8s; begin c.x = 1; end $$; -do $$ declare c nested_int8s; begin c.x.q1 = 1; end $$; -do $$ declare c nested_int8s; begin c.c2.x = 1; end $$; -do $$ declare c nested_int8s; begin d.c2.x = 1; end $$; -do $$ <> declare c two_int8s; begin b.c.x = 1; end $$; -do $$ <> declare c nested_int8s; begin b.c.x = 1; end $$; -do $$ <> declare c nested_int8s; begin b.c.x.q1 = 1; end $$; -do $$ <> declare c nested_int8s; begin b.c.c2.x = 1; end $$; -do $$ <> declare c nested_int8s; begin b.d.c2.x = 1; end $$; - --- check passing composite result to another function -create function getq1(two_int8s) returns int8 language plpgsql as $$ -declare r two_int8s; begin r := $1; return r.q1; end $$; - -select getq1(retc(344)); -select getq1(row(1,2)); - -do $$ -declare r1 two_int8s; r2 record; x int8; -begin - r1 := retc(345); - perform getq1(r1); - x := getq1(r1); - raise notice 'x = %', x; - r2 := retc(346); - perform getq1(r2); - x := getq1(r2); - raise notice 'x = %', x; -end$$; - --- check assignments of composites -do $$ -declare r1 two_int8s; r2 two_int8s; r3 record; r4 record; -begin - r1 := row(1,2); - raise notice 'r1 = %', r1; - r1 := r1; -- shouldn't do anything - raise notice 'r1 = %', r1; - r2 := r1; - raise notice 'r1 = %', r1; - raise notice 'r2 = %', r2; - r2.q2 = r1.q1 + 3; -- check that r2 has distinct storage - raise notice 'r1 = %', r1; - raise notice 'r2 = %', r2; - r1 := null; - raise notice 'r1 = %', r1; - raise notice 'r2 = %', r2; - r1 := row(7,11)::two_int8s; - r2 := r1; - raise notice 'r1 = %', r1; - raise notice 'r2 = %', r2; - r3 := row(1,2); - r4 := r3; - raise notice 'r3 = %', r3; - raise notice 'r4 = %', r4; - r4.f1 := r4.f1 + 3; -- check that r4 has distinct storage - raise notice 'r3 = %', r3; - raise notice 'r4 = %', r4; - r1 := r3; - raise notice 'r1 = %', r1; - r4 := r1; - raise notice 'r4 = %', r4; - r4.q2 := r4.q2 + 1; -- r4's field names have changed - raise notice 'r4 = %', r4; -end$$; - --- fields of named-type vars read as null if uninitialized -do $$ -declare r1 two_int8s; -begin - raise notice 'r1 = %', r1; - raise notice 'r1.q1 = %', r1.q1; - raise notice 'r1.q2 = %', r1.q2; - raise notice 'r1 = %', r1; -end$$; - -do $$ -declare r1 two_int8s; -begin - raise notice 'r1.q1 = %', r1.q1; - raise notice 'r1.q2 = %', r1.q2; - raise notice 'r1 = %', r1; - raise notice 'r1.nosuchfield = %', r1.nosuchfield; -end$$; - --- records, not so much -do $$ -declare r1 record; -begin - raise notice 'r1 = %', r1; - raise notice 'r1.f1 = %', r1.f1; - raise notice 'r1.f2 = %', r1.f2; - raise notice 'r1 = %', r1; -end$$; - --- but OK if you assign first -do $$ -declare r1 record; -begin - raise notice 'r1 = %', r1; - r1 := row(1,2); - raise notice 'r1.f1 = %', r1.f1; - raise notice 'r1.f2 = %', r1.f2; - raise notice 'r1 = %', r1; - raise notice 'r1.nosuchfield = %', r1.nosuchfield; -end$$; - --- check repeated assignments to composite fields -create table some_table (id int, data text); - -do $$ -declare r some_table; -begin - r := (23, 'skidoo'); - for i in 1 .. 10 loop - r.id := r.id + i; - r.data := r.data || ' ' || i; - end loop; - raise notice 'r = %', r; -end$$; - --- check behavior of function declared to return "record" - -create function returnsrecord(int) returns record language plpgsql as -$$ begin return row($1,$1+1); end $$; - -select returnsrecord(42); -select * from returnsrecord(42) as r(x int, y int); -select * from returnsrecord(42) as r(x int, y int, z int); -- fail -select * from returnsrecord(42) as r(x int, y bigint); -- fail - --- same with an intermediate record variable -create or replace function returnsrecord(int) returns record language plpgsql as -$$ declare r record; begin r := row($1,$1+1); return r; end $$; - -select returnsrecord(42); -select * from returnsrecord(42) as r(x int, y int); -select * from returnsrecord(42) as r(x int, y int, z int); -- fail -select * from returnsrecord(42) as r(x int, y bigint); -- fail - --- should work the same with a missing column in the actual result value -create table has_hole(f1 int, f2 int, f3 int); -alter table has_hole drop column f2; - -create or replace function returnsrecord(int) returns record language plpgsql as -$$ begin return row($1,$1+1)::has_hole; end $$; - -select returnsrecord(42); -select * from returnsrecord(42) as r(x int, y int); -select * from returnsrecord(42) as r(x int, y int, z int); -- fail -select * from returnsrecord(42) as r(x int, y bigint); -- fail - --- same with an intermediate record variable -create or replace function returnsrecord(int) returns record language plpgsql as -$$ declare r record; begin r := row($1,$1+1)::has_hole; return r; end $$; - -select returnsrecord(42); -select * from returnsrecord(42) as r(x int, y int); -select * from returnsrecord(42) as r(x int, y int, z int); -- fail -select * from returnsrecord(42) as r(x int, y bigint); -- fail - --- check access to a field of an argument declared "record" -create function getf1(x record) returns int language plpgsql as -$$ begin return x.f1; end $$; -select getf1(1); -select getf1(row(1,2)); --- the context stack is different when debug_discard_caches --- is set, so suppress context output -\set SHOW_CONTEXT never -select getf1(row(1,2)::two_int8s); -\set SHOW_CONTEXT errors -select getf1(row(1,2)); - --- check behavior when assignment to FOR-loop variable requires coercion -do $$ -declare r two_int8s; -begin - for r in select i, i+1 from generate_series(1,4) i - loop - raise notice 'r = %', r; - end loop; -end$$; - --- check behavior when returning setof composite -create function returnssetofholes() returns setof has_hole language plpgsql as -$$ -declare r record; - h has_hole; -begin - return next h; - r := (1,2); - h := (3,4); - return next r; - return next h; - return next row(5,6); - return next row(7,8)::has_hole; -end$$; -select returnssetofholes(); - -create or replace function returnssetofholes() returns setof has_hole language plpgsql as -$$ -declare r record; -begin - return next r; -- fails, not assigned yet -end$$; -select returnssetofholes(); - -create or replace function returnssetofholes() returns setof has_hole language plpgsql as -$$ -begin - return next row(1,2,3); -- fails -end$$; -select returnssetofholes(); - --- check behavior with changes of a named rowtype -create table mutable(f1 int, f2 text); - -create function sillyaddone(int) returns int language plpgsql as -$$ declare r mutable; begin r.f1 := $1; return r.f1 + 1; end $$; -select sillyaddone(42); - --- test for change of type of column f1 should be here someday; --- for now see plpgsql_cache test - -alter table mutable drop column f1; --- the context stack is different when debug_discard_caches --- is set, so suppress context output -\set SHOW_CONTEXT never -select sillyaddone(42); -- fail -\set SHOW_CONTEXT errors - -create function getf3(x mutable) returns int language plpgsql as -$$ begin return x.f3; end $$; -select getf3(null::mutable); -- doesn't work yet -alter table mutable add column f3 int; -select getf3(null::mutable); -- now it works -alter table mutable drop column f3; --- the context stack is different when debug_discard_caches --- is set, so suppress context output -\set SHOW_CONTEXT never -select getf3(null::mutable); -- fails again -\set SHOW_CONTEXT errors - --- check behavior with creating/dropping a named rowtype -set check_function_bodies = off; -- else reference to nonexistent type fails - -create function sillyaddtwo(int) returns int language plpgsql as -$$ declare r mutable2; begin r.f1 := $1; return r.f1 + 2; end $$; - -reset check_function_bodies; - -select sillyaddtwo(42); -- fail -create table mutable2(f1 int, f2 text); -select sillyaddtwo(42); -drop table mutable2; --- the context stack is different when debug_discard_caches --- is set, so suppress context output -\set SHOW_CONTEXT never -select sillyaddtwo(42); -- fail -\set SHOW_CONTEXT errors -create table mutable2(f0 text, f1 int, f2 text); -select sillyaddtwo(42); -select sillyaddtwo(43); - --- check access to system columns in a record variable - -create function sillytrig() returns trigger language plpgsql as -$$begin - raise notice 'old.ctid = %', old.ctid; - raise notice 'old.tableoid = %', old.tableoid::regclass; - return new; -end$$; - -create trigger mutable_trig before update on mutable for each row -execute procedure sillytrig(); - -insert into mutable values ('foo'), ('bar'); -update mutable set f2 = f2 || ' baz'; -table mutable; - --- check returning a composite datum from a trigger - -create or replace function sillytrig() returns trigger language plpgsql as -$$begin - return row(new.*); -end$$; - -update mutable set f2 = f2 || ' baz'; -table mutable; - -create or replace function sillytrig() returns trigger language plpgsql as -$$declare r record; -begin - r := row(new.*); - return r; -end$$; - -update mutable set f2 = f2 || ' baz'; -table mutable; - --- --- Domains of composite --- - -create domain ordered_int8s as two_int8s check((value).q1 <= (value).q2); - -create function read_ordered_int8s(p ordered_int8s) returns int8 as $$ -begin return p.q1 + p.q2; end -$$ language plpgsql; - -select read_ordered_int8s(row(1, 2)); -select read_ordered_int8s(row(2, 1)); -- fail - -create function build_ordered_int8s(i int8, j int8) returns ordered_int8s as $$ -begin return row(i,j); end -$$ language plpgsql; - -select build_ordered_int8s(1,2); -select build_ordered_int8s(2,1); -- fail - -create function build_ordered_int8s_2(i int8, j int8) returns ordered_int8s as $$ -declare r record; begin r := row(i,j); return r; end -$$ language plpgsql; - -select build_ordered_int8s_2(1,2); -select build_ordered_int8s_2(2,1); -- fail - -create function build_ordered_int8s_3(i int8, j int8) returns ordered_int8s as $$ -declare r two_int8s; begin r := row(i,j); return r; end -$$ language plpgsql; - -select build_ordered_int8s_3(1,2); -select build_ordered_int8s_3(2,1); -- fail - -create function build_ordered_int8s_4(i int8, j int8) returns ordered_int8s as $$ -declare r ordered_int8s; begin r := row(i,j); return r; end -$$ language plpgsql; - -select build_ordered_int8s_4(1,2); -select build_ordered_int8s_4(2,1); -- fail - -create function build_ordered_int8s_a(i int8, j int8) returns ordered_int8s[] as $$ -begin return array[row(i,j), row(i,j+1)]; end -$$ language plpgsql; - -select build_ordered_int8s_a(1,2); -select build_ordered_int8s_a(2,1); -- fail - --- check field assignment -do $$ -declare r ordered_int8s; -begin - r.q1 := null; - r.q2 := 43; - r.q1 := 42; - r.q2 := 41; -- fail -end$$; - --- check whole-row assignment -do $$ -declare r ordered_int8s; -begin - r := null; - r := row(null,null); - r := row(1,2); - r := row(2,1); -- fail -end$$; - --- check assignment in for-loop -do $$ -declare r ordered_int8s; -begin - for r in values (1,2),(3,4),(6,5) loop - raise notice 'r = %', r; - end loop; -end$$; - --- check behavior with toastable fields, too - -create type two_texts as (f1 text, f2 text); -create domain ordered_texts as two_texts check((value).f1 <= (value).f2); - -create table sometable (id int, a text, b text); --- b should be compressed, but in-line -insert into sometable values (1, 'a', repeat('ffoob',1000)); --- this b should be out-of-line -insert into sometable values (2, 'a', repeat('ffoob',100000)); --- this pair should fail the domain check -insert into sometable values (3, 'z', repeat('ffoob',100000)); - -do $$ -declare d ordered_texts; -begin - for d in select a, b from sometable loop - raise notice 'succeeded at "%"', d.f1; - end loop; -end$$; - -do $$ -declare r record; d ordered_texts; -begin - for r in select * from sometable loop - raise notice 'processing row %', r.id; - d := row(r.a, r.b); - end loop; -end$$; - -do $$ -declare r record; d ordered_texts; -begin - for r in select * from sometable loop - raise notice 'processing row %', r.id; - d := null; - d.f1 := r.a; - d.f2 := r.b; - end loop; -end$$; - --- check coercion of a record result to named-composite function output type -create function compresult(int8) returns two_int8s language plpgsql as -$$ declare r record; begin r := row($1,$1); return r; end $$; - -create table two_int8s_tab (f1 two_int8s); -insert into two_int8s_tab values (compresult(42)); --- reconnect so we lose any local knowledge of anonymous record types -\c - -table two_int8s_tab; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_simple.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_simple.sql deleted file mode 100644 index 57020d22d6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_simple.sql +++ /dev/null @@ -1,82 +0,0 @@ --- --- Tests for plpgsql's handling of "simple" expressions --- - --- Check that changes to an inline-able function are handled correctly -create function simplesql(int) returns int language sql -as 'select $1'; - -create function simplecaller() returns int language plpgsql -as $$ -declare - sum int := 0; -begin - for n in 1..10 loop - sum := sum + simplesql(n); - if n = 5 then - create or replace function simplesql(int) returns int language sql - as 'select $1 + 100'; - end if; - end loop; - return sum; -end$$; - -select simplecaller(); - - --- Check that changes in search path are dealt with correctly -create schema simple1; - -create function simple1.simpletarget(int) returns int language plpgsql -as $$begin return $1; end$$; - -create function simpletarget(int) returns int language plpgsql -as $$begin return $1 + 100; end$$; - -create or replace function simplecaller() returns int language plpgsql -as $$ -declare - sum int := 0; -begin - for n in 1..10 loop - sum := sum + simpletarget(n); - if n = 5 then - set local search_path = 'simple1'; - end if; - end loop; - return sum; -end$$; - -select simplecaller(); - --- try it with non-volatile functions, too -alter function simple1.simpletarget(int) immutable; -alter function simpletarget(int) immutable; - -select simplecaller(); - --- make sure flushing local caches changes nothing -\c - - -select simplecaller(); - - --- Check case where first attempt to determine if it's simple fails - -create function simplesql() returns int language sql -as $$select 1 / 0$$; - -create or replace function simplecaller() returns int language plpgsql -as $$ -declare x int; -begin - select simplesql() into x; - return x; -end$$; - -select simplecaller(); -- division by zero occurs during simple-expr check - -create or replace function simplesql() returns int language sql -as $$select 2 + 2$$; - -select simplecaller(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_transaction.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_transaction.sql deleted file mode 100644 index 8d76d00daa..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_transaction.sql +++ /dev/null @@ -1,637 +0,0 @@ -CREATE TABLE test1 (a int, b text); - - -CREATE PROCEDURE transaction_test1(x int, y text) -LANGUAGE plpgsql -AS $$ -BEGIN - FOR i IN 0..x LOOP - INSERT INTO test1 (a, b) VALUES (i, y); - IF i % 2 = 0 THEN - COMMIT; - ELSE - ROLLBACK; - END IF; - END LOOP; -END -$$; - -CALL transaction_test1(9, 'foo'); - -SELECT * FROM test1; - - -TRUNCATE test1; - -DO -LANGUAGE plpgsql -$$ -BEGIN - FOR i IN 0..9 LOOP - INSERT INTO test1 (a) VALUES (i); - IF i % 2 = 0 THEN - COMMIT; - ELSE - ROLLBACK; - END IF; - END LOOP; -END -$$; - -SELECT * FROM test1; - - --- transaction commands not allowed when called in transaction block -START TRANSACTION; -CALL transaction_test1(9, 'error'); -COMMIT; - -START TRANSACTION; -DO LANGUAGE plpgsql $$ BEGIN COMMIT; END $$; -COMMIT; - - -TRUNCATE test1; - --- not allowed in a function -CREATE FUNCTION transaction_test2() RETURNS int -LANGUAGE plpgsql -AS $$ -BEGIN - FOR i IN 0..9 LOOP - INSERT INTO test1 (a) VALUES (i); - IF i % 2 = 0 THEN - COMMIT; - ELSE - ROLLBACK; - END IF; - END LOOP; - RETURN 1; -END -$$; - -SELECT transaction_test2(); - -SELECT * FROM test1; - - --- also not allowed if procedure is called from a function -CREATE FUNCTION transaction_test3() RETURNS int -LANGUAGE plpgsql -AS $$ -BEGIN - CALL transaction_test1(9, 'error'); - RETURN 1; -END; -$$; - -SELECT transaction_test3(); - -SELECT * FROM test1; - - --- DO block inside function -CREATE FUNCTION transaction_test4() RETURNS int -LANGUAGE plpgsql -AS $$ -BEGIN - EXECUTE 'DO LANGUAGE plpgsql $x$ BEGIN COMMIT; END $x$'; - RETURN 1; -END; -$$; - -SELECT transaction_test4(); - - --- proconfig settings currently disallow transaction statements -CREATE PROCEDURE transaction_test5() -LANGUAGE plpgsql -SET work_mem = 555 -AS $$ -BEGIN - COMMIT; -END; -$$; - -CALL transaction_test5(); - - --- SECURITY DEFINER currently disallow transaction statements -CREATE PROCEDURE transaction_test5b() -LANGUAGE plpgsql -SECURITY DEFINER -AS $$ -BEGIN - COMMIT; -END; -$$; - -CALL transaction_test5b(); - - -TRUNCATE test1; - --- nested procedure calls -CREATE PROCEDURE transaction_test6(c text) -LANGUAGE plpgsql -AS $$ -BEGIN - CALL transaction_test1(9, c); -END; -$$; - -CALL transaction_test6('bar'); - -SELECT * FROM test1; - -TRUNCATE test1; - -CREATE PROCEDURE transaction_test7() -LANGUAGE plpgsql -AS $$ -BEGIN - DO 'BEGIN CALL transaction_test1(9, $x$baz$x$); END;'; -END; -$$; - -CALL transaction_test7(); - -SELECT * FROM test1; - -CREATE PROCEDURE transaction_test8() -LANGUAGE plpgsql -AS $$ -BEGIN - EXECUTE 'CALL transaction_test1(10, $x$baz$x$)'; -END; -$$; - -CALL transaction_test8(); - - --- commit inside cursor loop -CREATE TABLE test2 (x int); -INSERT INTO test2 VALUES (0), (1), (2), (3), (4); - -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -DECLARE - r RECORD; -BEGIN - FOR r IN SELECT * FROM test2 ORDER BY x LOOP - INSERT INTO test1 (a) VALUES (r.x); - COMMIT; - END LOOP; -END; -$$; - -SELECT * FROM test1; - --- check that this doesn't leak a holdable portal -SELECT * FROM pg_cursors; - - --- error in cursor loop with commit -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -DECLARE - r RECORD; -BEGIN - FOR r IN SELECT * FROM test2 ORDER BY x LOOP - INSERT INTO test1 (a) VALUES (12/(r.x-2)); - COMMIT; - END LOOP; -END; -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -DECLARE - r RECORD; -BEGIN - FOR r IN SELECT * FROM test2 ORDER BY x LOOP - INSERT INTO test1 (a) VALUES (r.x); - ROLLBACK; - END LOOP; -END; -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- first commit then rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -DECLARE - r RECORD; -BEGIN - FOR r IN SELECT * FROM test2 ORDER BY x LOOP - INSERT INTO test1 (a) VALUES (r.x); - IF r.x % 2 = 0 THEN - COMMIT; - ELSE - ROLLBACK; - END IF; - END LOOP; -END; -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -DECLARE - r RECORD; -BEGIN - FOR r IN UPDATE test2 SET x = x * 2 RETURNING x LOOP - INSERT INTO test1 (a) VALUES (r.x); - ROLLBACK; - END LOOP; -END; -$$; - -SELECT * FROM test1; -SELECT * FROM test2; - -SELECT * FROM pg_cursors; - - --- interaction of FOR UPDATE cursor with subsequent updates (bug #17050) -TRUNCATE test1; - -INSERT INTO test1 VALUES (1,'one'), (2,'two'), (3,'three'); - -DO LANGUAGE plpgsql $$ -DECLARE - l_cur CURSOR FOR SELECT a FROM test1 ORDER BY 1 FOR UPDATE; -BEGIN - FOR r IN l_cur LOOP - UPDATE test1 SET b = b || ' ' || b WHERE a = r.a; - COMMIT; - END LOOP; -END; -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- like bug #17050, but with implicit cursor -TRUNCATE test1; - -INSERT INTO test1 VALUES (1,'one'), (2,'two'), (3,'three'); - -DO LANGUAGE plpgsql $$ -DECLARE r RECORD; -BEGIN - FOR r IN SELECT a FROM test1 FOR UPDATE LOOP - UPDATE test1 SET b = b || ' ' || b WHERE a = r.a; - COMMIT; - END LOOP; -END; -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- commit inside block with exception handler -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -BEGIN - BEGIN - INSERT INTO test1 (a) VALUES (1); - COMMIT; - INSERT INTO test1 (a) VALUES (1/0); - COMMIT; - EXCEPTION - WHEN division_by_zero THEN - RAISE NOTICE 'caught division_by_zero'; - END; -END; -$$; - -SELECT * FROM test1; - - --- rollback inside block with exception handler -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -BEGIN - BEGIN - INSERT INTO test1 (a) VALUES (1); - ROLLBACK; - INSERT INTO test1 (a) VALUES (1/0); - ROLLBACK; - EXCEPTION - WHEN division_by_zero THEN - RAISE NOTICE 'caught division_by_zero'; - END; -END; -$$; - -SELECT * FROM test1; - - --- test commit/rollback inside exception handler, too -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -BEGIN - FOR i IN 1..10 LOOP - BEGIN - INSERT INTO test1 VALUES (i, 'good'); - INSERT INTO test1 VALUES (i/0, 'bad'); - EXCEPTION - WHEN division_by_zero THEN - INSERT INTO test1 VALUES (i, 'exception'); - IF (i % 3) > 0 THEN COMMIT; ELSE ROLLBACK; END IF; - END; - END LOOP; -END; -$$; - -SELECT * FROM test1; - - --- detoast result of simple expression after commit -CREATE TEMP TABLE test4(f1 text); -ALTER TABLE test4 ALTER COLUMN f1 SET STORAGE EXTERNAL; -- disable compression -INSERT INTO test4 SELECT repeat('xyzzy', 2000); - --- immutable mark is a bit of a lie, but it serves to make call a simple expr --- that will return a still-toasted value -CREATE FUNCTION data_source(i int) RETURNS TEXT LANGUAGE sql -AS 'select f1 from test4' IMMUTABLE; - -DO $$ -declare x text; -begin - for i in 1..3 loop - x := data_source(i); - commit; - end loop; - raise notice 'length(x) = %', length(x); -end $$; - - --- operations on composite types vs. internal transactions -DO LANGUAGE plpgsql $$ -declare - c test1 := row(42, 'hello'); - r bool; -begin - for i in 1..3 loop - r := c is not null; - raise notice 'r = %', r; - commit; - end loop; - for i in 1..3 loop - r := c is null; - raise notice 'r = %', r; - rollback; - end loop; -end -$$; - - --- COMMIT failures -DO LANGUAGE plpgsql $$ -BEGIN - CREATE TABLE test3 (y int UNIQUE DEFERRABLE INITIALLY DEFERRED); - COMMIT; - INSERT INTO test3 (y) VALUES (1); - COMMIT; - INSERT INTO test3 (y) VALUES (1); - INSERT INTO test3 (y) VALUES (2); - COMMIT; - INSERT INTO test3 (y) VALUES (3); -- won't get here -END; -$$; - -SELECT * FROM test3; - --- failure while trying to persist a cursor across a transaction (bug #15703) -CREATE PROCEDURE cursor_fail_during_commit() - LANGUAGE plpgsql -AS $$ - DECLARE id int; - BEGIN - FOR id IN SELECT 1/(x-1000) FROM generate_series(1,1000) x LOOP - INSERT INTO test1 VALUES(id); - COMMIT; - END LOOP; - END; -$$; - -TRUNCATE test1; - -CALL cursor_fail_during_commit(); - --- note that error occurs during first COMMIT, hence nothing is in test1 -SELECT count(*) FROM test1; - -CREATE PROCEDURE cursor_fail_during_rollback() - LANGUAGE plpgsql -AS $$ - DECLARE id int; - BEGIN - FOR id IN SELECT 1/(x-1000) FROM generate_series(1,1000) x LOOP - INSERT INTO test1 VALUES(id); - ROLLBACK; - END LOOP; - END; -$$; - -TRUNCATE test1; - -CALL cursor_fail_during_rollback(); - -SELECT count(*) FROM test1; - - --- SET TRANSACTION -DO LANGUAGE plpgsql $$ -BEGIN - PERFORM 1; - RAISE INFO '%', current_setting('transaction_isolation'); - COMMIT; - SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; - PERFORM 1; - RAISE INFO '%', current_setting('transaction_isolation'); - COMMIT; - SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; - RESET TRANSACTION ISOLATION LEVEL; - PERFORM 1; - RAISE INFO '%', current_setting('transaction_isolation'); - COMMIT; -END; -$$; - --- error cases -DO LANGUAGE plpgsql $$ -BEGIN - SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; -END; -$$; - -DO LANGUAGE plpgsql $$ -BEGIN - SAVEPOINT foo; -END; -$$; - -DO LANGUAGE plpgsql $$ -BEGIN - EXECUTE 'COMMIT'; -END; -$$; - - --- snapshot handling test -TRUNCATE test2; - -CREATE PROCEDURE transaction_test9() -LANGUAGE SQL -AS $$ -INSERT INTO test2 VALUES (42); -$$; - -DO LANGUAGE plpgsql $$ -BEGIN - ROLLBACK; - CALL transaction_test9(); -END -$$; - -SELECT * FROM test2; - - --- another snapshot handling case: argument expressions of a CALL need --- to be evaluated with an up-to-date snapshot -CREATE FUNCTION report_count() RETURNS int -STABLE LANGUAGE sql -AS $$ SELECT COUNT(*) FROM test2 $$; - -CREATE PROCEDURE transaction_test9b(cnt int) -LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'count = %', cnt; -END -$$; - -DO $$ -BEGIN - CALL transaction_test9b(report_count()); - INSERT INTO test2 VALUES(43); - CALL transaction_test9b(report_count()); -END -$$; - - --- Test transaction in procedure with output parameters. This uses a --- different portal strategy and different code paths in pquery.c. -CREATE PROCEDURE transaction_test10a(INOUT x int) -LANGUAGE plpgsql -AS $$ -BEGIN - x := x + 1; - COMMIT; -END; -$$; - -CALL transaction_test10a(10); - -CREATE PROCEDURE transaction_test10b(INOUT x int) -LANGUAGE plpgsql -AS $$ -BEGIN - x := x - 1; - ROLLBACK; -END; -$$; - -CALL transaction_test10b(10); - - --- transaction timestamp vs. statement timestamp -CREATE PROCEDURE transaction_test11() -LANGUAGE plpgsql -AS $$ -DECLARE - s1 timestamp with time zone; - s2 timestamp with time zone; - s3 timestamp with time zone; - t1 timestamp with time zone; - t2 timestamp with time zone; - t3 timestamp with time zone; -BEGIN - s1 := statement_timestamp(); - t1 := transaction_timestamp(); - ASSERT s1 = t1; - PERFORM pg_sleep(0.001); - COMMIT; - s2 := statement_timestamp(); - t2 := transaction_timestamp(); - ASSERT s2 = s1; - ASSERT t2 > t1; - PERFORM pg_sleep(0.001); - ROLLBACK; - s3 := statement_timestamp(); - t3 := transaction_timestamp(); - ASSERT s3 = s1; - ASSERT t3 > t2; -END; -$$; - -CALL transaction_test11(); - - --- transaction chain - -TRUNCATE test1; - -DO LANGUAGE plpgsql $$ -BEGIN - ROLLBACK; - SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; - FOR i IN 0..3 LOOP - RAISE INFO 'transaction_isolation = %', current_setting('transaction_isolation'); - INSERT INTO test1 (a) VALUES (i); - IF i % 2 = 0 THEN - COMMIT AND CHAIN; - ELSE - ROLLBACK AND CHAIN; - END IF; - END LOOP; -END -$$; - -SELECT * FROM test1; - - -DROP TABLE test1; -DROP TABLE test2; -DROP TABLE test3; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_trap.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_trap.sql deleted file mode 100644 index c6c1ad894b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_trap.sql +++ /dev/null @@ -1,175 +0,0 @@ --- --- Test error trapping --- - -create function trap_zero_divide(int) returns int as $$ -declare x int; - sx smallint; -begin - begin -- start a subtransaction - raise notice 'should see this'; - x := 100 / $1; - raise notice 'should see this only if % <> 0', $1; - sx := $1; - raise notice 'should see this only if % fits in smallint', $1; - if $1 < 0 then - raise exception '% is less than zero', $1; - end if; - exception - when division_by_zero then - raise notice 'caught division_by_zero'; - x := -1; - when NUMERIC_VALUE_OUT_OF_RANGE then - raise notice 'caught numeric_value_out_of_range'; - x := -2; - end; - return x; -end$$ language plpgsql; - -select trap_zero_divide(50); -select trap_zero_divide(0); -select trap_zero_divide(100000); -select trap_zero_divide(-100); - -create table match_source as - select x as id, x*10 as data, x/10 as ten from generate_series(1,100) x; - -create function trap_matching_test(int) returns int as $$ -declare x int; - sx smallint; - y int; -begin - begin -- start a subtransaction - x := 100 / $1; - sx := $1; - select into y data from match_source where id = - (select id from match_source b where ten = $1); - exception - when data_exception then -- category match - raise notice 'caught data_exception'; - x := -1; - when NUMERIC_VALUE_OUT_OF_RANGE OR CARDINALITY_VIOLATION then - raise notice 'caught numeric_value_out_of_range or cardinality_violation'; - x := -2; - end; - return x; -end$$ language plpgsql; - -select trap_matching_test(50); -select trap_matching_test(0); -select trap_matching_test(100000); -select trap_matching_test(1); - -create temp table foo (f1 int); - -create function subxact_rollback_semantics() returns int as $$ -declare x int; -begin - x := 1; - insert into foo values(x); - begin - x := x + 1; - insert into foo values(x); - raise exception 'inner'; - exception - when others then - x := x * 10; - end; - insert into foo values(x); - return x; -end$$ language plpgsql; - -select subxact_rollback_semantics(); -select * from foo; -drop table foo; - -create function trap_timeout() returns void as $$ -begin - declare x int; - begin - -- we assume this will take longer than 1 second: - select count(*) into x from generate_series(1, 1000000000000); - exception - when others then - raise notice 'caught others?'; - when query_canceled then - raise notice 'nyeah nyeah, can''t stop me'; - end; - -- Abort transaction to abandon the statement_timeout setting. Otherwise, - -- the next top-level statement would be vulnerable to the timeout. - raise exception 'end of function'; -end$$ language plpgsql; - -begin; -set statement_timeout to 1000; -select trap_timeout(); -rollback; - --- Test for pass-by-ref values being stored in proper context -create function test_variable_storage() returns text as $$ -declare x text; -begin - x := '1234'; - begin - x := x || '5678'; - -- force error inside subtransaction SPI context - perform trap_zero_divide(-100); - exception - when others then - x := x || '9012'; - end; - return x; -end$$ language plpgsql; - -select test_variable_storage(); - --- --- test foreign key error trapping --- - -create temp table root(f1 int primary key); - -create temp table leaf(f1 int references root deferrable); - -insert into root values(1); -insert into leaf values(1); -insert into leaf values(2); -- fails - -create function trap_foreign_key(int) returns int as $$ -begin - begin -- start a subtransaction - insert into leaf values($1); - exception - when foreign_key_violation then - raise notice 'caught foreign_key_violation'; - return 0; - end; - return 1; -end$$ language plpgsql; - -create function trap_foreign_key_2() returns int as $$ -begin - begin -- start a subtransaction - set constraints all immediate; - exception - when foreign_key_violation then - raise notice 'caught foreign_key_violation'; - return 0; - end; - return 1; -end$$ language plpgsql; - -select trap_foreign_key(1); -select trap_foreign_key(2); -- detects FK violation - -begin; - set constraints all deferred; - select trap_foreign_key(2); -- should not detect FK violation - savepoint x; - set constraints all immediate; -- fails - rollback to x; - select trap_foreign_key_2(); -- detects FK violation -commit; -- still fails - -drop function trap_foreign_key(int); -drop function trap_foreign_key_2(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_trigger.sql deleted file mode 100644 index e04c273c51..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpgsql%2Fsrc%2Fsql%2Fplpgsql_trigger.sql +++ /dev/null @@ -1,24 +0,0 @@ --- Simple test to verify accessibility of the OLD and NEW trigger variables - -create table testtr (a int, b text); - -create function testtr_trigger() returns trigger language plpgsql as -$$begin - raise notice 'tg_op = %', tg_op; - raise notice 'old(%) = %', old.a, row(old.*); - raise notice 'new(%) = %', new.a, row(new.*); - if (tg_op = 'DELETE') then - return old; - else - return new; - end if; -end$$; - -create trigger testtr_trigger before insert or delete or update on testtr - for each row execute function testtr_trigger(); - -insert into testtr values (1, 'one'), (2, 'two'); - -update testtr set a = a + 1; - -delete from testtr; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_call.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_call.sql deleted file mode 100644 index daa4bc377d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_call.sql +++ /dev/null @@ -1,80 +0,0 @@ --- --- Tests for procedures / CALL syntax --- - -CREATE PROCEDURE test_proc1() -LANGUAGE plpython3u -AS $$ -pass -$$; - -CALL test_proc1(); - - --- error: can't return non-None -CREATE PROCEDURE test_proc2() -LANGUAGE plpython3u -AS $$ -return 5 -$$; - -CALL test_proc2(); - - -CREATE TABLE test1 (a int); - -CREATE PROCEDURE test_proc3(x int) -LANGUAGE plpython3u -AS $$ -plpy.execute("INSERT INTO test1 VALUES (%s)" % x) -$$; - -CALL test_proc3(55); - -SELECT * FROM test1; - - --- output arguments - -CREATE PROCEDURE test_proc5(INOUT a text) -LANGUAGE plpython3u -AS $$ -return [a + '+' + a] -$$; - -CALL test_proc5('abc'); - - -CREATE PROCEDURE test_proc6(a int, INOUT b int, INOUT c int) -LANGUAGE plpython3u -AS $$ -return (b * a, c * a) -$$; - -CALL test_proc6(2, 3, 4); - - --- OUT parameters - -CREATE PROCEDURE test_proc9(IN a int, OUT b int) -LANGUAGE plpython3u -AS $$ -plpy.notice("a: %s" % (a)) -return (a * 2,) -$$; - -DO $$ -DECLARE _a int; _b int; -BEGIN - _a := 10; _b := 30; - CALL test_proc9(_a, _b); - RAISE NOTICE '_a: %, _b: %', _a, _b; -END -$$; - - -DROP PROCEDURE test_proc1; -DROP PROCEDURE test_proc2; -DROP PROCEDURE test_proc3; - -DROP TABLE test1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_composite.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_composite.sql deleted file mode 100644 index 21757701cc..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_composite.sql +++ /dev/null @@ -1,224 +0,0 @@ -CREATE FUNCTION multiout_simple(OUT i integer, OUT j integer) AS $$ -return (1, 2) -$$ LANGUAGE plpython3u; - -SELECT multiout_simple(); -SELECT * FROM multiout_simple(); -SELECT i, j + 2 FROM multiout_simple(); -SELECT (multiout_simple()).j + 3; - -CREATE FUNCTION multiout_simple_setof(n integer = 1, OUT integer, OUT integer) RETURNS SETOF record AS $$ -return [(1, 2)] * n -$$ LANGUAGE plpython3u; - -SELECT multiout_simple_setof(); -SELECT * FROM multiout_simple_setof(); -SELECT * FROM multiout_simple_setof(3); - -CREATE FUNCTION multiout_record_as(typ text, - first text, OUT first text, - second integer, OUT second integer, - retnull boolean) RETURNS record AS $$ -if retnull: - return None -if typ == 'dict': - return { 'first': first, 'second': second, 'additionalfield': 'must not cause trouble' } -elif typ == 'tuple': - return ( first, second ) -elif typ == 'list': - return [ first, second ] -elif typ == 'obj': - class type_record: pass - type_record.first = first - type_record.second = second - return type_record -elif typ == 'str': - return "('%s',%r)" % (first, second) -$$ LANGUAGE plpython3u; - -SELECT * FROM multiout_record_as('dict', 'foo', 1, 'f'); -SELECT multiout_record_as('dict', 'foo', 1, 'f'); - -SELECT * FROM multiout_record_as('dict', null, null, false); -SELECT * FROM multiout_record_as('dict', 'one', null, false); -SELECT * FROM multiout_record_as('dict', null, 2, false); -SELECT * FROM multiout_record_as('dict', 'three', 3, false); -SELECT * FROM multiout_record_as('dict', null, null, true); - -SELECT * FROM multiout_record_as('tuple', null, null, false); -SELECT * FROM multiout_record_as('tuple', 'one', null, false); -SELECT * FROM multiout_record_as('tuple', null, 2, false); -SELECT * FROM multiout_record_as('tuple', 'three', 3, false); -SELECT * FROM multiout_record_as('tuple', null, null, true); - -SELECT * FROM multiout_record_as('list', null, null, false); -SELECT * FROM multiout_record_as('list', 'one', null, false); -SELECT * FROM multiout_record_as('list', null, 2, false); -SELECT * FROM multiout_record_as('list', 'three', 3, false); -SELECT * FROM multiout_record_as('list', null, null, true); - -SELECT * FROM multiout_record_as('obj', null, null, false); -SELECT * FROM multiout_record_as('obj', 'one', null, false); -SELECT * FROM multiout_record_as('obj', null, 2, false); -SELECT * FROM multiout_record_as('obj', 'three', 3, false); -SELECT * FROM multiout_record_as('obj', null, null, true); - -SELECT * FROM multiout_record_as('str', 'one', 1, false); -SELECT * FROM multiout_record_as('str', 'one', 2, false); - -SELECT *, s IS NULL AS snull FROM multiout_record_as('tuple', 'xxx', NULL, 'f') AS f(f, s); -SELECT *, f IS NULL AS fnull, s IS NULL AS snull FROM multiout_record_as('tuple', 'xxx', 1, 't') AS f(f, s); -SELECT * FROM multiout_record_as('obj', NULL, 10, 'f'); - -CREATE FUNCTION multiout_setof(n integer, - OUT power_of_2 integer, - OUT length integer) RETURNS SETOF record AS $$ -for i in range(n): - power = 2 ** i - length = plpy.execute("select length('%d')" % power)[0]['length'] - yield power, length -$$ LANGUAGE plpython3u; - -SELECT * FROM multiout_setof(3); -SELECT multiout_setof(5); - -CREATE FUNCTION multiout_return_table() RETURNS TABLE (x integer, y text) AS $$ -return [{'x': 4, 'y' :'four'}, - {'x': 7, 'y' :'seven'}, - {'x': 0, 'y' :'zero'}] -$$ LANGUAGE plpython3u; - -SELECT * FROM multiout_return_table(); - -CREATE FUNCTION multiout_array(OUT integer[], OUT text) RETURNS SETOF record AS $$ -yield [[1], 'a'] -yield [[1,2], 'b'] -yield [[1,2,3], None] -$$ LANGUAGE plpython3u; - -SELECT * FROM multiout_array(); - -CREATE FUNCTION singleout_composite(OUT type_record) AS $$ -return {'first': 1, 'second': 2} -$$ LANGUAGE plpython3u; - -CREATE FUNCTION multiout_composite(OUT type_record) RETURNS SETOF type_record AS $$ -return [{'first': 1, 'second': 2}, - {'first': 3, 'second': 4 }] -$$ LANGUAGE plpython3u; - -SELECT * FROM singleout_composite(); -SELECT * FROM multiout_composite(); - --- composite OUT parameters in functions returning RECORD not supported yet -CREATE FUNCTION multiout_composite(INOUT n integer, OUT type_record) AS $$ -return (n, (n * 2, n * 3)) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION multiout_table_type_setof(typ text, returnnull boolean, INOUT n integer, OUT table_record) RETURNS SETOF record AS $$ -if returnnull: - d = None -elif typ == 'dict': - d = {'first': n * 2, 'second': n * 3, 'extra': 'not important'} -elif typ == 'tuple': - d = (n * 2, n * 3) -elif typ == 'list': - d = [ n * 2, n * 3 ] -elif typ == 'obj': - class d: pass - d.first = n * 2 - d.second = n * 3 -elif typ == 'str': - d = "(%r,%r)" % (n * 2, n * 3) -for i in range(n): - yield (i, d) -$$ LANGUAGE plpython3u; - -SELECT * FROM multiout_composite(2); -SELECT * FROM multiout_table_type_setof('dict', 'f', 3); -SELECT * FROM multiout_table_type_setof('dict', 'f', 7); -SELECT * FROM multiout_table_type_setof('tuple', 'f', 2); -SELECT * FROM multiout_table_type_setof('tuple', 'f', 3); -SELECT * FROM multiout_table_type_setof('list', 'f', 2); -SELECT * FROM multiout_table_type_setof('list', 'f', 3); -SELECT * FROM multiout_table_type_setof('obj', 'f', 4); -SELECT * FROM multiout_table_type_setof('obj', 'f', 5); -SELECT * FROM multiout_table_type_setof('str', 'f', 6); -SELECT * FROM multiout_table_type_setof('str', 'f', 7); -SELECT * FROM multiout_table_type_setof('dict', 't', 3); - --- check what happens if a type changes under us - -CREATE TABLE changing ( - i integer, - j integer -); - -CREATE FUNCTION changing_test(OUT n integer, OUT changing) RETURNS SETOF record AS $$ -return [(1, {'i': 1, 'j': 2}), - (1, (3, 4))] -$$ LANGUAGE plpython3u; - -SELECT * FROM changing_test(); -ALTER TABLE changing DROP COLUMN j; -SELECT * FROM changing_test(); -SELECT * FROM changing_test(); -ALTER TABLE changing ADD COLUMN j integer; -SELECT * FROM changing_test(); - --- tables of composite types - -CREATE FUNCTION composite_types_table(OUT tab table_record[], OUT typ type_record[] ) RETURNS SETOF record AS $$ -yield {'tab': [('first', 1), ('second', 2)], - 'typ': [{'first': 'third', 'second': 3}, - {'first': 'fourth', 'second': 4}]} -yield {'tab': [('first', 1), ('second', 2)], - 'typ': [{'first': 'third', 'second': 3}, - {'first': 'fourth', 'second': 4}]} -yield {'tab': [('first', 1), ('second', 2)], - 'typ': [{'first': 'third', 'second': 3}, - {'first': 'fourth', 'second': 4}]} -$$ LANGUAGE plpython3u; - -SELECT * FROM composite_types_table(); - --- check what happens if the output record descriptor changes -CREATE FUNCTION return_record(t text) RETURNS record AS $$ -return {'t': t, 'val': 10} -$$ LANGUAGE plpython3u; - -SELECT * FROM return_record('abc') AS r(t text, val integer); -SELECT * FROM return_record('abc') AS r(t text, val bigint); -SELECT * FROM return_record('abc') AS r(t text, val integer); -SELECT * FROM return_record('abc') AS r(t varchar(30), val integer); -SELECT * FROM return_record('abc') AS r(t varchar(100), val integer); -SELECT * FROM return_record('999') AS r(val text, t integer); - -CREATE FUNCTION return_record_2(t text) RETURNS record AS $$ -return {'v1':1,'v2':2,t:3} -$$ LANGUAGE plpython3u; - -SELECT * FROM return_record_2('v3') AS (v3 int, v2 int, v1 int); -SELECT * FROM return_record_2('v3') AS (v2 int, v3 int, v1 int); -SELECT * FROM return_record_2('v4') AS (v1 int, v4 int, v2 int); -SELECT * FROM return_record_2('v4') AS (v1 int, v4 int, v2 int); --- error -SELECT * FROM return_record_2('v4') AS (v1 int, v3 int, v2 int); --- works -SELECT * FROM return_record_2('v3') AS (v1 int, v3 int, v2 int); -SELECT * FROM return_record_2('v3') AS (v1 int, v2 int, v3 int); - --- multi-dimensional array of composite types. -CREATE FUNCTION composite_type_as_list() RETURNS type_record[] AS $$ - return [[('first', 1), ('second', 1)], [('first', 2), ('second', 2)], [('first', 3), ('second', 3)]]; -$$ LANGUAGE plpython3u; -SELECT * FROM composite_type_as_list(); - --- Starting with PostgreSQL 10, a composite type in an array cannot be --- represented as a Python list, because it's ambiguous with multi-dimensional --- arrays. So this throws an error now. The error should contain a useful hint --- on the issue. -CREATE FUNCTION composite_type_as_list_broken() RETURNS type_record[] AS $$ - return [['first', 1]]; -$$ LANGUAGE plpython3u; -SELECT * FROM composite_type_as_list_broken(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_ereport.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_ereport.sql deleted file mode 100644 index d4f6223e59..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_ereport.sql +++ /dev/null @@ -1,135 +0,0 @@ -CREATE FUNCTION elog_test() RETURNS void -AS $$ -plpy.debug('debug', detail='some detail') -plpy.log('log', detail='some detail') -plpy.info('info', detail='some detail') -plpy.info() -plpy.info('the question', detail=42); -plpy.info('This is message text.', - detail='This is detail text', - hint='This is hint text.', - sqlstate='XX000', - schema_name='any info about schema', - table_name='any info about table', - column_name='any info about column', - datatype_name='any info about datatype', - constraint_name='any info about constraint') -plpy.notice('notice', detail='some detail') -plpy.warning('warning', detail='some detail') -plpy.error('stop on error', detail='some detail', hint='some hint') -$$ LANGUAGE plpython3u; - -SELECT elog_test(); - -DO $$ plpy.info('other types', detail=(10, 20)) $$ LANGUAGE plpython3u; - -DO $$ -import time; -from datetime import date -plpy.info('other types', detail=date(2016, 2, 26)) -$$ LANGUAGE plpython3u; - -DO $$ -basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] -plpy.info('other types', detail=basket) -$$ LANGUAGE plpython3u; - --- should fail -DO $$ plpy.info('wrong sqlstate', sqlstate='54444A') $$ LANGUAGE plpython3u; -DO $$ plpy.info('unsupported argument', blabla='fooboo') $$ LANGUAGE plpython3u; -DO $$ plpy.info('first message', message='second message') $$ LANGUAGE plpython3u; -DO $$ plpy.info('first message', 'second message', message='third message') $$ LANGUAGE plpython3u; - --- raise exception in python, handle exception in plgsql -CREATE OR REPLACE FUNCTION raise_exception(_message text, _detail text DEFAULT NULL, _hint text DEFAULT NULL, - _sqlstate text DEFAULT NULL, - _schema_name text DEFAULT NULL, - _table_name text DEFAULT NULL, - _column_name text DEFAULT NULL, - _datatype_name text DEFAULT NULL, - _constraint_name text DEFAULT NULL) -RETURNS void AS $$ -kwargs = { - "message": _message, "detail": _detail, "hint": _hint, - "sqlstate": _sqlstate, "schema_name": _schema_name, "table_name": _table_name, - "column_name": _column_name, "datatype_name": _datatype_name, - "constraint_name": _constraint_name -} -# ignore None values -plpy.error(**dict((k, v) for k, v in iter(kwargs.items()) if v)) -$$ LANGUAGE plpython3u; - -SELECT raise_exception('hello', 'world'); -SELECT raise_exception('message text', 'detail text', _sqlstate => 'YY333'); -SELECT raise_exception(_message => 'message text', - _detail => 'detail text', - _hint => 'hint text', - _sqlstate => 'XX555', - _schema_name => 'schema text', - _table_name => 'table text', - _column_name => 'column text', - _datatype_name => 'datatype text', - _constraint_name => 'constraint text'); - -SELECT raise_exception(_message => 'message text', - _hint => 'hint text', - _schema_name => 'schema text', - _column_name => 'column text', - _constraint_name => 'constraint text'); - -DO $$ -DECLARE - __message text; - __detail text; - __hint text; - __sqlstate text; - __schema_name text; - __table_name text; - __column_name text; - __datatype_name text; - __constraint_name text; -BEGIN - BEGIN - PERFORM raise_exception(_message => 'message text', - _detail => 'detail text', - _hint => 'hint text', - _sqlstate => 'XX555', - _schema_name => 'schema text', - _table_name => 'table text', - _column_name => 'column text', - _datatype_name => 'datatype text', - _constraint_name => 'constraint text'); - EXCEPTION WHEN SQLSTATE 'XX555' THEN - GET STACKED DIAGNOSTICS __message = MESSAGE_TEXT, - __detail = PG_EXCEPTION_DETAIL, - __hint = PG_EXCEPTION_HINT, - __sqlstate = RETURNED_SQLSTATE, - __schema_name = SCHEMA_NAME, - __table_name = TABLE_NAME, - __column_name = COLUMN_NAME, - __datatype_name = PG_DATATYPE_NAME, - __constraint_name = CONSTRAINT_NAME; - RAISE NOTICE 'handled exception' - USING DETAIL = format('message:(%s), detail:(%s), hint: (%s), sqlstate: (%s), ' - 'schema_name:(%s), table_name:(%s), column_name:(%s), datatype_name:(%s), constraint_name:(%s)', - __message, __detail, __hint, __sqlstate, __schema_name, - __table_name, __column_name, __datatype_name, __constraint_name); - END; -END; -$$; - -DO $$ -try: - plpy.execute("select raise_exception(_message => 'my message', _sqlstate => 'XX987', _hint => 'some hint', _table_name => 'users_tab', _datatype_name => 'user_type')") -except Exception as e: - plpy.info(e.spidata) - raise e -$$ LANGUAGE plpython3u; - -DO $$ -try: - plpy.error(message = 'my message', sqlstate = 'XX987', hint = 'some hint', table_name = 'users_tab', datatype_name = 'user_type') -except Exception as e: - plpy.info('sqlstate: %s, hint: %s, table_name: %s, datatype_name: %s' % (e.sqlstate, e.hint, e.table_name, e.datatype_name)) - raise e -$$ LANGUAGE plpython3u; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_error.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_error.sql deleted file mode 100644 index 11f14ec5a7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_error.sql +++ /dev/null @@ -1,346 +0,0 @@ --- test error handling, i forgot to restore Warn_restart in --- the trigger handler once. the errors and subsequent core dump were --- interesting. - -/* Flat out Python syntax error - */ -CREATE FUNCTION python_syntax_error() RETURNS text - AS -'.syntaxerror' - LANGUAGE plpython3u; - -/* With check_function_bodies = false the function should get defined - * and the error reported when called - */ -SET check_function_bodies = false; - -CREATE FUNCTION python_syntax_error() RETURNS text - AS -'.syntaxerror' - LANGUAGE plpython3u; - -SELECT python_syntax_error(); -/* Run the function twice to check if the hashtable entry gets cleaned up */ -SELECT python_syntax_error(); - -RESET check_function_bodies; - -/* Flat out syntax error - */ -CREATE FUNCTION sql_syntax_error() RETURNS text - AS -'plpy.execute("syntax error")' - LANGUAGE plpython3u; - -SELECT sql_syntax_error(); - - -/* check the handling of uncaught python exceptions - */ -CREATE FUNCTION exception_index_invalid(text) RETURNS text - AS -'return args[1]' - LANGUAGE plpython3u; - -SELECT exception_index_invalid('test'); - - -/* check handling of nested exceptions - */ -CREATE FUNCTION exception_index_invalid_nested() RETURNS text - AS -'rv = plpy.execute("SELECT test5(''foo'')") -return rv[0]' - LANGUAGE plpython3u; - -SELECT exception_index_invalid_nested(); - - -/* a typo - */ -CREATE FUNCTION invalid_type_uncaught(a text) RETURNS text - AS -'if "plan" not in SD: - q = "SELECT fname FROM users WHERE lname = $1" - SD["plan"] = plpy.prepare(q, [ "test" ]) -rv = plpy.execute(SD["plan"], [ a ]) -if len(rv): - return rv[0]["fname"] -return None -' - LANGUAGE plpython3u; - -SELECT invalid_type_uncaught('rick'); - - -/* for what it's worth catch the exception generated by - * the typo, and return None - */ -CREATE FUNCTION invalid_type_caught(a text) RETURNS text - AS -'if "plan" not in SD: - q = "SELECT fname FROM users WHERE lname = $1" - try: - SD["plan"] = plpy.prepare(q, [ "test" ]) - except plpy.SPIError as ex: - plpy.notice(str(ex)) - return None -rv = plpy.execute(SD["plan"], [ a ]) -if len(rv): - return rv[0]["fname"] -return None -' - LANGUAGE plpython3u; - -SELECT invalid_type_caught('rick'); - - -/* for what it's worth catch the exception generated by - * the typo, and reraise it as a plain error - */ -CREATE FUNCTION invalid_type_reraised(a text) RETURNS text - AS -'if "plan" not in SD: - q = "SELECT fname FROM users WHERE lname = $1" - try: - SD["plan"] = plpy.prepare(q, [ "test" ]) - except plpy.SPIError as ex: - plpy.error(str(ex)) -rv = plpy.execute(SD["plan"], [ a ]) -if len(rv): - return rv[0]["fname"] -return None -' - LANGUAGE plpython3u; - -SELECT invalid_type_reraised('rick'); - - -/* no typo no messing about - */ -CREATE FUNCTION valid_type(a text) RETURNS text - AS -'if "plan" not in SD: - SD["plan"] = plpy.prepare("SELECT fname FROM users WHERE lname = $1", [ "text" ]) -rv = plpy.execute(SD["plan"], [ a ]) -if len(rv): - return rv[0]["fname"] -return None -' - LANGUAGE plpython3u; - -SELECT valid_type('rick'); - -/* error in nested functions to get a traceback -*/ -CREATE FUNCTION nested_error() RETURNS text - AS -'def fun1(): - plpy.error("boom") - -def fun2(): - fun1() - -def fun3(): - fun2() - -fun3() -return "not reached" -' - LANGUAGE plpython3u; - -SELECT nested_error(); - -/* raising plpy.Error is just like calling plpy.error -*/ -CREATE FUNCTION nested_error_raise() RETURNS text - AS -'def fun1(): - raise plpy.Error("boom") - -def fun2(): - fun1() - -def fun3(): - fun2() - -fun3() -return "not reached" -' - LANGUAGE plpython3u; - -SELECT nested_error_raise(); - -/* using plpy.warning should not produce a traceback -*/ -CREATE FUNCTION nested_warning() RETURNS text - AS -'def fun1(): - plpy.warning("boom") - -def fun2(): - fun1() - -def fun3(): - fun2() - -fun3() -return "you''ve been warned" -' - LANGUAGE plpython3u; - -SELECT nested_warning(); - -/* AttributeError at toplevel used to give segfaults with the traceback -*/ -CREATE FUNCTION toplevel_attribute_error() RETURNS void AS -$$ -plpy.nonexistent -$$ LANGUAGE plpython3u; - -SELECT toplevel_attribute_error(); - -/* Calling PL/Python functions from SQL and vice versa should not lose context. - */ -CREATE OR REPLACE FUNCTION python_traceback() RETURNS void AS $$ -def first(): - second() - -def second(): - third() - -def third(): - plpy.execute("select sql_error()") - -first() -$$ LANGUAGE plpython3u; - -CREATE OR REPLACE FUNCTION sql_error() RETURNS void AS $$ -begin - select 1/0; -end -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION python_from_sql_error() RETURNS void AS $$ -begin - select python_traceback(); -end -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION sql_from_python_error() RETURNS void AS $$ -plpy.execute("select sql_error()") -$$ LANGUAGE plpython3u; - -SELECT python_traceback(); -SELECT sql_error(); -SELECT python_from_sql_error(); -SELECT sql_from_python_error(); - -/* check catching specific types of exceptions - */ -CREATE TABLE specific ( - i integer PRIMARY KEY -); - -CREATE FUNCTION specific_exception(i integer) RETURNS void AS -$$ -from plpy import spiexceptions -try: - plpy.execute("insert into specific values (%s)" % (i or "NULL")); -except spiexceptions.NotNullViolation as e: - plpy.notice("Violated the NOT NULL constraint, sqlstate %s" % e.sqlstate) -except spiexceptions.UniqueViolation as e: - plpy.notice("Violated the UNIQUE constraint, sqlstate %s" % e.sqlstate) -$$ LANGUAGE plpython3u; - -SELECT specific_exception(2); -SELECT specific_exception(NULL); -SELECT specific_exception(2); - -/* SPI errors in PL/Python functions should preserve the SQLSTATE value - */ -CREATE FUNCTION python_unique_violation() RETURNS void AS $$ -plpy.execute("insert into specific values (1)") -plpy.execute("insert into specific values (1)") -$$ LANGUAGE plpython3u; - -CREATE FUNCTION catch_python_unique_violation() RETURNS text AS $$ -begin - begin - perform python_unique_violation(); - exception when unique_violation then - return 'ok'; - end; - return 'not reached'; -end; -$$ language plpgsql; - -SELECT catch_python_unique_violation(); - -/* manually starting subtransactions - a bad idea - */ -CREATE FUNCTION manual_subxact() RETURNS void AS $$ -plpy.execute("savepoint save") -plpy.execute("create table foo(x integer)") -plpy.execute("rollback to save") -$$ LANGUAGE plpython3u; - -SELECT manual_subxact(); - -/* same for prepared plans - */ -CREATE FUNCTION manual_subxact_prepared() RETURNS void AS $$ -save = plpy.prepare("savepoint save") -rollback = plpy.prepare("rollback to save") -plpy.execute(save) -plpy.execute("create table foo(x integer)") -plpy.execute(rollback) -$$ LANGUAGE plpython3u; - -SELECT manual_subxact_prepared(); - -/* raising plpy.spiexception.* from python code should preserve sqlstate - */ -CREATE FUNCTION plpy_raise_spiexception() RETURNS void AS $$ -raise plpy.spiexceptions.DivisionByZero() -$$ LANGUAGE plpython3u; - -DO $$ -BEGIN - SELECT plpy_raise_spiexception(); -EXCEPTION WHEN division_by_zero THEN - -- NOOP -END -$$ LANGUAGE plpgsql; - -/* setting a custom sqlstate should be handled - */ -CREATE FUNCTION plpy_raise_spiexception_override() RETURNS void AS $$ -exc = plpy.spiexceptions.DivisionByZero() -exc.sqlstate = 'SILLY' -raise exc -$$ LANGUAGE plpython3u; - -DO $$ -BEGIN - SELECT plpy_raise_spiexception_override(); -EXCEPTION WHEN SQLSTATE 'SILLY' THEN - -- NOOP -END -$$ LANGUAGE plpgsql; - -/* test the context stack trace for nested execution levels - */ -CREATE FUNCTION notice_innerfunc() RETURNS int AS $$ -plpy.execute("DO LANGUAGE plpython3u $x$ plpy.notice('inside DO') $x$") -return 1 -$$ LANGUAGE plpython3u; - -CREATE FUNCTION notice_outerfunc() RETURNS int AS $$ -plpy.execute("SELECT notice_innerfunc()") -return 1 -$$ LANGUAGE plpython3u; - -\set SHOW_CONTEXT always - -SELECT notice_outerfunc(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_params.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_params.sql deleted file mode 100644 index 8bab488859..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_params.sql +++ /dev/null @@ -1,42 +0,0 @@ --- --- Test named and nameless parameters --- - -CREATE FUNCTION test_param_names0(integer, integer) RETURNS int AS $$ -return args[0] + args[1] -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_param_names1(a0 integer, a1 text) RETURNS boolean AS $$ -assert a0 == args[0] -assert a1 == args[1] -return True -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_param_names2(u users) RETURNS text AS $$ -assert u == args[0] -if isinstance(u, dict): - # stringify dict the hard way because otherwise the order is implementation-dependent - u_keys = list(u.keys()) - u_keys.sort() - s = '{' + ', '.join([repr(k) + ': ' + repr(u[k]) for k in u_keys]) + '}' -else: - s = str(u) -return s -$$ LANGUAGE plpython3u; - --- use deliberately wrong parameter names -CREATE FUNCTION test_param_names3(a0 integer) RETURNS boolean AS $$ -try: - assert a1 == args[0] - return False -except NameError as e: - assert e.args[0].find("a1") > -1 - return True -$$ LANGUAGE plpython3u; - - -SELECT test_param_names0(2,7); -SELECT test_param_names1(1,'text'); -SELECT test_param_names2(users) from users; -SELECT test_param_names2(NULL); -SELECT test_param_names3(1); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_quote.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_quote.sql deleted file mode 100644 index a1133e7e26..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_quote.sql +++ /dev/null @@ -1,33 +0,0 @@ --- test quoting functions - -CREATE FUNCTION quote(t text, how text) RETURNS text AS $$ - if how == "literal": - return plpy.quote_literal(t) - elif how == "nullable": - return plpy.quote_nullable(t) - elif how == "ident": - return plpy.quote_ident(t) - else: - raise plpy.Error("unrecognized quote type %s" % how) -$$ LANGUAGE plpython3u; - -SELECT quote(t, 'literal') FROM (VALUES - ('abc'), - ('a''bc'), - ('''abc'''), - (''), - (''''), - ('xyzv')) AS v(t); - -SELECT quote(t, 'nullable') FROM (VALUES - ('abc'), - ('a''bc'), - ('''abc'''), - (''), - (''''), - (NULL)) AS v(t); - -SELECT quote(t, 'ident') FROM (VALUES - ('abc'), - ('a b c'), - ('a " ''abc''')) AS v(t); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_record.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_record.sql deleted file mode 100644 index 52bad8bcce..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_record.sql +++ /dev/null @@ -1,163 +0,0 @@ --- --- Test returning tuples --- - -CREATE TABLE table_record ( - first text, - second int4 - ) ; - -CREATE TYPE type_record AS ( - first text, - second int4 - ) ; - - -CREATE FUNCTION test_table_record_as(typ text, first text, second integer, retnull boolean) RETURNS table_record AS $$ -if retnull: - return None -if typ == 'dict': - return { 'first': first, 'second': second, 'additionalfield': 'must not cause trouble' } -elif typ == 'tuple': - return ( first, second ) -elif typ == 'list': - return [ first, second ] -elif typ == 'obj': - class type_record: pass - type_record.first = first - type_record.second = second - return type_record -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_type_record_as(typ text, first text, second integer, retnull boolean) RETURNS type_record AS $$ -if retnull: - return None -if typ == 'dict': - return { 'first': first, 'second': second, 'additionalfield': 'must not cause trouble' } -elif typ == 'tuple': - return ( first, second ) -elif typ == 'list': - return [ first, second ] -elif typ == 'obj': - class type_record: pass - type_record.first = first - type_record.second = second - return type_record -elif typ == 'str': - return "('%s',%r)" % (first, second) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_in_out_params(first in text, second out text) AS $$ -return first + '_in_to_out'; -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_in_out_params_multi(first in text, - second out text, third out text) AS $$ -return (first + '_record_in_to_out_1', first + '_record_in_to_out_2'); -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_inout_params(first inout text) AS $$ -return first + '_inout'; -$$ LANGUAGE plpython3u; - - --- Test tuple returning functions -SELECT * FROM test_table_record_as('dict', null, null, false); -SELECT * FROM test_table_record_as('dict', 'one', null, false); -SELECT * FROM test_table_record_as('dict', null, 2, false); -SELECT * FROM test_table_record_as('dict', 'three', 3, false); -SELECT * FROM test_table_record_as('dict', null, null, true); - -SELECT * FROM test_table_record_as('tuple', null, null, false); -SELECT * FROM test_table_record_as('tuple', 'one', null, false); -SELECT * FROM test_table_record_as('tuple', null, 2, false); -SELECT * FROM test_table_record_as('tuple', 'three', 3, false); -SELECT * FROM test_table_record_as('tuple', null, null, true); - -SELECT * FROM test_table_record_as('list', null, null, false); -SELECT * FROM test_table_record_as('list', 'one', null, false); -SELECT * FROM test_table_record_as('list', null, 2, false); -SELECT * FROM test_table_record_as('list', 'three', 3, false); -SELECT * FROM test_table_record_as('list', null, null, true); - -SELECT * FROM test_table_record_as('obj', null, null, false); -SELECT * FROM test_table_record_as('obj', 'one', null, false); -SELECT * FROM test_table_record_as('obj', null, 2, false); -SELECT * FROM test_table_record_as('obj', 'three', 3, false); -SELECT * FROM test_table_record_as('obj', null, null, true); - -SELECT * FROM test_type_record_as('dict', null, null, false); -SELECT * FROM test_type_record_as('dict', 'one', null, false); -SELECT * FROM test_type_record_as('dict', null, 2, false); -SELECT * FROM test_type_record_as('dict', 'three', 3, false); -SELECT * FROM test_type_record_as('dict', null, null, true); - -SELECT * FROM test_type_record_as('tuple', null, null, false); -SELECT * FROM test_type_record_as('tuple', 'one', null, false); -SELECT * FROM test_type_record_as('tuple', null, 2, false); -SELECT * FROM test_type_record_as('tuple', 'three', 3, false); -SELECT * FROM test_type_record_as('tuple', null, null, true); - -SELECT * FROM test_type_record_as('list', null, null, false); -SELECT * FROM test_type_record_as('list', 'one', null, false); -SELECT * FROM test_type_record_as('list', null, 2, false); -SELECT * FROM test_type_record_as('list', 'three', 3, false); -SELECT * FROM test_type_record_as('list', null, null, true); - -SELECT * FROM test_type_record_as('obj', null, null, false); -SELECT * FROM test_type_record_as('obj', 'one', null, false); -SELECT * FROM test_type_record_as('obj', null, 2, false); -SELECT * FROM test_type_record_as('obj', 'three', 3, false); -SELECT * FROM test_type_record_as('obj', null, null, true); - -SELECT * FROM test_type_record_as('str', 'one', 1, false); - -SELECT * FROM test_in_out_params('test_in'); -SELECT * FROM test_in_out_params_multi('test_in'); -SELECT * FROM test_inout_params('test_in'); - --- try changing the return types and call functions again - -ALTER TABLE table_record DROP COLUMN first; -ALTER TABLE table_record DROP COLUMN second; -ALTER TABLE table_record ADD COLUMN first text; -ALTER TABLE table_record ADD COLUMN second int4; - -SELECT * FROM test_table_record_as('obj', 'one', 1, false); - -ALTER TYPE type_record DROP ATTRIBUTE first; -ALTER TYPE type_record DROP ATTRIBUTE second; -ALTER TYPE type_record ADD ATTRIBUTE first text; -ALTER TYPE type_record ADD ATTRIBUTE second int4; - -SELECT * FROM test_type_record_as('obj', 'one', 1, false); - --- errors cases - -CREATE FUNCTION test_type_record_error1() RETURNS type_record AS $$ - return { 'first': 'first' } -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_record_error1(); - - -CREATE FUNCTION test_type_record_error2() RETURNS type_record AS $$ - return [ 'first' ] -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_record_error2(); - - -CREATE FUNCTION test_type_record_error3() RETURNS type_record AS $$ - class type_record: pass - type_record.first = 'first' - return type_record -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_record_error3(); - -CREATE FUNCTION test_type_record_error4() RETURNS type_record AS $$ - return 'foo' -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_record_error4(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_setof.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_setof.sql deleted file mode 100644 index 4cfb10192c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_setof.sql +++ /dev/null @@ -1,97 +0,0 @@ --- --- Test returning SETOF --- - -CREATE FUNCTION test_setof_error() RETURNS SETOF text AS $$ -return 37 -$$ LANGUAGE plpython3u; - -SELECT test_setof_error(); - - -CREATE FUNCTION test_setof_as_list(count integer, content text) RETURNS SETOF text AS $$ -return [ content ]*count -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_setof_as_tuple(count integer, content text) RETURNS SETOF text AS $$ -t = () -for i in range(count): - t += ( content, ) -return t -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_setof_as_iterator(count integer, content text) RETURNS SETOF text AS $$ -class producer: - def __init__ (self, icount, icontent): - self.icontent = icontent - self.icount = icount - def __iter__ (self): - return self - def __next__ (self): - if self.icount == 0: - raise StopIteration - self.icount -= 1 - return self.icontent -return producer(count, content) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_setof_spi_in_iterator() RETURNS SETOF text AS -$$ - for s in ('Hello', 'Brave', 'New', 'World'): - plpy.execute('select 1') - yield s - plpy.execute('select 2') -$$ -LANGUAGE plpython3u; - - --- Test set returning functions -SELECT test_setof_as_list(0, 'list'); -SELECT test_setof_as_list(1, 'list'); -SELECT test_setof_as_list(2, 'list'); -SELECT test_setof_as_list(2, null); - -SELECT test_setof_as_tuple(0, 'tuple'); -SELECT test_setof_as_tuple(1, 'tuple'); -SELECT test_setof_as_tuple(2, 'tuple'); -SELECT test_setof_as_tuple(2, null); - -SELECT test_setof_as_iterator(0, 'list'); -SELECT test_setof_as_iterator(1, 'list'); -SELECT test_setof_as_iterator(2, 'list'); -SELECT test_setof_as_iterator(2, null); - -SELECT test_setof_spi_in_iterator(); - --- set-returning function that modifies its parameters -CREATE OR REPLACE FUNCTION ugly(x int, lim int) RETURNS SETOF int AS $$ -global x -while x <= lim: - yield x - x = x + 1 -$$ LANGUAGE plpython3u; - -SELECT ugly(1, 5); - --- interleaved execution of such a function -SELECT ugly(1,3), ugly(7,8); - --- returns set of named-composite-type tuples -CREATE OR REPLACE FUNCTION get_user_records() -RETURNS SETOF users -AS $$ - return plpy.execute("SELECT * FROM users ORDER BY username") -$$ LANGUAGE plpython3u; - -SELECT get_user_records(); -SELECT * FROM get_user_records(); - --- same, but returning set of RECORD -CREATE OR REPLACE FUNCTION get_user_records2() -RETURNS TABLE(fname text, lname text, username text, userid int) -AS $$ - return plpy.execute("SELECT * FROM users ORDER BY username") -$$ LANGUAGE plpython3u; - -SELECT get_user_records2(); -SELECT * FROM get_user_records2(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_spi.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_spi.sql deleted file mode 100644 index fcd113acaa..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_spi.sql +++ /dev/null @@ -1,322 +0,0 @@ --- --- nested calls --- - -CREATE FUNCTION nested_call_one(a text) RETURNS text - AS -'q = "SELECT nested_call_two(''%s'')" % a -r = plpy.execute(q) -return r[0]' - LANGUAGE plpython3u ; - -CREATE FUNCTION nested_call_two(a text) RETURNS text - AS -'q = "SELECT nested_call_three(''%s'')" % a -r = plpy.execute(q) -return r[0]' - LANGUAGE plpython3u ; - -CREATE FUNCTION nested_call_three(a text) RETURNS text - AS -'return a' - LANGUAGE plpython3u ; - --- some spi stuff - -CREATE FUNCTION spi_prepared_plan_test_one(a text) RETURNS text - AS -'if "myplan" not in SD: - q = "SELECT count(*) FROM users WHERE lname = $1" - SD["myplan"] = plpy.prepare(q, [ "text" ]) -try: - rv = plpy.execute(SD["myplan"], [a]) - return "there are " + str(rv[0]["count"]) + " " + str(a) + "s" -except Exception as ex: - plpy.error(str(ex)) -return None -' - LANGUAGE plpython3u; - -CREATE FUNCTION spi_prepared_plan_test_two(a text) RETURNS text - AS -'if "myplan" not in SD: - q = "SELECT count(*) FROM users WHERE lname = $1" - SD["myplan"] = plpy.prepare(q, [ "text" ]) -try: - rv = SD["myplan"].execute([a]) - return "there are " + str(rv[0]["count"]) + " " + str(a) + "s" -except Exception as ex: - plpy.error(str(ex)) -return None -' - LANGUAGE plpython3u; - -CREATE FUNCTION spi_prepared_plan_test_nested(a text) RETURNS text - AS -'if "myplan" not in SD: - q = "SELECT spi_prepared_plan_test_one(''%s'') as count" % a - SD["myplan"] = plpy.prepare(q) -try: - rv = plpy.execute(SD["myplan"]) - if len(rv): - return rv[0]["count"] -except Exception as ex: - plpy.error(str(ex)) -return None -' - LANGUAGE plpython3u; - -CREATE FUNCTION join_sequences(s sequences) RETURNS text - AS -'if not s["multipart"]: - return s["sequence"] -q = "SELECT sequence FROM xsequences WHERE pid = ''%s''" % s["pid"] -rv = plpy.execute(q) -seq = s["sequence"] -for r in rv: - seq = seq + r["sequence"] -return seq -' - LANGUAGE plpython3u; - -CREATE FUNCTION spi_recursive_sum(a int) RETURNS int - AS -'r = 0 -if a > 1: - r = plpy.execute("SELECT spi_recursive_sum(%d) as a" % (a-1))[0]["a"] -return a + r -' - LANGUAGE plpython3u; - --- --- spi and nested calls --- -select nested_call_one('pass this along'); -select spi_prepared_plan_test_one('doe'); -select spi_prepared_plan_test_two('smith'); -select spi_prepared_plan_test_nested('smith'); - -SELECT join_sequences(sequences) FROM sequences; -SELECT join_sequences(sequences) FROM sequences - WHERE join_sequences(sequences) ~* '^A'; -SELECT join_sequences(sequences) FROM sequences - WHERE join_sequences(sequences) ~* '^B'; - -SELECT spi_recursive_sum(10); - --- --- plan and result objects --- - -CREATE FUNCTION result_metadata_test(cmd text) RETURNS int -AS $$ -plan = plpy.prepare(cmd) -plpy.info(plan.status()) # not really documented or useful -result = plpy.execute(plan) -if result.status() > 0: - plpy.info(result.colnames()) - plpy.info(result.coltypes()) - plpy.info(result.coltypmods()) - return result.nrows() -else: - return None -$$ LANGUAGE plpython3u; - -SELECT result_metadata_test($$SELECT 1 AS foo, '11'::text AS bar UNION SELECT 2, '22'$$); -SELECT result_metadata_test($$CREATE TEMPORARY TABLE foo1 (a int, b text)$$); - -CREATE FUNCTION result_nrows_test(cmd text) RETURNS int -AS $$ -result = plpy.execute(cmd) -return result.nrows() -$$ LANGUAGE plpython3u; - -SELECT result_nrows_test($$SELECT 1$$); -SELECT result_nrows_test($$CREATE TEMPORARY TABLE foo2 (a int, b text)$$); -SELECT result_nrows_test($$INSERT INTO foo2 VALUES (1, 'one'), (2, 'two')$$); -SELECT result_nrows_test($$UPDATE foo2 SET b = '' WHERE a = 2$$); - -CREATE FUNCTION result_len_test(cmd text) RETURNS int -AS $$ -result = plpy.execute(cmd) -return len(result) -$$ LANGUAGE plpython3u; - -SELECT result_len_test($$SELECT 1$$); -SELECT result_len_test($$CREATE TEMPORARY TABLE foo3 (a int, b text)$$); -SELECT result_len_test($$INSERT INTO foo3 VALUES (1, 'one'), (2, 'two')$$); -SELECT result_len_test($$UPDATE foo3 SET b= '' WHERE a = 2$$); - -CREATE FUNCTION result_subscript_test() RETURNS void -AS $$ -result = plpy.execute("SELECT 1 AS c UNION ALL SELECT 2 " - "UNION ALL SELECT 3 UNION ALL SELECT 4") - -plpy.info(result[1]['c']) -plpy.info(result[-1]['c']) - -plpy.info([item['c'] for item in result[1:3]]) -plpy.info([item['c'] for item in result[::2]]) - -result[-1] = {'c': 1000} -result[:2] = [{'c': 10}, {'c': 100}] -plpy.info([item['c'] for item in result[:]]) - -# raises TypeError, catch so further tests could be added -try: - plpy.info(result['foo']) -except TypeError: - pass -else: - assert False, "TypeError not raised" - -$$ LANGUAGE plpython3u; - -SELECT result_subscript_test(); - -CREATE FUNCTION result_empty_test() RETURNS void -AS $$ -result = plpy.execute("select 1 where false") - -plpy.info(result[:]) - -$$ LANGUAGE plpython3u; - -SELECT result_empty_test(); - -CREATE FUNCTION result_str_test(cmd text) RETURNS text -AS $$ -plan = plpy.prepare(cmd) -result = plpy.execute(plan) -return str(result) -$$ LANGUAGE plpython3u; - -SELECT result_str_test($$SELECT 1 AS foo UNION SELECT 2$$); -SELECT result_str_test($$CREATE TEMPORARY TABLE foo1 (a int, b text)$$); - --- cursor objects - -CREATE FUNCTION simple_cursor_test() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users") -does = 0 -for row in res: - if row['lname'] == 'doe': - does += 1 -return does -$$ LANGUAGE plpython3u; - -CREATE FUNCTION double_cursor_close() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users") -res.close() -res.close() -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_fetch() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users") -assert len(res.fetch(3)) == 3 -assert len(res.fetch(3)) == 1 -assert len(res.fetch(3)) == 0 -assert len(res.fetch(3)) == 0 -try: - # use next() or __next__(), the method name changed in - # http://www.python.org/dev/peps/pep-3114/ - try: - res.next() - except AttributeError: - res.__next__() -except StopIteration: - pass -else: - assert False, "StopIteration not raised" -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_mix_next_and_fetch() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users order by fname") -assert len(res.fetch(2)) == 2 - -item = None -try: - item = res.next() -except AttributeError: - item = res.__next__() -assert item['fname'] == 'rick' - -assert len(res.fetch(2)) == 1 -$$ LANGUAGE plpython3u; - -CREATE FUNCTION fetch_after_close() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users") -res.close() -try: - res.fetch(1) -except ValueError: - pass -else: - assert False, "ValueError not raised" -$$ LANGUAGE plpython3u; - -CREATE FUNCTION next_after_close() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users") -res.close() -try: - try: - res.next() - except AttributeError: - res.__next__() -except ValueError: - pass -else: - assert False, "ValueError not raised" -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_fetch_next_empty() RETURNS int AS $$ -res = plpy.cursor("select fname, lname from users where false") -assert len(res.fetch(1)) == 0 -try: - try: - res.next() - except AttributeError: - res.__next__() -except StopIteration: - pass -else: - assert False, "StopIteration not raised" -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_plan() RETURNS SETOF text AS $$ -plan = plpy.prepare( - "select fname, lname from users where fname like $1 || '%' order by fname", - ["text"]) -for row in plpy.cursor(plan, ["w"]): - yield row['fname'] -for row in plan.cursor(["j"]): - yield row['fname'] -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_plan_wrong_args() RETURNS SETOF text AS $$ -plan = plpy.prepare("select fname, lname from users where fname like $1 || '%'", - ["text"]) -c = plpy.cursor(plan, ["a", "b"]) -$$ LANGUAGE plpython3u; - -CREATE TYPE test_composite_type AS ( - a1 int, - a2 varchar -); - -CREATE OR REPLACE FUNCTION plan_composite_args() RETURNS test_composite_type AS $$ -plan = plpy.prepare("select $1 as c1", ["test_composite_type"]) -res = plpy.execute(plan, [{"a1": 3, "a2": "label"}]) -return res[0]["c1"] -$$ LANGUAGE plpython3u; - -SELECT simple_cursor_test(); -SELECT double_cursor_close(); -SELECT cursor_fetch(); -SELECT cursor_mix_next_and_fetch(); -SELECT fetch_after_close(); -SELECT next_after_close(); -SELECT cursor_fetch_next_empty(); -SELECT cursor_plan(); -SELECT cursor_plan_wrong_args(); -SELECT plan_composite_args(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_subtransaction.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_subtransaction.sql deleted file mode 100644 index c65c380f40..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_subtransaction.sql +++ /dev/null @@ -1,262 +0,0 @@ --- --- Test explicit subtransactions --- - --- Test table to see if transactions get properly rolled back - -CREATE TABLE subtransaction_tbl ( - i integer -); - -CREATE FUNCTION subtransaction_ctx_test(what_error text = NULL) RETURNS text -AS $$ -with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") - plpy.execute("INSERT INTO subtransaction_tbl VALUES (2)") - if what_error == "SPI": - plpy.execute("INSERT INTO subtransaction_tbl VALUES ('oops')") - elif what_error == "Python": - raise Exception("Python exception") -$$ LANGUAGE plpython3u; - -SELECT subtransaction_ctx_test(); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; -SELECT subtransaction_ctx_test('SPI'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; -SELECT subtransaction_ctx_test('Python'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - --- Nested subtransactions - -CREATE FUNCTION subtransaction_nested_test(swallow boolean = 'f') RETURNS text -AS $$ -plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") -with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (2)") - try: - with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (3)") - plpy.execute("error") - except plpy.SPIError as e: - if not swallow: - raise - plpy.notice("Swallowed %s(%r)" % (e.__class__.__name__, e.args[0])) -return "ok" -$$ LANGUAGE plpython3u; - -SELECT subtransaction_nested_test(); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - -SELECT subtransaction_nested_test('t'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - --- Nested subtransactions that recursively call code dealing with --- subtransactions - -CREATE FUNCTION subtransaction_deeply_nested_test() RETURNS text -AS $$ -plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") -with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (2)") - plpy.execute("SELECT subtransaction_nested_test('t')") -return "ok" -$$ LANGUAGE plpython3u; - -SELECT subtransaction_deeply_nested_test(); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - --- Error conditions from not opening/closing subtransactions - -CREATE FUNCTION subtransaction_exit_without_enter() RETURNS void -AS $$ -plpy.subtransaction().__exit__(None, None, None) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION subtransaction_enter_without_exit() RETURNS void -AS $$ -plpy.subtransaction().__enter__() -$$ LANGUAGE plpython3u; - -CREATE FUNCTION subtransaction_exit_twice() RETURNS void -AS $$ -plpy.subtransaction().__enter__() -plpy.subtransaction().__exit__(None, None, None) -plpy.subtransaction().__exit__(None, None, None) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION subtransaction_enter_twice() RETURNS void -AS $$ -plpy.subtransaction().__enter__() -plpy.subtransaction().__enter__() -$$ LANGUAGE plpython3u; - -CREATE FUNCTION subtransaction_exit_same_subtransaction_twice() RETURNS void -AS $$ -s = plpy.subtransaction() -s.__enter__() -s.__exit__(None, None, None) -s.__exit__(None, None, None) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION subtransaction_enter_same_subtransaction_twice() RETURNS void -AS $$ -s = plpy.subtransaction() -s.__enter__() -s.__enter__() -s.__exit__(None, None, None) -$$ LANGUAGE plpython3u; - --- No warnings here, as the subtransaction gets indeed closed -CREATE FUNCTION subtransaction_enter_subtransaction_in_with() RETURNS void -AS $$ -with plpy.subtransaction() as s: - s.__enter__() -$$ LANGUAGE plpython3u; - -CREATE FUNCTION subtransaction_exit_subtransaction_in_with() RETURNS void -AS $$ -try: - with plpy.subtransaction() as s: - s.__exit__(None, None, None) -except ValueError as e: - raise ValueError(e) -$$ LANGUAGE plpython3u; - -SELECT subtransaction_exit_without_enter(); -SELECT subtransaction_enter_without_exit(); -SELECT subtransaction_exit_twice(); -SELECT subtransaction_enter_twice(); -SELECT subtransaction_exit_same_subtransaction_twice(); -SELECT subtransaction_enter_same_subtransaction_twice(); -SELECT subtransaction_enter_subtransaction_in_with(); -SELECT subtransaction_exit_subtransaction_in_with(); - --- Make sure we don't get a "current transaction is aborted" error -SELECT 1 as test; - --- Mix explicit subtransactions and normal SPI calls - -CREATE FUNCTION subtransaction_mix_explicit_and_implicit() RETURNS void -AS $$ -p = plpy.prepare("INSERT INTO subtransaction_tbl VALUES ($1)", ["integer"]) -try: - with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") - plpy.execute(p, [2]) - plpy.execute(p, ["wrong"]) -except plpy.SPIError: - plpy.warning("Caught a SPI error from an explicit subtransaction") - -try: - plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") - plpy.execute(p, [2]) - plpy.execute(p, ["wrong"]) -except plpy.SPIError: - plpy.warning("Caught a SPI error") -$$ LANGUAGE plpython3u; - -SELECT subtransaction_mix_explicit_and_implicit(); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - --- Alternative method names for Python <2.6 - -CREATE FUNCTION subtransaction_alternative_names() RETURNS void -AS $$ -s = plpy.subtransaction() -s.enter() -s.exit(None, None, None) -$$ LANGUAGE plpython3u; - -SELECT subtransaction_alternative_names(); - --- try/catch inside a subtransaction block - -CREATE FUNCTION try_catch_inside_subtransaction() RETURNS void -AS $$ -with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") - try: - plpy.execute("INSERT INTO subtransaction_tbl VALUES ('a')") - except plpy.SPIError: - plpy.notice("caught") -$$ LANGUAGE plpython3u; - -SELECT try_catch_inside_subtransaction(); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - -ALTER TABLE subtransaction_tbl ADD PRIMARY KEY (i); - -CREATE FUNCTION pk_violation_inside_subtransaction() RETURNS void -AS $$ -with plpy.subtransaction(): - plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") - try: - plpy.execute("INSERT INTO subtransaction_tbl VALUES (1)") - except plpy.SPIError: - plpy.notice("caught") -$$ LANGUAGE plpython3u; - -SELECT pk_violation_inside_subtransaction(); -SELECT * FROM subtransaction_tbl; - -DROP TABLE subtransaction_tbl; - --- cursor/subtransactions interactions - -CREATE FUNCTION cursor_in_subxact() RETURNS int AS $$ -with plpy.subtransaction(): - cur = plpy.cursor("select * from generate_series(1, 20) as gen(i)") - cur.fetch(10) -fetched = cur.fetch(10); -return int(fetched[5]["i"]) -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_aborted_subxact() RETURNS int AS $$ -try: - with plpy.subtransaction(): - cur = plpy.cursor("select * from generate_series(1, 20) as gen(i)") - cur.fetch(10); - plpy.execute("select no_such_function()") -except plpy.SPIError: - fetched = cur.fetch(10) - return int(fetched[5]["i"]) -return 0 # not reached -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_plan_aborted_subxact() RETURNS int AS $$ -try: - with plpy.subtransaction(): - plpy.execute('create temporary table tmp(i) ' - 'as select generate_series(1, 10)') - plan = plpy.prepare("select i from tmp") - cur = plpy.cursor(plan) - plpy.execute("select no_such_function()") -except plpy.SPIError: - fetched = cur.fetch(5) - return fetched[2]["i"] -return 0 # not reached -$$ LANGUAGE plpython3u; - -CREATE FUNCTION cursor_close_aborted_subxact() RETURNS boolean AS $$ -try: - with plpy.subtransaction(): - cur = plpy.cursor('select 1') - plpy.execute("select no_such_function()") -except plpy.SPIError: - cur.close() - return True -return False # not reached -$$ LANGUAGE plpython3u; - -SELECT cursor_in_subxact(); -SELECT cursor_aborted_subxact(); -SELECT cursor_plan_aborted_subxact(); -SELECT cursor_close_aborted_subxact(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_test.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_test.sql deleted file mode 100644 index aa22a27415..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_test.sql +++ /dev/null @@ -1,52 +0,0 @@ --- first some tests of basic functionality -CREATE EXTENSION plpython3u; - --- really stupid function just to get the module loaded -CREATE FUNCTION stupid() RETURNS text AS 'return "zarkon"' LANGUAGE plpython3u; - -select stupid(); - --- check 2/3 versioning -CREATE FUNCTION stupidn() RETURNS text AS 'return "zarkon"' LANGUAGE plpython3u; - -select stupidn(); - --- test multiple arguments and odd characters in function name -CREATE FUNCTION "Argument test #1"(u users, a1 text, a2 text) RETURNS text - AS -'keys = list(u.keys()) -keys.sort() -out = [] -for key in keys: - out.append("%s: %s" % (key, u[key])) -words = a1 + " " + a2 + " => {" + ", ".join(out) + "}" -return words' - LANGUAGE plpython3u; - -select "Argument test #1"(users, fname, lname) from users where lname = 'doe' order by 1; - - --- check module contents -CREATE FUNCTION module_contents() RETURNS SETOF text AS -$$ -contents = list(filter(lambda x: not x.startswith("__"), dir(plpy))) -contents.sort() -return contents -$$ LANGUAGE plpython3u; - -select module_contents(); - -CREATE FUNCTION elog_test_basic() RETURNS void -AS $$ -plpy.debug('debug') -plpy.log('log') -plpy.info('info') -plpy.info(37) -plpy.info() -plpy.info('info', 37, [1, 2, 3]) -plpy.notice('notice') -plpy.warning('warning') -plpy.error('error') -$$ LANGUAGE plpython3u; - -SELECT elog_test_basic(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_transaction.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_transaction.sql deleted file mode 100644 index c939ba76d4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_transaction.sql +++ /dev/null @@ -1,182 +0,0 @@ -CREATE TABLE test1 (a int, b text); - - -CREATE PROCEDURE transaction_test1() -LANGUAGE plpython3u -AS $$ -for i in range(0, 10): - plpy.execute("INSERT INTO test1 (a) VALUES (%d)" % i) - if i % 2 == 0: - plpy.commit() - else: - plpy.rollback() -$$; - -CALL transaction_test1(); - -SELECT * FROM test1; - - -TRUNCATE test1; - -DO -LANGUAGE plpython3u -$$ -for i in range(0, 10): - plpy.execute("INSERT INTO test1 (a) VALUES (%d)" % i) - if i % 2 == 0: - plpy.commit() - else: - plpy.rollback() -$$; - -SELECT * FROM test1; - - -TRUNCATE test1; - --- not allowed in a function -CREATE FUNCTION transaction_test2() RETURNS int -LANGUAGE plpython3u -AS $$ -for i in range(0, 10): - plpy.execute("INSERT INTO test1 (a) VALUES (%d)" % i) - if i % 2 == 0: - plpy.commit() - else: - plpy.rollback() -return 1 -$$; - -SELECT transaction_test2(); - -SELECT * FROM test1; - - --- also not allowed if procedure is called from a function -CREATE FUNCTION transaction_test3() RETURNS int -LANGUAGE plpython3u -AS $$ -plpy.execute("CALL transaction_test1()") -return 1 -$$; - -SELECT transaction_test3(); - -SELECT * FROM test1; - - --- DO block inside function -CREATE FUNCTION transaction_test4() RETURNS int -LANGUAGE plpython3u -AS $$ -plpy.execute("DO LANGUAGE plpython3u $x$ plpy.commit() $x$") -return 1 -$$; - -SELECT transaction_test4(); - - --- commit inside subtransaction (prohibited) -DO LANGUAGE plpython3u $$ -s = plpy.subtransaction() -s.enter() -plpy.commit() -$$; - - --- commit inside cursor loop -CREATE TABLE test2 (x int); -INSERT INTO test2 VALUES (0), (1), (2), (3), (4); - -TRUNCATE test1; - -DO LANGUAGE plpython3u $$ -for row in plpy.cursor("SELECT * FROM test2 ORDER BY x"): - plpy.execute("INSERT INTO test1 (a) VALUES (%s)" % row['x']) - plpy.commit() -$$; - -SELECT * FROM test1; - --- check that this doesn't leak a holdable portal -SELECT * FROM pg_cursors; - - --- error in cursor loop with commit -TRUNCATE test1; - -DO LANGUAGE plpython3u $$ -for row in plpy.cursor("SELECT * FROM test2 ORDER BY x"): - plpy.execute("INSERT INTO test1 (a) VALUES (12/(%s-2))" % row['x']) - plpy.commit() -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plpython3u $$ -for row in plpy.cursor("SELECT * FROM test2 ORDER BY x"): - plpy.execute("INSERT INTO test1 (a) VALUES (%s)" % row['x']) - plpy.rollback() -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- first commit then rollback inside cursor loop -TRUNCATE test1; - -DO LANGUAGE plpython3u $$ -for row in plpy.cursor("SELECT * FROM test2 ORDER BY x"): - plpy.execute("INSERT INTO test1 (a) VALUES (%s)" % row['x']) - if row['x'] % 2 == 0: - plpy.commit() - else: - plpy.rollback() -$$; - -SELECT * FROM test1; - -SELECT * FROM pg_cursors; - - --- check handling of an error during COMMIT -CREATE TABLE testpk (id int PRIMARY KEY); -CREATE TABLE testfk(f1 int REFERENCES testpk DEFERRABLE INITIALLY DEFERRED); - -DO LANGUAGE plpython3u $$ -# this insert will fail during commit: -plpy.execute("INSERT INTO testfk VALUES (0)") -plpy.commit() -plpy.warning('should not get here') -$$; - -SELECT * FROM testpk; -SELECT * FROM testfk; - -DO LANGUAGE plpython3u $$ -# this insert will fail during commit: -plpy.execute("INSERT INTO testfk VALUES (0)") -try: - plpy.commit() -except Exception as e: - plpy.info('sqlstate: %s' % (e.sqlstate)) -# these inserts should work: -plpy.execute("INSERT INTO testpk VALUES (1)") -plpy.execute("INSERT INTO testfk VALUES (1)") -$$; - -SELECT * FROM testpk; -SELECT * FROM testfk; - - -DROP TABLE test1; -DROP TABLE test2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_trigger.sql deleted file mode 100644 index e5504b9ab1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_trigger.sql +++ /dev/null @@ -1,469 +0,0 @@ --- these triggers are dedicated to HPHC of RI who --- decided that my kid's name was william not willem, and --- vigorously resisted all efforts at correction. they have --- since gone bankrupt... - -CREATE FUNCTION users_insert() returns trigger - AS -'if TD["new"]["fname"] == None or TD["new"]["lname"] == None: - return "SKIP" -if TD["new"]["username"] == None: - TD["new"]["username"] = TD["new"]["fname"][:1] + "_" + TD["new"]["lname"] - rv = "MODIFY" -else: - rv = None -if TD["new"]["fname"] == "william": - TD["new"]["fname"] = TD["args"][0] - rv = "MODIFY" -return rv' - LANGUAGE plpython3u; - - -CREATE FUNCTION users_update() returns trigger - AS -'if TD["event"] == "UPDATE": - if TD["old"]["fname"] != TD["new"]["fname"] and TD["old"]["fname"] == TD["args"][0]: - return "SKIP" -return None' - LANGUAGE plpython3u; - - -CREATE FUNCTION users_delete() RETURNS trigger - AS -'if TD["old"]["fname"] == TD["args"][0]: - return "SKIP" -return None' - LANGUAGE plpython3u; - - -CREATE TRIGGER users_insert_trig BEFORE INSERT ON users FOR EACH ROW - EXECUTE PROCEDURE users_insert ('willem'); - -CREATE TRIGGER users_update_trig BEFORE UPDATE ON users FOR EACH ROW - EXECUTE PROCEDURE users_update ('willem'); - -CREATE TRIGGER users_delete_trig BEFORE DELETE ON users FOR EACH ROW - EXECUTE PROCEDURE users_delete ('willem'); - - --- quick peek at the table --- -SELECT * FROM users; - --- should fail --- -UPDATE users SET fname = 'william' WHERE fname = 'willem'; - --- should modify william to willem and create username --- -INSERT INTO users (fname, lname) VALUES ('william', 'smith'); -INSERT INTO users (fname, lname, username) VALUES ('charles', 'darwin', 'beagle'); - -SELECT * FROM users; - - --- dump trigger data - -CREATE TABLE trigger_test - (i int, v text ); - -CREATE TABLE trigger_test_generated ( - i int, - j int GENERATED ALWAYS AS (i * 2) STORED -); - -CREATE FUNCTION trigger_data() RETURNS trigger LANGUAGE plpython3u AS $$ - -if 'relid' in TD: - TD['relid'] = "bogus:12345" - -skeys = list(TD.keys()) -skeys.sort() -for key in skeys: - val = TD[key] - if not isinstance(val, dict): - plpy.notice("TD[" + key + "] => " + str(val)) - else: - # print dicts the hard way because otherwise the order is implementation-dependent - valkeys = list(val.keys()) - valkeys.sort() - plpy.notice("TD[" + key + "] => " + '{' + ', '.join([repr(k) + ': ' + repr(val[k]) for k in valkeys]) + '}') - -return None - -$$; - -CREATE TRIGGER show_trigger_data_trig_before -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER show_trigger_data_trig_after -AFTER INSERT OR UPDATE OR DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -CREATE TRIGGER show_trigger_data_trig_stmt -BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON trigger_test -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -insert into trigger_test values(1,'insert'); -update trigger_test set v = 'update' where i = 1; -delete from trigger_test; -truncate table trigger_test; - -DROP TRIGGER show_trigger_data_trig_stmt on trigger_test; -DROP TRIGGER show_trigger_data_trig_before on trigger_test; -DROP TRIGGER show_trigger_data_trig_after on trigger_test; - -CREATE TRIGGER show_trigger_data_trig_before -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE trigger_data(); - -CREATE TRIGGER show_trigger_data_trig_after -AFTER INSERT OR UPDATE OR DELETE ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE trigger_data(); - -insert into trigger_test_generated (i) values (1); -update trigger_test_generated set i = 11 where i = 1; -delete from trigger_test_generated; - -DROP TRIGGER show_trigger_data_trig_before ON trigger_test_generated; -DROP TRIGGER show_trigger_data_trig_after ON trigger_test_generated; - -insert into trigger_test values(1,'insert'); -CREATE VIEW trigger_test_view AS SELECT * FROM trigger_test; - -CREATE TRIGGER show_trigger_data_trig -INSTEAD OF INSERT OR UPDATE OR DELETE ON trigger_test_view -FOR EACH ROW EXECUTE PROCEDURE trigger_data(24,'skidoo view'); - -insert into trigger_test_view values(2,'insert'); -update trigger_test_view set v = 'update' where i = 1; -delete from trigger_test_view; - -DROP FUNCTION trigger_data() CASCADE; -DROP VIEW trigger_test_view; -delete from trigger_test; - - --- --- trigger error handling --- - -INSERT INTO trigger_test VALUES (0, 'zero'); - - --- returning non-string from trigger function - -CREATE FUNCTION stupid1() RETURNS trigger -AS $$ - return 37 -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger1 -BEFORE INSERT ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid1(); - -INSERT INTO trigger_test VALUES (1, 'one'); - -DROP TRIGGER stupid_trigger1 ON trigger_test; - - --- returning MODIFY from DELETE trigger - -CREATE FUNCTION stupid2() RETURNS trigger -AS $$ - return "MODIFY" -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger2 -BEFORE DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid2(); - -DELETE FROM trigger_test WHERE i = 0; - -DROP TRIGGER stupid_trigger2 ON trigger_test; - -INSERT INTO trigger_test VALUES (0, 'zero'); - - --- returning unrecognized string from trigger function - -CREATE FUNCTION stupid3() RETURNS trigger -AS $$ - return "foo" -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger3 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid3(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger3 ON trigger_test; - - --- Unicode variant - -CREATE FUNCTION stupid3u() RETURNS trigger -AS $$ - return "foo" -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger3 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid3u(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger3 ON trigger_test; - - --- deleting the TD dictionary - -CREATE FUNCTION stupid4() RETURNS trigger -AS $$ - del TD["new"] - return "MODIFY"; -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger4 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid4(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger4 ON trigger_test; - - --- TD not a dictionary - -CREATE FUNCTION stupid5() RETURNS trigger -AS $$ - TD["new"] = ['foo', 'bar'] - return "MODIFY"; -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger5 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid5(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger5 ON trigger_test; - - --- TD not having string keys - -CREATE FUNCTION stupid6() RETURNS trigger -AS $$ - TD["new"] = {1: 'foo', 2: 'bar'} - return "MODIFY"; -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger6 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid6(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger6 ON trigger_test; - - --- TD keys not corresponding to row columns - -CREATE FUNCTION stupid7() RETURNS trigger -AS $$ - TD["new"] = {'v': 'foo', 'a': 'bar'} - return "MODIFY"; -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger7 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid7(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger7 ON trigger_test; - - --- Unicode variant - -CREATE FUNCTION stupid7u() RETURNS trigger -AS $$ - TD["new"] = {'v': 'foo', 'a': 'bar'} - return "MODIFY" -$$ LANGUAGE plpython3u; - -CREATE TRIGGER stupid_trigger7 -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE stupid7u(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER stupid_trigger7 ON trigger_test; - - --- calling a trigger function directly - -SELECT stupid7(); - - --- --- Null values --- - -SELECT * FROM trigger_test; - -CREATE FUNCTION test_null() RETURNS trigger -AS $$ - TD["new"]['v'] = None - return "MODIFY" -$$ LANGUAGE plpython3u; - -CREATE TRIGGER test_null_trigger -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE test_null(); - -UPDATE trigger_test SET v = 'null' WHERE i = 0; - -DROP TRIGGER test_null_trigger ON trigger_test; - -SELECT * FROM trigger_test; - - --- --- Test that triggers honor typmod when assigning to tuple fields, --- as per an early 9.0 bug report --- - -SET DateStyle = 'ISO'; - -CREATE FUNCTION set_modif_time() RETURNS trigger AS $$ - TD['new']['modif_time'] = '2010-10-13 21:57:28.930486' - return 'MODIFY' -$$ LANGUAGE plpython3u; - -CREATE TABLE pb (a TEXT, modif_time TIMESTAMP(0) WITHOUT TIME ZONE); - -CREATE TRIGGER set_modif_time BEFORE UPDATE ON pb - FOR EACH ROW EXECUTE PROCEDURE set_modif_time(); - -INSERT INTO pb VALUES ('a', '2010-10-09 21:57:33.930486'); -SELECT * FROM pb; -UPDATE pb SET a = 'b'; -SELECT * FROM pb; - - --- triggers for tables with composite types - -CREATE TABLE comp1 (i integer, j boolean); -CREATE TYPE comp2 AS (k integer, l boolean); - -CREATE TABLE composite_trigger_test (f1 comp1, f2 comp2); - -CREATE FUNCTION composite_trigger_f() RETURNS trigger AS $$ - TD['new']['f1'] = (3, False) - TD['new']['f2'] = {'k': 7, 'l': 'yes', 'ignored': 10} - return 'MODIFY' -$$ LANGUAGE plpython3u; - -CREATE TRIGGER composite_trigger BEFORE INSERT ON composite_trigger_test - FOR EACH ROW EXECUTE PROCEDURE composite_trigger_f(); - -INSERT INTO composite_trigger_test VALUES (NULL, NULL); -SELECT * FROM composite_trigger_test; - - --- triggers with composite type columns (bug #6559) - -CREATE TABLE composite_trigger_noop_test (f1 comp1, f2 comp2); - -CREATE FUNCTION composite_trigger_noop_f() RETURNS trigger AS $$ - return 'MODIFY' -$$ LANGUAGE plpython3u; - -CREATE TRIGGER composite_trigger_noop BEFORE INSERT ON composite_trigger_noop_test - FOR EACH ROW EXECUTE PROCEDURE composite_trigger_noop_f(); - -INSERT INTO composite_trigger_noop_test VALUES (NULL, NULL); -INSERT INTO composite_trigger_noop_test VALUES (ROW(1, 'f'), NULL); -INSERT INTO composite_trigger_noop_test VALUES (ROW(NULL, 't'), ROW(1, 'f')); -SELECT * FROM composite_trigger_noop_test; - - --- nested composite types - -CREATE TYPE comp3 AS (c1 comp1, c2 comp2, m integer); - -CREATE TABLE composite_trigger_nested_test(c comp3); - -CREATE FUNCTION composite_trigger_nested_f() RETURNS trigger AS $$ - return 'MODIFY' -$$ LANGUAGE plpython3u; - -CREATE TRIGGER composite_trigger_nested BEFORE INSERT ON composite_trigger_nested_test - FOR EACH ROW EXECUTE PROCEDURE composite_trigger_nested_f(); - -INSERT INTO composite_trigger_nested_test VALUES (NULL); -INSERT INTO composite_trigger_nested_test VALUES (ROW(ROW(1, 'f'), NULL, 3)); -INSERT INTO composite_trigger_nested_test VALUES (ROW(ROW(NULL, 't'), ROW(1, 'f'), NULL)); -SELECT * FROM composite_trigger_nested_test; - --- check that using a function as a trigger over two tables works correctly -CREATE FUNCTION trig1234() RETURNS trigger LANGUAGE plpython3u AS $$ - TD["new"]["data"] = '1234' - return 'MODIFY' -$$; - -CREATE TABLE a(data text); -CREATE TABLE b(data int); -- different type conversion - -CREATE TRIGGER a_t BEFORE INSERT ON a FOR EACH ROW EXECUTE PROCEDURE trig1234(); -CREATE TRIGGER b_t BEFORE INSERT ON b FOR EACH ROW EXECUTE PROCEDURE trig1234(); - -INSERT INTO a DEFAULT VALUES; -SELECT * FROM a; -DROP TABLE a; -INSERT INTO b DEFAULT VALUES; -SELECT * FROM b; - --- check that SQL run in trigger code can see transition tables - -CREATE TABLE transition_table_test (id int, name text); -INSERT INTO transition_table_test VALUES (1, 'a'); - -CREATE FUNCTION transition_table_test_f() RETURNS trigger LANGUAGE plpython3u AS -$$ - rv = plpy.execute("SELECT * FROM old_table") - assert(rv.nrows() == 1) - plpy.info("old: " + str(rv[0]["id"]) + " -> " + rv[0]["name"]) - rv = plpy.execute("SELECT * FROM new_table") - assert(rv.nrows() == 1) - plpy.info("new: " + str(rv[0]["id"]) + " -> " + rv[0]["name"]) - return None -$$; - -CREATE TRIGGER a_t AFTER UPDATE ON transition_table_test - REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table - FOR EACH STATEMENT EXECUTE PROCEDURE transition_table_test_f(); -UPDATE transition_table_test SET name = 'b'; - -DROP TABLE transition_table_test; -DROP FUNCTION transition_table_test_f(); - - --- dealing with generated columns - -CREATE FUNCTION generated_test_func1() RETURNS trigger -LANGUAGE plpython3u -AS $$ -TD['new']['j'] = 5 # not allowed -return 'MODIFY' -$$; - -CREATE TRIGGER generated_test_trigger1 BEFORE INSERT ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE generated_test_func1(); - -TRUNCATE trigger_test_generated; -INSERT INTO trigger_test_generated (i) VALUES (1); -SELECT * FROM trigger_test_generated; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_types.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_types.sql deleted file mode 100644 index 40f4f79d99..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_types.sql +++ /dev/null @@ -1,571 +0,0 @@ --- --- Test data type behavior --- - --- --- Base/common types --- - -CREATE FUNCTION test_type_conversion_bool(x bool) RETURNS bool AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_bool(true); -SELECT * FROM test_type_conversion_bool(false); -SELECT * FROM test_type_conversion_bool(null); - - --- test various other ways to express Booleans in Python -CREATE FUNCTION test_type_conversion_bool_other(n int) RETURNS bool AS $$ -# numbers -if n == 0: - ret = 0 -elif n == 1: - ret = 5 -# strings -elif n == 2: - ret = '' -elif n == 3: - ret = 'fa' # true in Python, false in PostgreSQL -# containers -elif n == 4: - ret = [] -elif n == 5: - ret = [0] -plpy.info(ret, not not ret) -return ret -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_bool_other(0); -SELECT * FROM test_type_conversion_bool_other(1); -SELECT * FROM test_type_conversion_bool_other(2); -SELECT * FROM test_type_conversion_bool_other(3); -SELECT * FROM test_type_conversion_bool_other(4); -SELECT * FROM test_type_conversion_bool_other(5); - - -CREATE FUNCTION test_type_conversion_char(x char) RETURNS char AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_char('a'); -SELECT * FROM test_type_conversion_char(null); - - -CREATE FUNCTION test_type_conversion_int2(x int2) RETURNS int2 AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_int2(100::int2); -SELECT * FROM test_type_conversion_int2(-100::int2); -SELECT * FROM test_type_conversion_int2(null); - - -CREATE FUNCTION test_type_conversion_int4(x int4) RETURNS int4 AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_int4(100); -SELECT * FROM test_type_conversion_int4(-100); -SELECT * FROM test_type_conversion_int4(null); - - -CREATE FUNCTION test_type_conversion_int8(x int8) RETURNS int8 AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_int8(100); -SELECT * FROM test_type_conversion_int8(-100); -SELECT * FROM test_type_conversion_int8(5000000000); -SELECT * FROM test_type_conversion_int8(null); - - -CREATE FUNCTION test_type_conversion_numeric(x numeric) RETURNS numeric AS $$ -# print just the class name, not the type, to avoid differences -# between decimal and cdecimal -plpy.info(str(x), x.__class__.__name__) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_numeric(100); -SELECT * FROM test_type_conversion_numeric(-100); -SELECT * FROM test_type_conversion_numeric(100.0); -SELECT * FROM test_type_conversion_numeric(100.00); -SELECT * FROM test_type_conversion_numeric(5000000000.5); -SELECT * FROM test_type_conversion_numeric(1234567890.0987654321); -SELECT * FROM test_type_conversion_numeric(-1234567890.0987654321); -SELECT * FROM test_type_conversion_numeric(null); - - -CREATE FUNCTION test_type_conversion_float4(x float4) RETURNS float4 AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_float4(100); -SELECT * FROM test_type_conversion_float4(-100); -SELECT * FROM test_type_conversion_float4(5000.5); -SELECT * FROM test_type_conversion_float4(null); - - -CREATE FUNCTION test_type_conversion_float8(x float8) RETURNS float8 AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_float8(100); -SELECT * FROM test_type_conversion_float8(-100); -SELECT * FROM test_type_conversion_float8(5000000000.5); -SELECT * FROM test_type_conversion_float8(null); -SELECT * FROM test_type_conversion_float8(100100100.654321); - - -CREATE FUNCTION test_type_conversion_oid(x oid) RETURNS oid AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_oid(100); -SELECT * FROM test_type_conversion_oid(2147483649); -SELECT * FROM test_type_conversion_oid(null); - - -CREATE FUNCTION test_type_conversion_text(x text) RETURNS text AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_text('hello world'); -SELECT * FROM test_type_conversion_text(null); - - -CREATE FUNCTION test_type_conversion_bytea(x bytea) RETURNS bytea AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_bytea('hello world'); -SELECT * FROM test_type_conversion_bytea(E'null\\000byte'); -SELECT * FROM test_type_conversion_bytea(null); - - -CREATE FUNCTION test_type_marshal() RETURNS bytea AS $$ -import marshal -return marshal.dumps('hello world') -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_type_unmarshal(x bytea) RETURNS text AS $$ -import marshal -try: - return marshal.loads(x) -except ValueError as e: - return 'FAILED: ' + str(e) -$$ LANGUAGE plpython3u; - -SELECT test_type_unmarshal(x) FROM test_type_marshal() x; - - --- --- Domains --- - -CREATE DOMAIN booltrue AS bool CHECK (VALUE IS TRUE OR VALUE IS NULL); - -CREATE FUNCTION test_type_conversion_booltrue(x booltrue, y bool) RETURNS booltrue AS $$ -return y -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_booltrue(true, true); -SELECT * FROM test_type_conversion_booltrue(false, true); -SELECT * FROM test_type_conversion_booltrue(true, false); - - -CREATE DOMAIN uint2 AS int2 CHECK (VALUE >= 0); - -CREATE FUNCTION test_type_conversion_uint2(x uint2, y int) RETURNS uint2 AS $$ -plpy.info(x, type(x)) -return y -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_uint2(100::uint2, 50); -SELECT * FROM test_type_conversion_uint2(100::uint2, -50); -SELECT * FROM test_type_conversion_uint2(null, 1); - - -CREATE DOMAIN nnint AS int CHECK (VALUE IS NOT NULL); - -CREATE FUNCTION test_type_conversion_nnint(x nnint, y int) RETURNS nnint AS $$ -return y -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_nnint(10, 20); -SELECT * FROM test_type_conversion_nnint(null, 20); -SELECT * FROM test_type_conversion_nnint(10, null); - - -CREATE DOMAIN bytea10 AS bytea CHECK (octet_length(VALUE) = 10 AND VALUE IS NOT NULL); - -CREATE FUNCTION test_type_conversion_bytea10(x bytea10, y bytea) RETURNS bytea10 AS $$ -plpy.info(x, type(x)) -return y -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_bytea10('hello wold', 'hello wold'); -SELECT * FROM test_type_conversion_bytea10('hello world', 'hello wold'); -SELECT * FROM test_type_conversion_bytea10('hello word', 'hello world'); -SELECT * FROM test_type_conversion_bytea10(null, 'hello word'); -SELECT * FROM test_type_conversion_bytea10('hello word', null); - - --- --- Arrays --- - -CREATE FUNCTION test_type_conversion_array_int4(x int4[]) RETURNS int4[] AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_int4(ARRAY[0, 100]); -SELECT * FROM test_type_conversion_array_int4(ARRAY[0,-100,55]); -SELECT * FROM test_type_conversion_array_int4(ARRAY[NULL,1]); -SELECT * FROM test_type_conversion_array_int4(ARRAY[]::integer[]); -SELECT * FROM test_type_conversion_array_int4(NULL); -SELECT * FROM test_type_conversion_array_int4(ARRAY[[1,2,3],[4,5,6]]); -SELECT * FROM test_type_conversion_array_int4(ARRAY[[[1,2,NULL],[NULL,5,6]],[[NULL,8,9],[10,11,12]]]); -SELECT * FROM test_type_conversion_array_int4('[2:4]={1,2,3}'); - -CREATE FUNCTION test_type_conversion_array_int8(x int8[]) RETURNS int8[] AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_int8(ARRAY[[[1,2,NULL],[NULL,5,6]],[[NULL,8,9],[10,11,12]]]::int8[]); - -CREATE FUNCTION test_type_conversion_array_date(x date[]) RETURNS date[] AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_date(ARRAY[[['2016-09-21','2016-09-22',NULL],[NULL,'2016-10-21','2016-10-22']], - [[NULL,'2016-11-21','2016-10-21'],['2015-09-21','2015-09-22','2014-09-21']]]::date[]); - -CREATE FUNCTION test_type_conversion_array_timestamp(x timestamp[]) RETURNS timestamp[] AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_timestamp(ARRAY[[['2016-09-21 15:34:24.078792-04','2016-10-22 11:34:24.078795-04',NULL], - [NULL,'2016-10-21 11:34:25.078792-04','2016-10-21 11:34:24.098792-04']], - [[NULL,'2016-01-21 11:34:24.078792-04','2016-11-21 11:34:24.108792-04'], - ['2015-09-21 11:34:24.079792-04','2014-09-21 11:34:24.078792-04','2013-09-21 11:34:24.078792-04']]]::timestamp[]); - - -CREATE OR REPLACE FUNCTION pyreturnmultidemint4(h int4, i int4, j int4, k int4 ) RETURNS int4[] AS $BODY$ -m = [[[[x for x in range(h)] for y in range(i)] for z in range(j)] for w in range(k)] -plpy.info(m, type(m)) -return m -$BODY$ LANGUAGE plpython3u; - -select pyreturnmultidemint4(8,5,3,2); - -CREATE OR REPLACE FUNCTION pyreturnmultidemint8(h int4, i int4, j int4, k int4 ) RETURNS int8[] AS $BODY$ -m = [[[[x for x in range(h)] for y in range(i)] for z in range(j)] for w in range(k)] -plpy.info(m, type(m)) -return m -$BODY$ LANGUAGE plpython3u; - -select pyreturnmultidemint8(5,5,3,2); - -CREATE OR REPLACE FUNCTION pyreturnmultidemfloat4(h int4, i int4, j int4, k int4 ) RETURNS float4[] AS $BODY$ -m = [[[[x for x in range(h)] for y in range(i)] for z in range(j)] for w in range(k)] -plpy.info(m, type(m)) -return m -$BODY$ LANGUAGE plpython3u; - -select pyreturnmultidemfloat4(6,5,3,2); - -CREATE OR REPLACE FUNCTION pyreturnmultidemfloat8(h int4, i int4, j int4, k int4 ) RETURNS float8[] AS $BODY$ -m = [[[[x for x in range(h)] for y in range(i)] for z in range(j)] for w in range(k)] -plpy.info(m, type(m)) -return m -$BODY$ LANGUAGE plpython3u; - -select pyreturnmultidemfloat8(7,5,3,2); - -CREATE FUNCTION test_type_conversion_array_text(x text[]) RETURNS text[] AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_text(ARRAY['foo', 'bar']); -SELECT * FROM test_type_conversion_array_text(ARRAY[['foo', 'bar'],['foo2', 'bar2']]); - - -CREATE FUNCTION test_type_conversion_array_bytea(x bytea[]) RETURNS bytea[] AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_bytea(ARRAY[E'\\xdeadbeef'::bytea, NULL]); - - -CREATE FUNCTION test_type_conversion_array_mixed1() RETURNS text[] AS $$ -return [123, 'abc'] -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_mixed1(); - - -CREATE FUNCTION test_type_conversion_array_mixed2() RETURNS int[] AS $$ -return [123, 'abc'] -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_mixed2(); - -CREATE FUNCTION test_type_conversion_mdarray_malformed() RETURNS int[] AS $$ -return [[1,2,3],[4,5]] -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_mdarray_malformed(); - -CREATE FUNCTION test_type_conversion_mdarray_toodeep() RETURNS int[] AS $$ -return [[[[[[[1]]]]]]] -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_mdarray_toodeep(); - - -CREATE FUNCTION test_type_conversion_array_record() RETURNS type_record[] AS $$ -return [{'first': 'one', 'second': 42}, {'first': 'two', 'second': 11}] -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_record(); - - -CREATE FUNCTION test_type_conversion_array_string() RETURNS text[] AS $$ -return 'abc' -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_string(); - -CREATE FUNCTION test_type_conversion_array_tuple() RETURNS text[] AS $$ -return ('abc', 'def') -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_tuple(); - -CREATE FUNCTION test_type_conversion_array_error() RETURNS int[] AS $$ -return 5 -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_error(); - - --- --- Domains over arrays --- - -CREATE DOMAIN ordered_pair_domain AS integer[] CHECK (array_length(VALUE,1)=2 AND VALUE[1] < VALUE[2]); - -CREATE FUNCTION test_type_conversion_array_domain(x ordered_pair_domain) RETURNS ordered_pair_domain AS $$ -plpy.info(x, type(x)) -return x -$$ LANGUAGE plpython3u; - -SELECT * FROM test_type_conversion_array_domain(ARRAY[0, 100]::ordered_pair_domain); -SELECT * FROM test_type_conversion_array_domain(NULL::ordered_pair_domain); - -CREATE FUNCTION test_type_conversion_array_domain_check_violation() RETURNS ordered_pair_domain AS $$ -return [2,1] -$$ LANGUAGE plpython3u; -SELECT * FROM test_type_conversion_array_domain_check_violation(); - - --- --- Arrays of domains --- - -CREATE FUNCTION test_read_uint2_array(x uint2[]) RETURNS uint2 AS $$ -plpy.info(x, type(x)) -return x[0] -$$ LANGUAGE plpython3u; - -select test_read_uint2_array(array[1::uint2]); - -CREATE FUNCTION test_build_uint2_array(x int2) RETURNS uint2[] AS $$ -return [x, x] -$$ LANGUAGE plpython3u; - -select test_build_uint2_array(1::int2); -select test_build_uint2_array(-1::int2); -- fail - --- --- ideally this would work, but for now it doesn't, because the return value --- is [[2,4], [2,4]] which our conversion code thinks should become a 2-D --- integer array, not an array of arrays. --- -CREATE FUNCTION test_type_conversion_domain_array(x integer[]) - RETURNS ordered_pair_domain[] AS $$ -return [x, x] -$$ LANGUAGE plpython3u; - -select test_type_conversion_domain_array(array[2,4]); -select test_type_conversion_domain_array(array[4,2]); -- fail - -CREATE FUNCTION test_type_conversion_domain_array2(x ordered_pair_domain) - RETURNS integer AS $$ -plpy.info(x, type(x)) -return x[1] -$$ LANGUAGE plpython3u; - -select test_type_conversion_domain_array2(array[2,4]); -select test_type_conversion_domain_array2(array[4,2]); -- fail - -CREATE FUNCTION test_type_conversion_array_domain_array(x ordered_pair_domain[]) - RETURNS ordered_pair_domain AS $$ -plpy.info(x, type(x)) -return x[0] -$$ LANGUAGE plpython3u; - -select test_type_conversion_array_domain_array(array[array[2,4]::ordered_pair_domain]); - - ---- ---- Composite types ---- - -CREATE TABLE employee ( - name text, - basesalary integer, - bonus integer -); - -INSERT INTO employee VALUES ('John', 100, 10), ('Mary', 200, 10); - -CREATE OR REPLACE FUNCTION test_composite_table_input(e employee) RETURNS integer AS $$ -return e['basesalary'] + e['bonus'] -$$ LANGUAGE plpython3u; - -SELECT name, test_composite_table_input(employee.*) FROM employee; - -ALTER TABLE employee DROP bonus; - -SELECT name, test_composite_table_input(employee.*) FROM employee; - -ALTER TABLE employee ADD bonus integer; -UPDATE employee SET bonus = 10; - -SELECT name, test_composite_table_input(employee.*) FROM employee; - -CREATE TYPE named_pair AS ( - i integer, - j integer -); - -CREATE OR REPLACE FUNCTION test_composite_type_input(p named_pair) RETURNS integer AS $$ -return sum(p.values()) -$$ LANGUAGE plpython3u; - -SELECT test_composite_type_input(row(1, 2)); - -ALTER TYPE named_pair RENAME TO named_pair_2; - -SELECT test_composite_type_input(row(1, 2)); - - --- --- Domains within composite --- - -CREATE TYPE nnint_container AS (f1 int, f2 nnint); - -CREATE FUNCTION nnint_test(x int, y int) RETURNS nnint_container AS $$ -return {'f1': x, 'f2': y} -$$ LANGUAGE plpython3u; - -SELECT nnint_test(null, 3); -SELECT nnint_test(3, null); -- fail - - --- --- Domains of composite --- - -CREATE DOMAIN ordered_named_pair AS named_pair_2 CHECK((VALUE).i <= (VALUE).j); - -CREATE FUNCTION read_ordered_named_pair(p ordered_named_pair) RETURNS integer AS $$ -return p['i'] + p['j'] -$$ LANGUAGE plpython3u; - -SELECT read_ordered_named_pair(row(1, 2)); -SELECT read_ordered_named_pair(row(2, 1)); -- fail - -CREATE FUNCTION build_ordered_named_pair(i int, j int) RETURNS ordered_named_pair AS $$ -return {'i': i, 'j': j} -$$ LANGUAGE plpython3u; - -SELECT build_ordered_named_pair(1,2); -SELECT build_ordered_named_pair(2,1); -- fail - -CREATE FUNCTION build_ordered_named_pairs(i int, j int) RETURNS ordered_named_pair[] AS $$ -return [{'i': i, 'j': j}, {'i': i, 'j': j+1}] -$$ LANGUAGE plpython3u; - -SELECT build_ordered_named_pairs(1,2); -SELECT build_ordered_named_pairs(2,1); -- fail - - --- --- Prepared statements --- - -CREATE OR REPLACE FUNCTION test_prep_bool_input() RETURNS int -LANGUAGE plpython3u -AS $$ -plan = plpy.prepare("SELECT CASE WHEN $1 THEN 1 ELSE 0 END AS val", ['boolean']) -rv = plpy.execute(plan, ['fa'], 5) # 'fa' is true in Python -return rv[0]['val'] -$$; - -SELECT test_prep_bool_input(); -- 1 - - -CREATE OR REPLACE FUNCTION test_prep_bool_output() RETURNS bool -LANGUAGE plpython3u -AS $$ -plan = plpy.prepare("SELECT $1 = 1 AS val", ['int']) -rv = plpy.execute(plan, [0], 5) -plpy.info(rv[0]) -return rv[0]['val'] -$$; - -SELECT test_prep_bool_output(); -- false - - -CREATE OR REPLACE FUNCTION test_prep_bytea_input(bb bytea) RETURNS int -LANGUAGE plpython3u -AS $$ -plan = plpy.prepare("SELECT octet_length($1) AS val", ['bytea']) -rv = plpy.execute(plan, [bb], 5) -return rv[0]['val'] -$$; - -SELECT test_prep_bytea_input(E'a\\000b'); -- 3 (embedded null formerly truncated value) - - -CREATE OR REPLACE FUNCTION test_prep_bytea_output() RETURNS bytea -LANGUAGE plpython3u -AS $$ -plan = plpy.prepare("SELECT decode('aa00bb', 'hex') AS val") -rv = plpy.execute(plan, [], 5) -plpy.info(rv[0]) -return rv[0]['val'] -$$; - -SELECT test_prep_bytea_output(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_void.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_void.sql deleted file mode 100644 index 5a1a6711fb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Fplpython%2Fsql%2Fplpython_void.sql +++ /dev/null @@ -1,22 +0,0 @@ --- --- Tests for functions that return void --- - -CREATE FUNCTION test_void_func1() RETURNS void AS $$ -x = 10 -$$ LANGUAGE plpython3u; - --- illegal: can't return non-None value in void-returning func -CREATE FUNCTION test_void_func2() RETURNS void AS $$ -return 10 -$$ LANGUAGE plpython3u; - -CREATE FUNCTION test_return_none() RETURNS int AS $$ -None -$$ LANGUAGE plpython3u; - - --- Tests for functions returning void -SELECT test_void_func1(), test_void_func1() IS NULL AS "is null"; -SELECT test_void_func2(); -- should fail -SELECT test_return_none(), test_return_none() IS NULL AS "is null"; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_call.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_call.sql deleted file mode 100644 index 37efbdefc2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_call.sql +++ /dev/null @@ -1,78 +0,0 @@ -CREATE PROCEDURE test_proc1() -LANGUAGE pltcl -AS $$ -unset -$$; - -CALL test_proc1(); - - -CREATE PROCEDURE test_proc2() -LANGUAGE pltcl -AS $$ -return 5 -$$; - -CALL test_proc2(); - - -CREATE TABLE test1 (a int); - -CREATE PROCEDURE test_proc3(x int) -LANGUAGE pltcl -AS $$ -spi_exec "INSERT INTO test1 VALUES ($1)" -$$; - -CALL test_proc3(55); - -SELECT * FROM test1; - - --- output arguments - -CREATE PROCEDURE test_proc5(INOUT a text) -LANGUAGE pltcl -AS $$ -set aa [concat $1 "+" $1] -return [list a $aa] -$$; - -CALL test_proc5('abc'); - - -CREATE PROCEDURE test_proc6(a int, INOUT b int, INOUT c int) -LANGUAGE pltcl -AS $$ -set bb [expr $2 * $1] -set cc [expr $3 * $1] -return [list b $bb c $cc] -$$; - -CALL test_proc6(2, 3, 4); - - --- OUT parameters - -CREATE PROCEDURE test_proc9(IN a int, OUT b int) -LANGUAGE pltcl -AS $$ -elog NOTICE "a: $1" -return [list b [expr {$1 * 2}]] -$$; - -DO $$ -DECLARE _a int; _b int; -BEGIN - _a := 10; _b := 30; - CALL test_proc9(_a, _b); - RAISE NOTICE '_a: %, _b: %', _a, _b; -END -$$; - - -DROP PROCEDURE test_proc1; -DROP PROCEDURE test_proc2; -DROP PROCEDURE test_proc3; - -DROP TABLE test1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_queries.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_queries.sql deleted file mode 100644 index bbd2d97999..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_queries.sql +++ /dev/null @@ -1,166 +0,0 @@ --- suppress CONTEXT so that function OIDs aren't in output -\set VERBOSITY terse - --- Test composite-type arguments -select tcl_composite_arg_ref1(row('tkey', 42, 'ref2')); -select tcl_composite_arg_ref2(row('tkey', 42, 'ref2')); - --- More tests for composite argument/result types - -create domain d_comp1 as T_comp1 check ((value).ref1 > 0); - -create function tcl_record_arg(record, fldname text) returns int as ' - return $1($2) -' language pltcl; - -select tcl_record_arg(row('tkey', 42, 'ref2')::T_comp1, 'ref1'); -select tcl_record_arg(row('tkey', 42, 'ref2')::d_comp1, 'ref1'); -select tcl_record_arg(row(2,4), 'f2'); - -create function tcl_cdomain_arg(d_comp1) returns int as ' - return $1(ref1) -' language pltcl; - -select tcl_cdomain_arg(row('tkey', 42, 'ref2')); -select tcl_cdomain_arg(row('tkey', 42, 'ref2')::T_comp1); -select tcl_cdomain_arg(row('tkey', -1, 'ref2')); -- fail - --- Test argisnull primitive -select tcl_argisnull('foo'); -select tcl_argisnull(''); -select tcl_argisnull(null); - --- test some error cases -create function tcl_error(out a int, out b int) as $$return {$$ language pltcl; -select tcl_error(); - -create function bad_record(out a text, out b text) as $$return [list a]$$ language pltcl; -select bad_record(); - -create function bad_field(out a text, out b text) as $$return [list a 1 b 2 cow 3]$$ language pltcl; -select bad_field(); - --- test compound return -select * from tcl_test_cube_squared(5); - --- test SRF -select * from tcl_test_squared_rows(0,5); - -select * from tcl_test_sequence(0,5) as a; - -select 1, tcl_test_sequence(0,5); - -create function non_srf() returns int as $$return_next 1$$ language pltcl; -select non_srf(); - -create function bad_record_srf(out a text, out b text) returns setof record as $$ -return_next [list a] -$$ language pltcl; -select bad_record_srf(); - -create function bad_field_srf(out a text, out b text) returns setof record as $$ -return_next [list a 1 b 2 cow 3] -$$ language pltcl; -select bad_field_srf(); - --- test composite and domain-over-composite results -create function tcl_composite_result(int) returns T_comp1 as $$ -return [list tkey tkey1 ref1 $1 ref2 ref22] -$$ language pltcl; -select tcl_composite_result(1001); -select * from tcl_composite_result(1002); - -create function tcl_dcomposite_result(int) returns d_comp1 as $$ -return [list tkey tkey2 ref1 $1 ref2 ref42] -$$ language pltcl; -select tcl_dcomposite_result(1001); -select * from tcl_dcomposite_result(1002); -select * from tcl_dcomposite_result(-1); -- fail - -create function tcl_record_result(int) returns record as $$ -return [list q1 sometext q2 $1 q3 moretext] -$$ language pltcl; -select tcl_record_result(42); -- fail -select * from tcl_record_result(42); -- fail -select * from tcl_record_result(42) as (q1 text, q2 int, q3 text); -select * from tcl_record_result(42) as (q1 text, q2 int, q3 text, q4 int); -select * from tcl_record_result(42) as (q1 text, q2 int, q4 int); -- fail - --- test quote -select tcl_eval('quote foo bar'); -select tcl_eval('quote [format %c 39]'); -select tcl_eval('quote [format %c 92]'); - --- Test argisnull -select tcl_eval('argisnull'); -select tcl_eval('argisnull 14'); -select tcl_eval('argisnull abc'); - --- Test return_null -select tcl_eval('return_null 14'); - --- Test spi_exec -select tcl_eval('spi_exec'); -select tcl_eval('spi_exec -count'); -select tcl_eval('spi_exec -array'); -select tcl_eval('spi_exec -count abc'); -select tcl_eval('spi_exec query loop body toomuch'); -select tcl_eval('spi_exec "begin; rollback;"'); - --- Test spi_execp -select tcl_eval('spi_execp'); -select tcl_eval('spi_execp -count'); -select tcl_eval('spi_execp -array'); -select tcl_eval('spi_execp -count abc'); -select tcl_eval('spi_execp -nulls'); -select tcl_eval('spi_execp ""'); - --- test spi_prepare -select tcl_eval('spi_prepare'); -select tcl_eval('spi_prepare a b'); -select tcl_eval('spi_prepare a "b {"'); -select tcl_error_handling_test($tcl$spi_prepare "select moo" []$tcl$); - --- test full error text -select tcl_error_handling_test($tcl$ -spi_exec "DO $$ -BEGIN -RAISE 'my message' - USING HINT = 'my hint' - , DETAIL = 'my detail' - , SCHEMA = 'my schema' - , TABLE = 'my table' - , COLUMN = 'my column' - , CONSTRAINT = 'my constraint' - , DATATYPE = 'my datatype' -; -END$$;" -$tcl$); - --- verify tcl_error_handling_test() properly reports non-postgres errors -select tcl_error_handling_test('moo'); - --- test elog -select tcl_eval('elog'); -select tcl_eval('elog foo bar'); - --- test forced error -select tcl_eval('error "forced error"'); - --- test loop control in spi_exec[p] -select tcl_spi_exec(true, 'break'); -select tcl_spi_exec(true, 'continue'); -select tcl_spi_exec(true, 'error'); -select tcl_spi_exec(true, 'return'); -select tcl_spi_exec(false, 'break'); -select tcl_spi_exec(false, 'continue'); -select tcl_spi_exec(false, 'error'); -select tcl_spi_exec(false, 'return'); - --- forcibly run the Tcl event loop for awhile, to check that we have not --- messed things up too badly by disabling the Tcl notifier subsystem -select tcl_eval($$ - unset -nocomplain ::tcl_vwait - after 100 {set ::tcl_vwait 1} - vwait ::tcl_vwait - unset -nocomplain ::tcl_vwait$$); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_setup.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_setup.sql deleted file mode 100644 index e9f59989b5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_setup.sql +++ /dev/null @@ -1,278 +0,0 @@ -create table T_comp1 ( - tkey char(10), - ref1 int4, - ref2 char(20) -); - -create function tcl_composite_arg_ref1(T_comp1) returns int as ' - return $1(ref1) -' language pltcl; - -create function tcl_composite_arg_ref2(T_comp1) returns text as ' - return $1(ref2) -' language pltcl; - -create function tcl_argisnull(text) returns bool as ' - argisnull 1 -' language pltcl; - - -create function tcl_int4add(int4,int4) returns int4 as ' - return [expr $1 + $2] -' language pltcl; - --- We use split(n) as a quick-and-dirty way of parsing the input array --- value, which comes in as a string like '{1,2}'. There are better ways... - -create function tcl_int4_accum(int4[], int4) returns int4[] as ' - set state [split $1 "{,}"] - set newsum [expr {[lindex $state 1] + $2}] - set newcnt [expr {[lindex $state 2] + 1}] - return "{$newsum,$newcnt}" -' language pltcl; - -create function tcl_int4_avg(int4[]) returns int4 as ' - set state [split $1 "{,}"] - if {[lindex $state 2] == 0} { return_null } - return [expr {[lindex $state 1] / [lindex $state 2]}] -' language pltcl; - -create aggregate tcl_avg ( - sfunc = tcl_int4_accum, - basetype = int4, - stype = int4[], - finalfunc = tcl_int4_avg, - initcond = '{0,0}' - ); - -create aggregate tcl_sum ( - sfunc = tcl_int4add, - basetype = int4, - stype = int4, - initcond1 = 0 - ); - -create function tcl_int4lt(int4,int4) returns bool as ' - if {$1 < $2} { - return t - } - return f -' language pltcl; - -create function tcl_int4le(int4,int4) returns bool as ' - if {$1 <= $2} { - return t - } - return f -' language pltcl; - -create function tcl_int4eq(int4,int4) returns bool as ' - if {$1 == $2} { - return t - } - return f -' language pltcl; - -create function tcl_int4ge(int4,int4) returns bool as ' - if {$1 >= $2} { - return t - } - return f -' language pltcl; - -create function tcl_int4gt(int4,int4) returns bool as ' - if {$1 > $2} { - return t - } - return f -' language pltcl; - -create operator @< ( - leftarg = int4, - rightarg = int4, - procedure = tcl_int4lt - ); - -create operator @<= ( - leftarg = int4, - rightarg = int4, - procedure = tcl_int4le - ); - -create operator @= ( - leftarg = int4, - rightarg = int4, - procedure = tcl_int4eq - ); - -create operator @>= ( - leftarg = int4, - rightarg = int4, - procedure = tcl_int4ge - ); - -create operator @> ( - leftarg = int4, - rightarg = int4, - procedure = tcl_int4gt - ); - -create function tcl_int4cmp(int4,int4) returns int4 as ' - if {$1 < $2} { - return -1 - } - if {$1 > $2} { - return 1 - } - return 0 -' language pltcl; - -CREATE OPERATOR CLASS tcl_int4_ops - FOR TYPE int4 USING btree AS - OPERATOR 1 @<, - OPERATOR 2 @<=, - OPERATOR 3 @=, - OPERATOR 4 @>=, - OPERATOR 5 @>, - FUNCTION 1 tcl_int4cmp(int4,int4) ; - --- --- Test usage of Tcl's "clock" command. In recent Tcl versions this --- command fails without working "unknown" support, so it's a good canary --- for initialization problems. --- -create function tcl_date_week(int4,int4,int4) returns text as $$ - return [clock format [clock scan "$2/$3/$1"] -format "%U"] -$$ language pltcl immutable; - -select tcl_date_week(2010,1,26); -select tcl_date_week(2001,10,24); - --- test pltcl event triggers -create function tclsnitch() returns event_trigger language pltcl as $$ - elog NOTICE "tclsnitch: $TG_event $TG_tag" -$$; - -create event trigger tcl_a_snitch on ddl_command_start execute procedure tclsnitch(); -create event trigger tcl_b_snitch on ddl_command_end execute procedure tclsnitch(); - -create function foobar() returns int language sql as $$select 1;$$; -alter function foobar() cost 77; -drop function foobar(); - -create table foo(); -drop table foo; - -drop event trigger tcl_a_snitch; -drop event trigger tcl_b_snitch; - -create function tcl_test_cube_squared(in int, out squared int, out cubed int) as $$ - return [list squared [expr {$1 * $1}] cubed [expr {$1 * $1 * $1}]] -$$ language pltcl; - -create function tcl_test_squared_rows(int,int) returns table (x int, y int) as $$ - for {set i $1} {$i < $2} {incr i} { - return_next [list y [expr {$i * $i}] x $i] - } -$$ language pltcl; - -create function tcl_test_sequence(int,int) returns setof int as $$ - for {set i $1} {$i < $2} {incr i} { - return_next $i - } -$$ language pltcl; - -create function tcl_eval(string text) returns text as $$ - eval $1 -$$ language pltcl; - --- test use of errorCode in error handling -create function tcl_error_handling_test(text) returns text -language pltcl -as $function$ - if {[catch $1 err]} { - # If not a Postgres error, just return the basic error message - if {[lindex $::errorCode 0] != "POSTGRES"} { - return $err - } - - # Get rid of keys that can't be expected to remain constant - array set myArray $::errorCode - unset myArray(POSTGRES) - unset -nocomplain myArray(funcname) - unset -nocomplain myArray(filename) - unset -nocomplain myArray(lineno) - - # Format into something nicer - set vals [] - foreach {key} [lsort [array names myArray]] { - set value [string map {"\n" "\n\t"} $myArray($key)] - lappend vals "$key: $value" - } - return [join $vals "\n"] - } else { - return "no error" - } -$function$; - --- test spi_exec and spi_execp with -array -create function tcl_spi_exec( - prepare boolean, - action text -) -returns void language pltcl AS $function$ -set query "select * from (values (1,'foo'),(2,'bar'),(3,'baz')) v(col1,col2)" -if {$1 == "t"} { - set prep [spi_prepare $query {}] - spi_execp -array A $prep { - elog NOTICE "col1 $A(col1), col2 $A(col2)" - - switch $A(col1) { - 2 { - elog NOTICE "action: $2" - switch $2 { - break { - break - } - continue { - continue - } - return { - return - } - error { - error "error message" - } - } - error "should not get here" - } - } - } -} else { - spi_exec -array A $query { - elog NOTICE "col1 $A(col1), col2 $A(col2)" - - switch $A(col1) { - 2 { - elog NOTICE "action: $2" - switch $2 { - break { - break - } - continue { - continue - } - return { - return - } - error { - error "error message" - } - } - error "should not get here" - } - } - } -} -elog NOTICE "end of function" -$function$; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_start_proc.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_start_proc.sql deleted file mode 100644 index 7a8e68e266..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_start_proc.sql +++ /dev/null @@ -1,21 +0,0 @@ --- --- Test start_proc execution --- - -SET pltcl.start_proc = 'no_such_function'; - -select tcl_int4add(1, 2); -select tcl_int4add(1, 2); - -create function tcl_initialize() returns void as -$$ elog NOTICE "in tcl_initialize" $$ language pltcl SECURITY DEFINER; - -SET pltcl.start_proc = 'public.tcl_initialize'; - -select tcl_int4add(1, 2); -- fail - -create or replace function tcl_initialize() returns void as -$$ elog NOTICE "in tcl_initialize" $$ language pltcl; - -select tcl_int4add(1, 2); -select tcl_int4add(1, 2); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_subxact.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_subxact.sql deleted file mode 100644 index 0625736ea4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_subxact.sql +++ /dev/null @@ -1,95 +0,0 @@ --- --- Test explicit subtransactions --- - -CREATE TABLE subtransaction_tbl ( - i integer -); - --- --- We use this wrapper to catch errors and return errormsg only, --- because values of $::errorinfo variable contain procedure name which --- includes OID, so it's not stable --- -CREATE FUNCTION pltcl_wrapper(statement text) RETURNS text -AS $$ - if [catch {spi_exec $1} msg] { - return "ERROR: $msg" - } else { - return "SUCCESS: $msg" - } -$$ LANGUAGE pltcl; - --- Test subtransaction successfully committed - -CREATE FUNCTION subtransaction_ctx_success() RETURNS void -AS $$ - spi_exec "INSERT INTO subtransaction_tbl VALUES(1)" - subtransaction { - spi_exec "INSERT INTO subtransaction_tbl VALUES(2)" - } -$$ LANGUAGE pltcl; - -BEGIN; -INSERT INTO subtransaction_tbl VALUES(0); -SELECT subtransaction_ctx_success(); -COMMIT; -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - --- Test subtransaction rollback - -CREATE FUNCTION subtransaction_ctx_test(what_error text = NULL) RETURNS void -AS $$ - spi_exec "INSERT INTO subtransaction_tbl VALUES (1)" - subtransaction { - spi_exec "INSERT INTO subtransaction_tbl VALUES (2)" - if {$1 == "SPI"} { - spi_exec "INSERT INTO subtransaction_tbl VALUES ('oops')" - } elseif { $1 == "Tcl"} { - elog ERROR "Tcl error" - } - } -$$ LANGUAGE pltcl; - -SELECT pltcl_wrapper('SELECT subtransaction_ctx_test()'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - -SELECT pltcl_wrapper('SELECT subtransaction_ctx_test(''SPI'')'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - -SELECT pltcl_wrapper('SELECT subtransaction_ctx_test(''Tcl'')'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - --- Nested subtransactions - -CREATE FUNCTION subtransaction_nested_test(swallow boolean = 'f') RETURNS text -AS $$ -spi_exec "INSERT INTO subtransaction_tbl VALUES (1)" -subtransaction { - spi_exec "INSERT INTO subtransaction_tbl VALUES (2)" - if [catch { - subtransaction { - spi_exec "INSERT INTO subtransaction_tbl VALUES (3)" - spi_exec "error" - } - } errormsg] { - if {$1 != "t"} { - error $errormsg $::errorInfo $::errorCode - } - elog NOTICE "Swallowed $errormsg" - } -} -return "ok" -$$ LANGUAGE pltcl; - -SELECT pltcl_wrapper('SELECT subtransaction_nested_test()'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; - -SELECT pltcl_wrapper('SELECT subtransaction_nested_test(''t'')'); -SELECT * FROM subtransaction_tbl; -TRUNCATE subtransaction_tbl; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_transaction.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_transaction.sql deleted file mode 100644 index bd759850a7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_transaction.sql +++ /dev/null @@ -1,135 +0,0 @@ --- suppress CONTEXT so that function OIDs aren't in output -\set VERBOSITY terse - -CREATE TABLE test1 (a int, b text); - - -CREATE PROCEDURE transaction_test1() -LANGUAGE pltcl -AS $$ -for {set i 0} {$i < 10} {incr i} { - spi_exec "INSERT INTO test1 (a) VALUES ($i)" - if {$i % 2 == 0} { - commit - } else { - rollback - } -} -$$; - -CALL transaction_test1(); - -SELECT * FROM test1; - - -TRUNCATE test1; - --- not allowed in a function -CREATE FUNCTION transaction_test2() RETURNS int -LANGUAGE pltcl -AS $$ -for {set i 0} {$i < 10} {incr i} { - spi_exec "INSERT INTO test1 (a) VALUES ($i)" - if {$i % 2 == 0} { - commit - } else { - rollback - } -} -return 1 -$$; - -SELECT transaction_test2(); - -SELECT * FROM test1; - - --- also not allowed if procedure is called from a function -CREATE FUNCTION transaction_test3() RETURNS int -LANGUAGE pltcl -AS $$ -spi_exec "CALL transaction_test1()" -return 1 -$$; - -SELECT transaction_test3(); - -SELECT * FROM test1; - - --- commit inside cursor loop -CREATE TABLE test2 (x int); -INSERT INTO test2 VALUES (0), (1), (2), (3), (4); - -TRUNCATE test1; - -CREATE PROCEDURE transaction_test4a() -LANGUAGE pltcl -AS $$ -spi_exec -array row "SELECT * FROM test2 ORDER BY x" { - spi_exec "INSERT INTO test1 (a) VALUES ($row(x))" - commit -} -$$; - -CALL transaction_test4a(); - -SELECT * FROM test1; - - --- rollback inside cursor loop -TRUNCATE test1; - -CREATE PROCEDURE transaction_test4b() -LANGUAGE pltcl -AS $$ -spi_exec -array row "SELECT * FROM test2 ORDER BY x" { - spi_exec "INSERT INTO test1 (a) VALUES ($row(x))" - rollback -} -$$; - -CALL transaction_test4b(); - -SELECT * FROM test1; - - --- check handling of an error during COMMIT -CREATE TABLE testpk (id int PRIMARY KEY); -CREATE TABLE testfk(f1 int REFERENCES testpk DEFERRABLE INITIALLY DEFERRED); - -CREATE PROCEDURE transaction_testfk() -LANGUAGE pltcl -AS $$ -# this insert will fail during commit: -spi_exec "INSERT INTO testfk VALUES (0)" -commit -elog WARNING "should not get here" -$$; - -CALL transaction_testfk(); - -SELECT * FROM testpk; -SELECT * FROM testfk; - -CREATE OR REPLACE PROCEDURE transaction_testfk() -LANGUAGE pltcl -AS $$ -# this insert will fail during commit: -spi_exec "INSERT INTO testfk VALUES (0)" -if [catch {commit} msg] { - elog INFO $msg -} -# these inserts should work: -spi_exec "INSERT INTO testpk VALUES (1)" -spi_exec "INSERT INTO testfk VALUES (1)" -$$; - -CALL transaction_testfk(); - -SELECT * FROM testpk; -SELECT * FROM testfk; - - -DROP TABLE test1; -DROP TABLE test2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_trigger.sql deleted file mode 100644 index 2db75a333a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_trigger.sql +++ /dev/null @@ -1,603 +0,0 @@ --- suppress CONTEXT so that function OIDs aren't in output -\set VERBOSITY terse - --- --- Create the tables used in the test queries --- --- T_pkey1 is the primary key table for T_dta1. Entries from T_pkey1 --- Cannot be changed or deleted if they are referenced from T_dta1. --- --- T_pkey2 is the primary key table for T_dta2. If the key values in --- T_pkey2 are changed, the references in T_dta2 follow. If entries --- are deleted, the referencing entries from T_dta2 are deleted too. --- The values for field key2 in T_pkey2 are silently converted to --- upper case on insert/update. --- -create table T_pkey1 ( - key1 int4, - key2 char(20), - txt char(40) -); - -create table T_pkey2 ( - key1 int4, - key2 char(20), - txt char(40) -); - -create table T_dta1 ( - tkey char(10), - ref1 int4, - ref2 char(20) -); - -create table T_dta2 ( - tkey char(10), - ref1 int4, - ref2 char(20) -); - - --- --- Function to check key existence in T_pkey1 --- -create function check_pkey1_exists(int4, bpchar) returns bool as E' - if {![info exists GD]} { - set GD(plan) [spi_prepare \\ - "select 1 from T_pkey1 \\ - where key1 = \\$1 and key2 = \\$2" \\ - {int4 bpchar}] - } - - set n [spi_execp -count 1 $GD(plan) [list $1 $2]] - - if {$n > 0} { - return "t" - } - return "f" -' language pltcl; - - --- dump trigger data - -CREATE TABLE trigger_test ( - i int, - v text, - dropme text, - test_skip boolean DEFAULT false, - test_return_null boolean DEFAULT false, - test_argisnull boolean DEFAULT false -); --- Make certain dropped attributes are handled correctly -ALTER TABLE trigger_test DROP dropme; - -CREATE TABLE trigger_test_generated ( - i int, - j int GENERATED ALWAYS AS (i * 2) STORED -); - -CREATE VIEW trigger_test_view AS SELECT i, v FROM trigger_test; - -CREATE FUNCTION trigger_data() returns trigger language pltcl as $_$ - if {$TG_table_name eq "trigger_test" && $TG_level eq "ROW" && $TG_op ne "DELETE"} { - # Special case tests - if {$NEW(test_return_null) eq "t" } { - return_null - } - if {$NEW(test_argisnull) eq "t" } { - set should_error [argisnull 1] - } - if {$NEW(test_skip) eq "t" } { - elog NOTICE "SKIPPING OPERATION $TG_op" - return SKIP - } - } - - if { [info exists TG_relid] } { - set TG_relid "bogus:12345" - } - - set dnames [info locals {[a-zA-Z]*} ] - - foreach key [lsort $dnames] { - - if { [array exists $key] } { - set str "{" - foreach akey [lsort [ array names $key ] ] { - if {[string length $str] > 1} { set str "$str, " } - set cmd "($akey)" - set cmd "set val \$$key$cmd" - eval $cmd - set str "$str$akey: $val" - } - set str "$str}" - elog NOTICE "$key: $str" - } else { - set val [eval list "\$$key" ] - elog NOTICE "$key: $val" - } - } - - - return OK - -$_$; - -CREATE TRIGGER show_trigger_data_trig -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); -CREATE TRIGGER statement_trigger -BEFORE INSERT OR UPDATE OR DELETE OR TRUNCATE ON trigger_test -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_data(42,'statement trigger'); - -CREATE TRIGGER show_trigger_data_trig_before -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE trigger_data(); -CREATE TRIGGER show_trigger_data_trig_after -AFTER INSERT OR UPDATE OR DELETE ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE trigger_data(); - -CREATE TRIGGER show_trigger_data_view_trig -INSTEAD OF INSERT OR UPDATE OR DELETE ON trigger_test_view -FOR EACH ROW EXECUTE PROCEDURE trigger_data(24,'skidoo view'); - --- --- Trigger function on every change to T_pkey1 --- -create function trig_pkey1_before() returns trigger as E' - # - # Create prepared plans on the first call - # - if {![info exists GD]} { - # - # Plan to check for duplicate key in T_pkey1 - # - set GD(plan_pkey1) [spi_prepare \\ - "select check_pkey1_exists(\\$1, \\$2) as ret" \\ - {int4 bpchar}] - # - # Plan to check for references from T_dta1 - # - set GD(plan_dta1) [spi_prepare \\ - "select 1 from T_dta1 \\ - where ref1 = \\$1 and ref2 = \\$2" \\ - {int4 bpchar}] - } - - # - # Initialize flags - # - set check_old_ref 0 - set check_new_dup 0 - - switch $TG_op { - INSERT { - # - # Must check for duplicate key on INSERT - # - set check_new_dup 1 - } - UPDATE { - # - # Must check for duplicate key on UPDATE only if - # the key changes. In that case we must check for - # references to OLD values too. - # - if {[string compare $NEW(key1) $OLD(key1)] != 0} { - set check_old_ref 1 - set check_new_dup 1 - } - if {[string compare $NEW(key2) $OLD(key2)] != 0} { - set check_old_ref 1 - set check_new_dup 1 - } - } - DELETE { - # - # Must only check for references to OLD on DELETE - # - set check_old_ref 1 - } - } - - if {$check_new_dup} { - # - # Check for duplicate key - # - spi_execp -count 1 $GD(plan_pkey1) [list $NEW(key1) $NEW(key2)] - if {$ret == "t"} { - elog ERROR \\ - "duplicate key ''$NEW(key1)'', ''$NEW(key2)'' for T_pkey1" - } - } - - if {$check_old_ref} { - # - # Check for references to OLD - # - set n [spi_execp -count 1 $GD(plan_dta1) [list $OLD(key1) $OLD(key2)]] - if {$n > 0} { - elog ERROR \\ - "key ''$OLD(key1)'', ''$OLD(key2)'' referenced by T_dta1" - } - } - - # - # Anything is fine - let operation pass through - # - return OK -' language pltcl; - - -create trigger pkey1_before before insert or update or delete on T_pkey1 - for each row execute procedure - trig_pkey1_before(); - - --- --- Trigger function to check for duplicate keys in T_pkey2 --- and to force key2 to be upper case only without leading whitespaces --- -create function trig_pkey2_before() returns trigger as E' - # - # Prepare plan on first call - # - if {![info exists GD]} { - set GD(plan_pkey2) [spi_prepare \\ - "select 1 from T_pkey2 \\ - where key1 = \\$1 and key2 = \\$2" \\ - {int4 bpchar}] - } - - # - # Convert key2 value - # - set NEW(key2) [string toupper [string trim $NEW(key2)]] - - # - # Check for duplicate key - # - set n [spi_execp -count 1 $GD(plan_pkey2) [list $NEW(key1) $NEW(key2)]] - if {$n > 0} { - elog ERROR \\ - "duplicate key ''$NEW(key1)'', ''$NEW(key2)'' for T_pkey2" - } - - # - # Return modified tuple in NEW - # - return [array get NEW] -' language pltcl; - - -create trigger pkey2_before before insert or update on T_pkey2 - for each row execute procedure - trig_pkey2_before(); - - --- --- Trigger function to force references from T_dta2 follow changes --- in T_pkey2 or be deleted too. This must be done AFTER the changes --- in T_pkey2 are done so the trigger for primkey check on T_dta2 --- fired on our updates will see the new key values in T_pkey2. --- -create function trig_pkey2_after() returns trigger as E' - # - # Prepare plans on first call - # - if {![info exists GD]} { - # - # Plan to update references from T_dta2 - # - set GD(plan_dta2_upd) [spi_prepare \\ - "update T_dta2 set ref1 = \\$3, ref2 = \\$4 \\ - where ref1 = \\$1 and ref2 = \\$2" \\ - {int4 bpchar int4 bpchar}] - # - # Plan to delete references from T_dta2 - # - set GD(plan_dta2_del) [spi_prepare \\ - "delete from T_dta2 \\ - where ref1 = \\$1 and ref2 = \\$2" \\ - {int4 bpchar}] - } - - # - # Initialize flags - # - set old_ref_follow 0 - set old_ref_delete 0 - - switch $TG_op { - UPDATE { - # - # On update we must let old references follow - # - set NEW(key2) [string toupper $NEW(key2)] - - if {[string compare $NEW(key1) $OLD(key1)] != 0} { - set old_ref_follow 1 - } - if {[string compare $NEW(key2) $OLD(key2)] != 0} { - set old_ref_follow 1 - } - } - DELETE { - # - # On delete we must delete references too - # - set old_ref_delete 1 - } - } - - if {$old_ref_follow} { - # - # Let old references follow and fire NOTICE message if - # there where some - # - set n [spi_execp $GD(plan_dta2_upd) \\ - [list $OLD(key1) $OLD(key2) $NEW(key1) $NEW(key2)]] - if {$n > 0} { - elog NOTICE \\ - "updated $n entries in T_dta2 for new key in T_pkey2" - } - } - - if {$old_ref_delete} { - # - # delete references and fire NOTICE message if - # there where some - # - set n [spi_execp $GD(plan_dta2_del) \\ - [list $OLD(key1) $OLD(key2)]] - if {$n > 0} { - elog NOTICE \\ - "deleted $n entries from T_dta2" - } - } - - return OK -' language pltcl; - - -create trigger pkey2_after after update or delete on T_pkey2 - for each row execute procedure - trig_pkey2_after(); - - --- --- Generic trigger function to check references in T_dta1 and T_dta2 --- -create function check_primkey() returns trigger as E' - # - # For every trigger/relation pair we create - # a saved plan and hold them in GD - # - set plankey [list "plan" $TG_name $TG_relid] - set planrel [list "relname" $TG_relid] - - # - # Extract the pkey relation name - # - set keyidx [expr [llength $args] / 2] - set keyrel [string tolower [lindex $args $keyidx]] - - if {![info exists GD($plankey)]} { - # - # We must prepare a new plan. Build up a query string - # for the primary key check. - # - set keylist [lrange $args [expr $keyidx + 1] end] - - set query "select 1 from $keyrel" - set qual " where" - set typlist "" - set idx 1 - foreach key $keylist { - set key [string tolower $key] - # - # Add the qual part to the query string - # - append query "$qual $key = \\$$idx" - set qual " and" - - # - # Lookup the fields type in pg_attribute - # - set n [spi_exec "select T.typname \\ - from pg_catalog.pg_type T, pg_catalog.pg_attribute A, pg_catalog.pg_class C \\ - where C.relname = ''[quote $keyrel]'' \\ - and C.oid = A.attrelid \\ - and A.attname = ''[quote $key]'' \\ - and A.atttypid = T.oid"] - if {$n != 1} { - elog ERROR "table $keyrel doesn''t have a field named $key" - } - - # - # Append the fields type to the argument type list - # - lappend typlist $typname - incr idx - } - - # - # Prepare the plan - # - set GD($plankey) [spi_prepare $query $typlist] - - # - # Lookup and remember the table name for later error messages - # - spi_exec "select relname from pg_catalog.pg_class \\ - where oid = ''$TG_relid''::oid" - set GD($planrel) $relname - } - - # - # Build the argument list from the NEW row - # - incr keyidx -1 - set arglist "" - foreach arg [lrange $args 0 $keyidx] { - lappend arglist $NEW($arg) - } - - # - # Check for the primary key - # - set n [spi_execp -count 1 $GD($plankey) $arglist] - if {$n <= 0} { - elog ERROR "key for $GD($planrel) not in $keyrel" - } - - # - # Anything is fine - # - return OK -' language pltcl; - - -create trigger dta1_before before insert or update on T_dta1 - for each row execute procedure - check_primkey('ref1', 'ref2', 'T_pkey1', 'key1', 'key2'); - - -create trigger dta2_before before insert or update on T_dta2 - for each row execute procedure - check_primkey('ref1', 'ref2', 'T_pkey2', 'key1', 'key2'); - - -insert into T_pkey1 values (1, 'key1-1', 'test key'); -insert into T_pkey1 values (1, 'key1-2', 'test key'); -insert into T_pkey1 values (1, 'key1-3', 'test key'); -insert into T_pkey1 values (2, 'key2-1', 'test key'); -insert into T_pkey1 values (2, 'key2-2', 'test key'); -insert into T_pkey1 values (2, 'key2-3', 'test key'); - -insert into T_pkey2 values (1, 'key1-1', 'test key'); -insert into T_pkey2 values (1, 'key1-2', 'test key'); -insert into T_pkey2 values (1, 'key1-3', 'test key'); -insert into T_pkey2 values (2, 'key2-1', 'test key'); -insert into T_pkey2 values (2, 'key2-2', 'test key'); -insert into T_pkey2 values (2, 'key2-3', 'test key'); - -select * from T_pkey1; - --- key2 in T_pkey2 should have upper case only -select * from T_pkey2; - -insert into T_pkey1 values (1, 'KEY1-3', 'should work'); - --- Due to the upper case translation in trigger this must fail -insert into T_pkey2 values (1, 'KEY1-3', 'should fail'); - -insert into T_dta1 values ('trec 1', 1, 'key1-1'); -insert into T_dta1 values ('trec 2', 1, 'key1-2'); -insert into T_dta1 values ('trec 3', 1, 'key1-3'); - --- Must fail due to unknown key in T_pkey1 -insert into T_dta1 values ('trec 4', 1, 'key1-4'); - -insert into T_dta2 values ('trec 1', 1, 'KEY1-1'); -insert into T_dta2 values ('trec 2', 1, 'KEY1-2'); -insert into T_dta2 values ('trec 3', 1, 'KEY1-3'); - --- Must fail due to unknown key in T_pkey2 -insert into T_dta2 values ('trec 4', 1, 'KEY1-4'); - -select * from T_dta1; - -select * from T_dta2; - -update T_pkey1 set key2 = 'key2-9' where key1 = 2 and key2 = 'key2-1'; -update T_pkey1 set key2 = 'key1-9' where key1 = 1 and key2 = 'key1-1'; -delete from T_pkey1 where key1 = 2 and key2 = 'key2-2'; -delete from T_pkey1 where key1 = 1 and key2 = 'key1-2'; - -update T_pkey2 set key2 = 'KEY2-9' where key1 = 2 and key2 = 'KEY2-1'; -update T_pkey2 set key2 = 'KEY1-9' where key1 = 1 and key2 = 'KEY1-1'; -delete from T_pkey2 where key1 = 2 and key2 = 'KEY2-2'; -delete from T_pkey2 where key1 = 1 and key2 = 'KEY1-2'; - -select * from T_pkey1; -select * from T_pkey2; -select * from T_dta1; -select * from T_dta2; - -select tcl_avg(key1) from T_pkey1; -select tcl_sum(key1) from T_pkey1; -select tcl_avg(key1) from T_pkey2; -select tcl_sum(key1) from T_pkey2; - --- The following should return NULL instead of 0 -select tcl_avg(key1) from T_pkey1 where key1 = 99; -select tcl_sum(key1) from T_pkey1 where key1 = 99; - -select 1 @< 2; -select 100 @< 4; - -select * from T_pkey1 order by key1 using @<, key2 collate "C"; -select * from T_pkey2 order by key1 using @<, key2 collate "C"; - --- show dump of trigger data -insert into trigger_test values(1,'insert'); - -insert into trigger_test_generated (i) values (1); -update trigger_test_generated set i = 11 where i = 1; -delete from trigger_test_generated; - -insert into trigger_test_view values(2,'insert'); -update trigger_test_view set v = 'update' where i=1; -delete from trigger_test_view; - -update trigger_test set v = 'update', test_skip=true where i = 1; -update trigger_test set v = 'update' where i = 1; -delete from trigger_test; -truncate trigger_test; - -DROP TRIGGER show_trigger_data_trig_before ON trigger_test_generated; -DROP TRIGGER show_trigger_data_trig_after ON trigger_test_generated; - --- should error -insert into trigger_test(test_argisnull) values(true); - --- should error -insert into trigger_test(test_return_null) values(true); - --- test transition table visibility -create table transition_table_test (id int, name text); -insert into transition_table_test values (1, 'a'); -create function transition_table_test_f() returns trigger language pltcl as -$$ - spi_exec -array C "SELECT id, name FROM old_table" { - elog INFO "old: $C(id) -> $C(name)" - } - spi_exec -array C "SELECT id, name FROM new_table" { - elog INFO "new: $C(id) -> $C(name)" - } - return OK -$$; -CREATE TRIGGER a_t AFTER UPDATE ON transition_table_test - REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table - FOR EACH STATEMENT EXECUTE PROCEDURE transition_table_test_f(); -update transition_table_test set name = 'b'; -drop table transition_table_test; -drop function transition_table_test_f(); - --- dealing with generated columns - -CREATE FUNCTION generated_test_func1() RETURNS trigger -LANGUAGE pltcl -AS $$ -# not allowed -set NEW(j) 5 -return [array get NEW] -$$; - -CREATE TRIGGER generated_test_trigger1 BEFORE INSERT ON trigger_test_generated -FOR EACH ROW EXECUTE PROCEDURE generated_test_func1(); - -TRUNCATE trigger_test_generated; -INSERT INTO trigger_test_generated (i) VALUES (1); -SELECT * FROM trigger_test_generated; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_unicode.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_unicode.sql deleted file mode 100644 index f000604612..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Fpl%2Ftcl%2Fsql%2Fpltcl_unicode.sql +++ /dev/null @@ -1,38 +0,0 @@ --- --- Unicode handling --- --- Note: this test case is known to fail if the database encoding is --- EUC_CN, EUC_JP, EUC_KR, or EUC_TW, for lack of any equivalent to --- U+00A0 (no-break space) in those encodings. However, testing with --- plain ASCII data would be rather useless, so we must live with that. --- - -SET client_encoding TO UTF8; - -CREATE TABLE unicode_test ( - testvalue text NOT NULL -); - -CREATE FUNCTION unicode_return() RETURNS text AS $$ - return "\xA0" -$$ LANGUAGE pltcl; - -CREATE FUNCTION unicode_trigger() RETURNS trigger AS $$ - set NEW(testvalue) "\xA0" - return [array get NEW] -$$ LANGUAGE pltcl; - -CREATE TRIGGER unicode_test_bi BEFORE INSERT ON unicode_test - FOR EACH ROW EXECUTE PROCEDURE unicode_trigger(); - -CREATE FUNCTION unicode_plan1() RETURNS text AS $$ - set plan [ spi_prepare {SELECT $1 AS testvalue} [ list "text" ] ] - spi_execp $plan [ list "\xA0" ] - return $testvalue -$$ LANGUAGE pltcl; - - -SELECT unicode_return(); -INSERT INTO unicode_test (testvalue) VALUES ('test'); -SELECT * FROM unicode_test; -SELECT unicode_plan1(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fdummy_seclabel%2Fsql%2Fdummy_seclabel.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fdummy_seclabel%2Fsql%2Fdummy_seclabel.sql deleted file mode 100644 index 8c347b6a68..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fdummy_seclabel%2Fsql%2Fdummy_seclabel.sql +++ /dev/null @@ -1,115 +0,0 @@ --- --- Test for facilities of security label --- -CREATE EXTENSION dummy_seclabel; - --- initial setups -SET client_min_messages TO 'warning'; - -DROP ROLE IF EXISTS regress_dummy_seclabel_user1; -DROP ROLE IF EXISTS regress_dummy_seclabel_user2; - -RESET client_min_messages; - -CREATE USER regress_dummy_seclabel_user1 WITH CREATEROLE; -CREATE USER regress_dummy_seclabel_user2; - -CREATE TABLE dummy_seclabel_tbl1 (a int, b text); -CREATE TABLE dummy_seclabel_tbl2 (x int, y text); -CREATE VIEW dummy_seclabel_view1 AS SELECT * FROM dummy_seclabel_tbl2; -CREATE FUNCTION dummy_seclabel_four() RETURNS integer AS $$SELECT 4$$ language sql; -CREATE DOMAIN dummy_seclabel_domain AS text; - -ALTER TABLE dummy_seclabel_tbl1 OWNER TO regress_dummy_seclabel_user1; -ALTER TABLE dummy_seclabel_tbl2 OWNER TO regress_dummy_seclabel_user2; - --- --- Test of SECURITY LABEL statement with a plugin --- -SET SESSION AUTHORIZATION regress_dummy_seclabel_user1; - -SECURITY LABEL ON TABLE dummy_seclabel_tbl1 IS 'classified'; -- OK -SECURITY LABEL ON COLUMN dummy_seclabel_tbl1.a IS 'unclassified'; -- OK -SECURITY LABEL ON COLUMN dummy_seclabel_tbl1 IS 'unclassified'; -- fail -SECURITY LABEL ON TABLE dummy_seclabel_tbl1 IS '...invalid label...'; -- fail -SECURITY LABEL FOR 'dummy' ON TABLE dummy_seclabel_tbl1 IS 'unclassified'; -- OK -SECURITY LABEL FOR 'unknown_seclabel' ON TABLE dummy_seclabel_tbl1 IS 'classified'; -- fail -SECURITY LABEL ON TABLE dummy_seclabel_tbl2 IS 'unclassified'; -- fail (not owner) -SECURITY LABEL ON TABLE dummy_seclabel_tbl1 IS 'secret'; -- fail (not superuser) -SECURITY LABEL ON TABLE dummy_seclabel_tbl3 IS 'unclassified'; -- fail (not found) - -SET SESSION AUTHORIZATION regress_dummy_seclabel_user2; -SECURITY LABEL ON TABLE dummy_seclabel_tbl1 IS 'unclassified'; -- fail -SECURITY LABEL ON TABLE dummy_seclabel_tbl2 IS 'classified'; -- OK - --- --- Test for shared database object --- -SET SESSION AUTHORIZATION regress_dummy_seclabel_user1; - -SECURITY LABEL ON ROLE regress_dummy_seclabel_user1 IS 'classified'; -- OK -SECURITY LABEL ON ROLE regress_dummy_seclabel_user1 IS '...invalid label...'; -- fail -SECURITY LABEL FOR 'dummy' ON ROLE regress_dummy_seclabel_user2 IS 'unclassified'; -- OK -SECURITY LABEL FOR 'unknown_seclabel' ON ROLE regress_dummy_seclabel_user1 IS 'unclassified'; -- fail -SECURITY LABEL ON ROLE regress_dummy_seclabel_user1 IS 'secret'; -- fail (not superuser) -SECURITY LABEL ON ROLE regress_dummy_seclabel_user3 IS 'unclassified'; -- fail (not found) - -SET SESSION AUTHORIZATION regress_dummy_seclabel_user2; -SECURITY LABEL ON ROLE regress_dummy_seclabel_user2 IS 'unclassified'; -- fail (not privileged) - -RESET SESSION AUTHORIZATION; - --- --- Test for various types of object --- -RESET SESSION AUTHORIZATION; - -SECURITY LABEL ON TABLE dummy_seclabel_tbl1 IS 'top secret'; -- OK -SECURITY LABEL ON VIEW dummy_seclabel_view1 IS 'classified'; -- OK -SECURITY LABEL ON FUNCTION dummy_seclabel_four() IS 'classified'; -- OK -SECURITY LABEL ON DOMAIN dummy_seclabel_domain IS 'classified'; -- OK -CREATE SCHEMA dummy_seclabel_test; -SECURITY LABEL ON SCHEMA dummy_seclabel_test IS 'unclassified'; -- OK - -SET client_min_messages = error; -CREATE PUBLICATION dummy_pub; -CREATE SUBSCRIPTION dummy_sub CONNECTION '' PUBLICATION foo WITH (connect = false, slot_name = NONE); -RESET client_min_messages; -SECURITY LABEL ON PUBLICATION dummy_pub IS 'classified'; -SECURITY LABEL ON SUBSCRIPTION dummy_sub IS 'classified'; - -SELECT objtype, objname, provider, label FROM pg_seclabels - ORDER BY objtype, objname; - --- check for event trigger -CREATE FUNCTION event_trigger_test() -RETURNS event_trigger AS $$ - BEGIN RAISE NOTICE 'event %: %', TG_EVENT, TG_TAG; END; -$$ LANGUAGE plpgsql; - -CREATE EVENT TRIGGER always_start ON ddl_command_start -EXECUTE PROCEDURE event_trigger_test(); - -CREATE EVENT TRIGGER always_end ON ddl_command_end -EXECUTE PROCEDURE event_trigger_test(); - -CREATE EVENT TRIGGER always_drop ON sql_drop -EXECUTE PROCEDURE event_trigger_test(); - -CREATE EVENT TRIGGER always_rewrite ON table_rewrite -EXECUTE PROCEDURE event_trigger_test(); - --- should trigger ddl_command_{start,end} -SECURITY LABEL ON TABLE dummy_seclabel_tbl1 IS 'classified'; - --- clean up -DROP EVENT TRIGGER always_start, always_end, always_drop, always_rewrite; - -DROP VIEW dummy_seclabel_view1; -DROP TABLE dummy_seclabel_tbl1, dummy_seclabel_tbl2; - -DROP SUBSCRIPTION dummy_sub; -DROP PUBLICATION dummy_pub; - -DROP ROLE regress_dummy_seclabel_user1; -DROP ROLE regress_dummy_seclabel_user2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fplsample%2Fsql%2Fplsample.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fplsample%2Fsql%2Fplsample.sql deleted file mode 100644 index cf652ad56f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fplsample%2Fsql%2Fplsample.sql +++ /dev/null @@ -1,38 +0,0 @@ -CREATE EXTENSION plsample; --- Create and test some dummy functions -CREATE FUNCTION plsample_result_text(a1 numeric, a2 text, a3 integer[]) -RETURNS TEXT -AS $$ - Example of source with text result. -$$ LANGUAGE plsample; -SELECT plsample_result_text(1.23, 'abc', '{4, 5, 6}'); - -CREATE FUNCTION plsample_result_void(a1 text[]) -RETURNS VOID -AS $$ - Example of source with void result. -$$ LANGUAGE plsample; -SELECT plsample_result_void('{foo, bar, hoge}'); - -CREATE FUNCTION my_trigger_func() RETURNS trigger AS $$ -if TD_event == "INSERT" - return TD_NEW -elseif TD_event == "UPDATE" - return TD_NEW -else - return "OK" -end -$$ language plsample; - -CREATE TABLE my_table (num integer, description text); -CREATE TRIGGER my_trigger_func BEFORE INSERT OR UPDATE ON my_table - FOR EACH ROW EXECUTE FUNCTION my_trigger_func(); -CREATE TRIGGER my_trigger_func2 AFTER INSERT OR UPDATE ON my_table - FOR EACH ROW EXECUTE FUNCTION my_trigger_func(8); - -INSERT INTO my_table (num, description) -VALUES (1, 'first'); - -UPDATE my_table -SET description = 'first, modified once' -WHERE num = 1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_ddl_deparse%2Fsql%2Fcreate_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_ddl_deparse%2Fsql%2Fcreate_trigger.sql deleted file mode 100644 index fc0aef7593..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_ddl_deparse%2Fsql%2Fcreate_trigger.sql +++ /dev/null @@ -1,18 +0,0 @@ ---- ---- CREATE_TRIGGER ---- - -CREATE FUNCTION plpgsql_function_trigger_1() - RETURNS TRIGGER - LANGUAGE plpgsql -AS $$ -BEGIN - RETURN NEW; -END; -$$; - -CREATE TRIGGER trigger_1 - BEFORE INSERT OR UPDATE - ON datatype_table - FOR EACH ROW - EXECUTE PROCEDURE plpgsql_function_trigger_1(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_ddl_deparse%2Fsql%2Ftest_ddl_deparse.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_ddl_deparse%2Fsql%2Ftest_ddl_deparse.sql deleted file mode 100644 index e257a215e4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_ddl_deparse%2Fsql%2Ftest_ddl_deparse.sql +++ /dev/null @@ -1,42 +0,0 @@ -CREATE EXTENSION test_ddl_deparse; - -CREATE OR REPLACE FUNCTION test_ddl_deparse() - RETURNS event_trigger LANGUAGE plpgsql AS -$$ -DECLARE - r record; - r2 record; - cmdtype text; - objtype text; - tag text; -BEGIN - FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() - LOOP - -- verify that tags match - tag = public.get_command_tag(r.command); - IF tag <> r.command_tag THEN - RAISE NOTICE 'tag % doesn''t match %', tag, r.command_tag; - END IF; - - -- log the operation - cmdtype = public.get_command_type(r.command); - IF cmdtype <> 'grant' THEN - RAISE NOTICE 'DDL test: type %, tag %', cmdtype, tag; - ELSE - RAISE NOTICE 'DDL test: type %, object type %', cmdtype, r.object_type; - END IF; - - -- if alter table, log more - IF cmdtype = 'alter table' THEN - FOR r2 IN SELECT * - FROM unnest(public.get_altertable_subcmdtypes(r.command)) - LOOP - RAISE NOTICE ' subcommand: %', r2.unnest; - END LOOP; - END IF; - END LOOP; -END; -$$; - -CREATE EVENT TRIGGER test_ddl_deparse -ON ddl_command_end EXECUTE PROCEDURE test_ddl_deparse(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Fsql%2Ftest_extdepend.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Fsql%2Ftest_extdepend.sql deleted file mode 100644 index 63240a1af5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Fsql%2Ftest_extdepend.sql +++ /dev/null @@ -1,90 +0,0 @@ --- --- test ALTER THING name DEPENDS ON EXTENSION --- - --- Common setup for all tests -CREATE TABLE test_extdep_commands (command text); -COPY test_extdep_commands FROM stdin; - CREATE SCHEMA test_ext - CREATE EXTENSION test_ext5 SCHEMA test_ext - SET search_path TO test_ext - CREATE TABLE a (a1 int) - - CREATE FUNCTION b() RETURNS TRIGGER LANGUAGE plpgsql AS\n $$ BEGIN NEW.a1 := NEW.a1 + 42; RETURN NEW; END; $$ - ALTER FUNCTION b() DEPENDS ON EXTENSION test_ext5 - - CREATE TRIGGER c BEFORE INSERT ON a FOR EACH ROW EXECUTE PROCEDURE b() - ALTER TRIGGER c ON a DEPENDS ON EXTENSION test_ext5 - - CREATE MATERIALIZED VIEW d AS SELECT * FROM a - ALTER MATERIALIZED VIEW d DEPENDS ON EXTENSION test_ext5 - - CREATE INDEX e ON a (a1) - ALTER INDEX e DEPENDS ON EXTENSION test_ext5 - RESET search_path -\. - -SELECT * FROM test_extdep_commands; --- First, test that dependent objects go away when the extension is dropped. -SELECT * FROM test_extdep_commands \gexec --- A dependent object made dependent again has no effect -ALTER FUNCTION test_ext.b() DEPENDS ON EXTENSION test_ext5; --- make sure we have the right dependencies on the extension -SELECT deptype, p.* - FROM pg_depend, pg_identify_object(classid, objid, objsubid) AS p - WHERE refclassid = 'pg_extension'::regclass AND - refobjid = (SELECT oid FROM pg_extension WHERE extname = 'test_ext5') -ORDER BY type; -DROP EXTENSION test_ext5; --- anything still depending on the table? -SELECT deptype, i.* - FROM pg_catalog.pg_depend, pg_identify_object(classid, objid, objsubid) i -WHERE refclassid='pg_class'::regclass AND - refobjid='test_ext.a'::regclass AND NOT deptype IN ('i', 'a'); -DROP SCHEMA test_ext CASCADE; - --- Second test: If we drop the table, the objects are dropped too and no --- vestige remains in pg_depend. -SELECT * FROM test_extdep_commands \gexec -DROP TABLE test_ext.a; -- should fail, require cascade -DROP TABLE test_ext.a CASCADE; --- anything still depending on the extension? Should be only function b() -SELECT deptype, i.* - FROM pg_catalog.pg_depend, pg_identify_object(classid, objid, objsubid) i - WHERE refclassid='pg_extension'::regclass AND - refobjid=(SELECT oid FROM pg_extension WHERE extname='test_ext5'); -DROP EXTENSION test_ext5; -DROP SCHEMA test_ext CASCADE; - --- Third test: we can drop the objects individually -SELECT * FROM test_extdep_commands \gexec -SET search_path TO test_ext; -DROP TRIGGER c ON a; -DROP FUNCTION b(); -DROP MATERIALIZED VIEW d; -DROP INDEX e; - -SELECT deptype, i.* - FROM pg_catalog.pg_depend, pg_identify_object(classid, objid, objsubid) i - WHERE (refclassid='pg_extension'::regclass AND - refobjid=(SELECT oid FROM pg_extension WHERE extname='test_ext5')) - OR (refclassid='pg_class'::regclass AND refobjid='test_ext.a'::regclass) - AND NOT deptype IN ('i', 'a'); -DROP TABLE a; -RESET search_path; -DROP SCHEMA test_ext CASCADE; - --- Fourth test: we can mark the objects as dependent, then unmark; then the --- drop of the extension does nothing -SELECT * FROM test_extdep_commands \gexec -SET search_path TO test_ext; -ALTER FUNCTION b() NO DEPENDS ON EXTENSION test_ext5; -ALTER TRIGGER c ON a NO DEPENDS ON EXTENSION test_ext5; -ALTER MATERIALIZED VIEW d NO DEPENDS ON EXTENSION test_ext5; -ALTER INDEX e NO DEPENDS ON EXTENSION test_ext5; -DROP EXTENSION test_ext5; -DROP TRIGGER c ON a; -DROP FUNCTION b(); -DROP MATERIALIZED VIEW d; -DROP INDEX e; -DROP SCHEMA test_ext CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Fsql%2Ftest_extensions.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Fsql%2Ftest_extensions.sql deleted file mode 100644 index c16fd36da8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Fsql%2Ftest_extensions.sql +++ /dev/null @@ -1,101 +0,0 @@ --- test some errors -CREATE EXTENSION test_ext1; -CREATE EXTENSION test_ext1 SCHEMA test_ext1; -CREATE EXTENSION test_ext1 SCHEMA test_ext; -CREATE SCHEMA test_ext; -CREATE EXTENSION test_ext1 SCHEMA test_ext; - --- finally success -CREATE EXTENSION test_ext1 SCHEMA test_ext CASCADE; - -SELECT extname, nspname, extversion, extrelocatable FROM pg_extension e, pg_namespace n WHERE extname LIKE 'test_ext%' AND e.extnamespace = n.oid ORDER BY 1; - -CREATE EXTENSION test_ext_cyclic1 CASCADE; - -DROP SCHEMA test_ext CASCADE; - -CREATE EXTENSION test_ext6; -DROP EXTENSION test_ext6; -CREATE EXTENSION test_ext6; - --- test dropping of member tables that own extensions: --- this table will be absorbed into test_ext7 -create table old_table1 (col1 serial primary key); -create extension test_ext7; -\dx+ test_ext7 -alter extension test_ext7 update to '2.0'; -\dx+ test_ext7 - --- test handling of temp objects created by extensions -create extension test_ext8; - --- \dx+ would expose a variable pg_temp_nn schema name, so we can't use it here -select regexp_replace(pg_describe_object(classid, objid, objsubid), - 'pg_temp_\d+', 'pg_temp', 'g') as "Object description" -from pg_depend -where refclassid = 'pg_extension'::regclass and deptype = 'e' and - refobjid = (select oid from pg_extension where extname = 'test_ext8') -order by 1; - --- Should be possible to drop and recreate this extension -drop extension test_ext8; -create extension test_ext8; - -select regexp_replace(pg_describe_object(classid, objid, objsubid), - 'pg_temp_\d+', 'pg_temp', 'g') as "Object description" -from pg_depend -where refclassid = 'pg_extension'::regclass and deptype = 'e' and - refobjid = (select oid from pg_extension where extname = 'test_ext8') -order by 1; - --- here we want to start a new session and wait till old one is gone -select pg_backend_pid() as oldpid \gset -\c - -do 'declare c int = 0; -begin - while (select count(*) from pg_stat_activity where pid = ' - :'oldpid' - ') > 0 loop c := c + 1; perform pg_stat_clear_snapshot(); end loop; - raise log ''test_extensions looped % times'', c; -end'; - --- extension should now contain no temp objects -\dx+ test_ext8 - --- dropping it should still work -drop extension test_ext8; - --- Test creation of extension in temporary schema with two-phase commit, --- which should not work. This function wrapper is useful for portability. - --- Avoid noise caused by CONTEXT and NOTICE messages including the temporary --- schema name. -\set SHOW_CONTEXT never -SET client_min_messages TO 'warning'; --- First enforce presence of temporary schema. -CREATE TEMP TABLE test_ext4_tab (); -CREATE OR REPLACE FUNCTION create_extension_with_temp_schema() - RETURNS VOID AS $$ - DECLARE - tmpschema text; - query text; - BEGIN - SELECT INTO tmpschema pg_my_temp_schema()::regnamespace; - query := 'CREATE EXTENSION test_ext4 SCHEMA ' || tmpschema || ' CASCADE;'; - RAISE NOTICE 'query %', query; - EXECUTE query; - END; $$ LANGUAGE plpgsql; -BEGIN; -SELECT create_extension_with_temp_schema(); -PREPARE TRANSACTION 'twophase_extension'; --- Clean up -DROP TABLE test_ext4_tab; -DROP FUNCTION create_extension_with_temp_schema(); -RESET client_min_messages; -\unset SHOW_CONTEXT - --- Test case of an event trigger run in an extension upgrade script. --- See: https://postgr.es/m/20200902193715.6e0269d4@firost -CREATE EXTENSION test_ext_evttrig; -ALTER EXTENSION test_ext_evttrig UPDATE TO '2.0'; -DROP EXTENSION test_ext_evttrig; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Ftest_ext_evttrig--1.0.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Ftest_ext_evttrig--1.0.sql deleted file mode 100644 index 0071712cb8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_extensions%2Ftest_ext_evttrig--1.0.sql +++ /dev/null @@ -1,16 +0,0 @@ -/* src/test/modules/test_extensions/test_event_trigger--1.0.sql */ --- complain if script is sourced in psql, rather than via CREATE EXTENSION -\echo Use "CREATE EXTENSION test_event_trigger" to load this file. \quit - --- Base table with event trigger, used in a regression test involving --- extension upgrades. -CREATE TABLE t (id text); -CREATE OR REPLACE FUNCTION _evt_table_rewrite_fnct() -RETURNS EVENT_TRIGGER LANGUAGE plpgsql AS -$$ - BEGIN - END; -$$; -CREATE EVENT TRIGGER table_rewrite_trg - ON table_rewrite - EXECUTE PROCEDURE _evt_table_rewrite_fnct(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_oat_hooks%2Fsql%2Ftest_oat_hooks.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_oat_hooks%2Fsql%2Ftest_oat_hooks.sql deleted file mode 100644 index 8b6d5373aa..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_oat_hooks%2Fsql%2Ftest_oat_hooks.sql +++ /dev/null @@ -1,100 +0,0 @@ --- Creating privileges on a placeholder GUC should create entries in the --- pg_parameter_acl catalog which conservatively grant no privileges to public. -CREATE ROLE regress_role_joe; -GRANT SET ON PARAMETER test_oat_hooks.user_var1 TO regress_role_joe; -GRANT SET ON PARAMETER test_oat_hooks.super_var1 TO regress_role_joe; - --- SET commands fire both the ProcessUtility_hook and the --- object_access_hook_str. Since the auditing GUC starts out false, we miss the --- initial "attempting" audit message from the ProcessUtility_hook, but we --- should thereafter see the audit messages. -LOAD 'test_oat_hooks'; -SET test_oat_hooks.audit = true; - --- Creating privileges on an existent custom GUC should create precisely the --- right privileges, not overly conservative ones. -GRANT SET ON PARAMETER test_oat_hooks.user_var2 TO regress_role_joe; -GRANT SET ON PARAMETER test_oat_hooks.super_var2 TO regress_role_joe; - --- Granting multiple privileges on a parameter should be reported correctly to --- the OAT hook, but beware that WITH GRANT OPTION is not represented. -GRANT SET, ALTER SYSTEM ON PARAMETER none.such TO regress_role_joe; -GRANT SET, ALTER SYSTEM ON PARAMETER another.bogus TO regress_role_joe WITH GRANT OPTION; - --- Check when the hooks fire relative to dependency based abort of a drop -DROP ROLE regress_role_joe; - --- Check the behavior of the hooks relative to do-nothing grants and revokes -GRANT SET ON PARAMETER work_mem TO PUBLIC; -REVOKE ALTER SYSTEM ON PARAMETER work_mem FROM PUBLIC; - --- Check the behavior of the hooks relative to unrecognized parameters -GRANT ALL ON PARAMETER "none.such" TO PUBLIC; - --- Check relative to an operation that causes the catalog entry to be deleted -REVOKE ALL ON PARAMETER "none.such" FROM PUBLIC; - --- Create objects for use in the test -CREATE USER regress_test_user; -CREATE TABLE regress_test_table (t text); -GRANT SELECT ON Table regress_test_table TO public; -CREATE FUNCTION regress_test_func (t text) RETURNS text AS $$ - SELECT $1; -$$ LANGUAGE sql; -GRANT EXECUTE ON FUNCTION regress_test_func (text) TO public; - --- Do a few things as superuser -SELECT * FROM regress_test_table; -SELECT regress_test_func('arg'); -SET work_mem = 8192; -RESET work_mem; -ALTER SYSTEM SET work_mem = 8192; -ALTER SYSTEM RESET work_mem; - --- Do those same things as non-superuser -SET SESSION AUTHORIZATION regress_test_user; -SELECT * FROM regress_test_table; -SELECT regress_test_func('arg'); -SET work_mem = 8192; -RESET work_mem; -ALTER SYSTEM SET work_mem = 8192; -ALTER SYSTEM RESET work_mem; - -SET test_oat_hooks.user_var1 = true; -SET test_oat_hooks.super_var1 = true; -ALTER SYSTEM SET test_oat_hooks.user_var1 = true; -ALTER SYSTEM SET test_oat_hooks.super_var1 = true; -SET test_oat_hooks.user_var2 = true; -SET test_oat_hooks.super_var2 = true; -ALTER SYSTEM SET test_oat_hooks.user_var2 = true; -ALTER SYSTEM SET test_oat_hooks.super_var2 = true; - -RESET SESSION AUTHORIZATION; - --- Turn off non-superuser permissions -SET test_oat_hooks.deny_set_variable = true; -SET test_oat_hooks.deny_alter_system = true; -SET test_oat_hooks.deny_object_access = true; -SET test_oat_hooks.deny_exec_perms = true; -SET test_oat_hooks.deny_utility_commands = true; - --- Try again as non-superuser with permissions denied -SET SESSION AUTHORIZATION regress_test_user; -SELECT * FROM regress_test_table; -SELECT regress_test_func('arg'); -SET work_mem = 8192; -RESET work_mem; -ALTER SYSTEM SET work_mem = 8192; -ALTER SYSTEM RESET work_mem; - --- Clean up -RESET SESSION AUTHORIZATION; - -SET test_oat_hooks.audit = false; -DROP ROLE regress_role_joe; -- fails -REVOKE ALL PRIVILEGES ON PARAMETER - none.such, another.bogus, - test_oat_hooks.user_var1, test_oat_hooks.super_var1, - test_oat_hooks.user_var2, test_oat_hooks.super_var2 - FROM regress_role_joe; -DROP ROLE regress_role_joe; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_pg_dump%2Fsql%2Ftest_pg_dump.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_pg_dump%2Fsql%2Ftest_pg_dump.sql deleted file mode 100644 index a61a7c8c4c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_pg_dump%2Fsql%2Ftest_pg_dump.sql +++ /dev/null @@ -1,108 +0,0 @@ -CREATE ROLE regress_dump_test_role; -CREATE EXTENSION test_pg_dump; - -ALTER EXTENSION test_pg_dump ADD DATABASE postgres; -- error - -CREATE TABLE test_pg_dump_t1 (c1 int, junk text); -ALTER TABLE test_pg_dump_t1 DROP COLUMN junk; -- to exercise dropped-col cases -CREATE VIEW test_pg_dump_v1 AS SELECT * FROM test_pg_dump_t1; -CREATE MATERIALIZED VIEW test_pg_dump_mv1 AS SELECT * FROM test_pg_dump_t1; -CREATE SCHEMA test_pg_dump_s1; -CREATE TYPE test_pg_dump_e1 AS ENUM ('abc', 'def'); - -CREATE AGGREGATE newavg ( - sfunc = int4_avg_accum, basetype = int4, stype = _int8, - finalfunc = int8_avg, - initcond1 = '{0,0}' -); - -CREATE FUNCTION test_pg_dump(int) RETURNS int AS $$ -BEGIN -RETURN abs($1); -END -$$ LANGUAGE plpgsql IMMUTABLE; - -CREATE OPERATOR ==== ( - LEFTARG = int, - RIGHTARG = int, - PROCEDURE = int4eq, - COMMUTATOR = ==== -); - -CREATE ACCESS METHOD gist2 TYPE INDEX HANDLER gisthandler; - -CREATE TYPE casttesttype; - -CREATE FUNCTION casttesttype_in(cstring) - RETURNS casttesttype - AS 'textin' - LANGUAGE internal STRICT IMMUTABLE; -CREATE FUNCTION casttesttype_out(casttesttype) - RETURNS cstring - AS 'textout' - LANGUAGE internal STRICT IMMUTABLE; - -CREATE TYPE casttesttype ( - internallength = variable, - input = casttesttype_in, - output = casttesttype_out, - alignment = int4 -); - -CREATE CAST (text AS casttesttype) WITHOUT FUNCTION; - -CREATE FOREIGN DATA WRAPPER dummy; - -CREATE SERVER s0 FOREIGN DATA WRAPPER dummy; - -CREATE FOREIGN TABLE ft1 ( - c1 integer OPTIONS ("param 1" 'val1') NOT NULL, - c2 text OPTIONS (param2 'val2', param3 'val3') CHECK (c2 <> ''), - c3 date, - CHECK (c3 BETWEEN '1994-01-01'::date AND '1994-01-31'::date) -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); - -REVOKE EXECUTE ON FUNCTION test_pg_dump(int) FROM PUBLIC; -GRANT EXECUTE ON FUNCTION test_pg_dump(int) TO regress_dump_test_role; - -GRANT SELECT (c1) ON test_pg_dump_t1 TO regress_dump_test_role; -GRANT SELECT ON test_pg_dump_v1 TO regress_dump_test_role; -GRANT USAGE ON FOREIGN DATA WRAPPER dummy TO regress_dump_test_role; -GRANT USAGE ON FOREIGN SERVER s0 TO regress_dump_test_role; -GRANT SELECT (c1) ON ft1 TO regress_dump_test_role; -GRANT SELECT ON ft1 TO regress_dump_test_role; -GRANT UPDATE ON test_pg_dump_mv1 TO regress_dump_test_role; -GRANT USAGE ON SCHEMA test_pg_dump_s1 TO regress_dump_test_role; -GRANT USAGE ON TYPE test_pg_dump_e1 TO regress_dump_test_role; - -ALTER EXTENSION test_pg_dump ADD ACCESS METHOD gist2; -ALTER EXTENSION test_pg_dump ADD AGGREGATE newavg(int4); -ALTER EXTENSION test_pg_dump ADD CAST (text AS casttesttype); -ALTER EXTENSION test_pg_dump ADD FOREIGN DATA WRAPPER dummy; -ALTER EXTENSION test_pg_dump ADD FOREIGN TABLE ft1; -ALTER EXTENSION test_pg_dump ADD MATERIALIZED VIEW test_pg_dump_mv1; -ALTER EXTENSION test_pg_dump ADD OPERATOR ==== (int, int); -ALTER EXTENSION test_pg_dump ADD SCHEMA test_pg_dump_s1; -ALTER EXTENSION test_pg_dump ADD SERVER s0; -ALTER EXTENSION test_pg_dump ADD FUNCTION test_pg_dump(int); -ALTER EXTENSION test_pg_dump ADD TABLE test_pg_dump_t1; -ALTER EXTENSION test_pg_dump ADD TYPE test_pg_dump_e1; -ALTER EXTENSION test_pg_dump ADD VIEW test_pg_dump_v1; - -REVOKE SELECT (c1) ON test_pg_dump_t1 FROM regress_dump_test_role; -REVOKE SELECT ON test_pg_dump_v1 FROM regress_dump_test_role; -REVOKE USAGE ON FOREIGN DATA WRAPPER dummy FROM regress_dump_test_role; - -ALTER EXTENSION test_pg_dump DROP ACCESS METHOD gist2; -ALTER EXTENSION test_pg_dump DROP AGGREGATE newavg(int4); -ALTER EXTENSION test_pg_dump DROP CAST (text AS casttesttype); -ALTER EXTENSION test_pg_dump DROP FOREIGN DATA WRAPPER dummy; -ALTER EXTENSION test_pg_dump DROP FOREIGN TABLE ft1; -ALTER EXTENSION test_pg_dump DROP FUNCTION test_pg_dump(int); -ALTER EXTENSION test_pg_dump DROP MATERIALIZED VIEW test_pg_dump_mv1; -ALTER EXTENSION test_pg_dump DROP OPERATOR ==== (int, int); -ALTER EXTENSION test_pg_dump DROP SCHEMA test_pg_dump_s1; -ALTER EXTENSION test_pg_dump DROP SERVER s0; -ALTER EXTENSION test_pg_dump DROP TABLE test_pg_dump_t1; -ALTER EXTENSION test_pg_dump DROP TYPE test_pg_dump_e1; -ALTER EXTENSION test_pg_dump DROP VIEW test_pg_dump_v1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_predtest%2Fsql%2Ftest_predtest.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_predtest%2Fsql%2Ftest_predtest.sql deleted file mode 100644 index 072eb5b0d5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Ftest_predtest%2Fsql%2Ftest_predtest.sql +++ /dev/null @@ -1,442 +0,0 @@ -CREATE EXTENSION test_predtest; - --- Make output more legible -\pset expanded on - --- Test data - --- all combinations of four boolean values -create table booleans as -select - case i%3 when 0 then true when 1 then false else null end as x, - case (i/3)%3 when 0 then true when 1 then false else null end as y, - case (i/9)%3 when 0 then true when 1 then false else null end as z, - case (i/27)%3 when 0 then true when 1 then false else null end as w -from generate_series(0, 3*3*3*3-1) i; - --- all combinations of two integers 0..9, plus null -create table integers as -select - case i%11 when 10 then null else i%11 end as x, - case (i/11)%11 when 10 then null else (i/11)%11 end as y -from generate_series(0, 11*11-1) i; - --- and a simple strict function that's opaque to the optimizer -create function strictf(bool, bool) returns bool -language plpgsql as $$begin return $1 and not $2; end$$ strict; - --- a simple function to make arrays opaque to the optimizer -create function opaque_array(int[]) returns int[] -language plpgsql as $$begin return $1; end$$ strict; - --- Basic proof rules for single boolean variables - -select * from test_predtest($$ -select x, x -from booleans -$$); - -select * from test_predtest($$ -select x, not x -from booleans -$$); - -select * from test_predtest($$ -select not x, x -from booleans -$$); - -select * from test_predtest($$ -select not x, not x -from booleans -$$); - -select * from test_predtest($$ -select x is not null, x -from booleans -$$); - -select * from test_predtest($$ -select x is not null, x is null -from integers -$$); - -select * from test_predtest($$ -select x is null, x is not null -from integers -$$); - -select * from test_predtest($$ -select x is not true, x -from booleans -$$); - -select * from test_predtest($$ -select x, x is not true -from booleans -$$); - -select * from test_predtest($$ -select x is false, x -from booleans -$$); - -select * from test_predtest($$ -select x, x is false -from booleans -$$); - -select * from test_predtest($$ -select x is unknown, x -from booleans -$$); - -select * from test_predtest($$ -select x, x is unknown -from booleans -$$); - --- Assorted not-so-trivial refutation rules - -select * from test_predtest($$ -select x is null, x -from booleans -$$); - -select * from test_predtest($$ -select x, x is null -from booleans -$$); - -select * from test_predtest($$ -select strictf(x,y), x is null -from booleans -$$); - -select * from test_predtest($$ -select (x is not null) is not true, x -from booleans -$$); - -select * from test_predtest($$ -select strictf(x,y), (x is not null) is false -from booleans -$$); - -select * from test_predtest($$ -select x > y, (y < x) is false -from integers -$$); - --- Tests involving AND/OR constructs - -select * from test_predtest($$ -select x, x and y -from booleans -$$); - -select * from test_predtest($$ -select not x, x and y -from booleans -$$); - -select * from test_predtest($$ -select x, not x and y -from booleans -$$); - -select * from test_predtest($$ -select x or y, x -from booleans -$$); - -select * from test_predtest($$ -select x and y, x -from booleans -$$); - -select * from test_predtest($$ -select x and y, not x -from booleans -$$); - -select * from test_predtest($$ -select x and y, y and x -from booleans -$$); - -select * from test_predtest($$ -select not y, y and x -from booleans -$$); - -select * from test_predtest($$ -select x or y, y or x -from booleans -$$); - -select * from test_predtest($$ -select x or y or z, x or z -from booleans -$$); - -select * from test_predtest($$ -select x and z, x and y and z -from booleans -$$); - -select * from test_predtest($$ -select z or w, x or y -from booleans -$$); - -select * from test_predtest($$ -select z and w, x or y -from booleans -$$); - -select * from test_predtest($$ -select x, (x and y) or (x and z) -from booleans -$$); - -select * from test_predtest($$ -select (x and y) or z, y and x -from booleans -$$); - -select * from test_predtest($$ -select (not x or not y) and z, y and x -from booleans -$$); - -select * from test_predtest($$ -select y or x, (x or y) and z -from booleans -$$); - -select * from test_predtest($$ -select not x and not y, (x or y) and z -from booleans -$$); - --- Tests using btree operator knowledge - -select * from test_predtest($$ -select x <= y, x < y -from integers -$$); - -select * from test_predtest($$ -select x <= y, x > y -from integers -$$); - -select * from test_predtest($$ -select x <= y, y >= x -from integers -$$); - -select * from test_predtest($$ -select x <= y, y > x and y < x+2 -from integers -$$); - -select * from test_predtest($$ -select x <= 5, x <= 7 -from integers -$$); - -select * from test_predtest($$ -select x <= 5, x > 7 -from integers -$$); - -select * from test_predtest($$ -select x <= 5, 7 > x -from integers -$$); - -select * from test_predtest($$ -select 5 >= x, 7 > x -from integers -$$); - -select * from test_predtest($$ -select 5 >= x, x > 7 -from integers -$$); - -select * from test_predtest($$ -select 5 = x, x = 7 -from integers -$$); - -select * from test_predtest($$ -select x is not null, x > 7 -from integers -$$); - -select * from test_predtest($$ -select x is not null, int4lt(x,8) -from integers -$$); - -select * from test_predtest($$ -select x is null, x > 7 -from integers -$$); - -select * from test_predtest($$ -select x is null, int4lt(x,8) -from integers -$$); - -select * from test_predtest($$ -select x is not null, x < 'foo' -from (values - ('aaa'::varchar), ('zzz'::varchar), (null)) as v(x) -$$); - --- Cases using ScalarArrayOpExpr - -select * from test_predtest($$ -select x <= 5, x in (1,3,5) -from integers -$$); - -select * from test_predtest($$ -select x <= 5, x in (1,3,5,7) -from integers -$$); - -select * from test_predtest($$ -select x <= 5, x in (1,3,5,null) -from integers -$$); - -select * from test_predtest($$ -select x in (null,1,3,5,7), x in (1,3,5) -from integers -$$); - -select * from test_predtest($$ -select x <= 5, x < all(array[1,3,5]) -from integers -$$); - -select * from test_predtest($$ -select x <= y, x = any(array[1,3,y]) -from integers -$$); - --- In these tests, we want to prevent predtest.c from breaking down the --- ScalarArrayOpExpr into an AND/OR tree, so as to exercise the logic --- that handles ScalarArrayOpExpr directly. We use opaque_array() if --- possible, otherwise an array longer than MAX_SAOP_ARRAY_SIZE. - --- ScalarArrayOpExpr implies scalar IS NOT NULL -select * from test_predtest($$ -select x is not null, x = any(opaque_array(array[1])) -from integers -$$); - --- but for ALL, we have to be able to prove the array nonempty -select * from test_predtest($$ -select x is not null, x <> all(opaque_array(array[1])) -from integers -$$); - -select * from test_predtest($$ -select x is not null, x <> all(array[ - 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28, - 29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53, - 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78, - 79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101 -]) -from integers -$$); - -select * from test_predtest($$ -select x is not null, x <> all(array[ - 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28, - 29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53, - 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78, - 79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,y -]) -from integers -$$); - --- check empty-array cases -select * from test_predtest($$ -select x is not null, x = any(opaque_array(array[]::int[])) -from integers -$$); - -select * from test_predtest($$ -select x is not null, x <> all(opaque_array(array[]::int[])) -from integers -$$); - --- same thing under a strict function doesn't prove it -select * from test_predtest($$ -select x is not null, strictf(true, x = any(opaque_array(array[]::int[]))) -from integers -$$); - --- ScalarArrayOpExpr refutes scalar IS NULL -select * from test_predtest($$ -select x is null, x = any(opaque_array(array[1])) -from integers -$$); - --- but for ALL, we have to be able to prove the array nonempty -select * from test_predtest($$ -select x is null, x <> all(opaque_array(array[1])) -from integers -$$); - -select * from test_predtest($$ -select x is null, x <> all(array[ - 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28, - 29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53, - 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78, - 79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101 -]) -from integers -$$); - --- check empty-array cases -select * from test_predtest($$ -select x is null, x = any(opaque_array(array[]::int[])) -from integers -$$); - -select * from test_predtest($$ -select x is null, x <> all(opaque_array(array[]::int[])) -from integers -$$); - --- same thing under a strict function doesn't prove it -select * from test_predtest($$ -select x is null, strictf(true, x = any(opaque_array(array[]::int[]))) -from integers -$$); - --- Also, nullness of the scalar weakly refutes a SAOP -select * from test_predtest($$ -select x = any(opaque_array(array[1])), x is null -from integers -$$); - --- as does nullness of the array -select * from test_predtest($$ -select x = any(opaque_array(array[y])), array[y] is null -from integers -$$); - --- ... unless we need to prove array empty -select * from test_predtest($$ -select x = all(opaque_array(array[1])), x is null -from integers -$$); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Funsafe_tests%2Fsql%2Falter_system_table.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Funsafe_tests%2Fsql%2Falter_system_table.sql deleted file mode 100644 index b77b68c946..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Funsafe_tests%2Fsql%2Falter_system_table.sql +++ /dev/null @@ -1,194 +0,0 @@ --- --- Tests for things affected by allow_system_table_mods --- --- We run the same set of commands once with allow_system_table_mods --- off and then again with on. --- --- The "on" tests should where possible be wrapped in BEGIN/ROLLBACK --- blocks so as to not leave a mess around. - -CREATE USER regress_user_ast; - -SET allow_system_table_mods = off; - --- create new table in pg_catalog -CREATE TABLE pg_catalog.test (a int); - --- anyarray column -CREATE TABLE t1x (a int, b anyarray); - --- index on system catalog -ALTER TABLE pg_namespace ADD CONSTRAINT foo UNIQUE USING INDEX pg_namespace_nspname_index; - --- write to system catalog table as superuser --- (allowed even without allow_system_table_mods) -INSERT INTO pg_description (objoid, classoid, objsubid, description) VALUES (0, 0, 0, 'foo'); - --- write to system catalog table as normal user -GRANT INSERT ON pg_description TO regress_user_ast; -SET ROLE regress_user_ast; -INSERT INTO pg_description (objoid, classoid, objsubid, description) VALUES (0, 0, 1, 'foo'); -RESET ROLE; - --- policy on system catalog -CREATE POLICY foo ON pg_description FOR SELECT USING (description NOT LIKE 'secret%'); - --- reserved schema name -CREATE SCHEMA pg_foo; - --- drop system table -DROP TABLE pg_description; - --- truncate of system table -TRUNCATE pg_description; - --- rename column of system table -ALTER TABLE pg_description RENAME COLUMN description TO comment; - --- ATSimplePermissions() -ALTER TABLE pg_description ALTER COLUMN description SET NOT NULL; - --- SET STATISTICS -ALTER TABLE pg_description ALTER COLUMN description SET STATISTICS -1; - --- foreign key referencing catalog -CREATE TABLE foo (a oid, b oid, c int, FOREIGN KEY (a, b, c) REFERENCES pg_description); - --- RangeVarCallbackOwnsRelation() -CREATE INDEX pg_description_test_index ON pg_description (description); - --- RangeVarCallbackForAlterRelation() -ALTER TABLE pg_description RENAME TO pg_comment; -ALTER TABLE pg_description SET SCHEMA public; - --- reserved tablespace name -CREATE TABLESPACE pg_foo LOCATION '/no/such/location'; - --- triggers -CREATE FUNCTION tf1() RETURNS trigger -LANGUAGE plpgsql -AS $$ -BEGIN - RETURN NULL; -END $$; - -CREATE TRIGGER t1 BEFORE INSERT ON pg_description EXECUTE FUNCTION tf1(); -ALTER TRIGGER t1 ON pg_description RENAME TO t2; ---DROP TRIGGER t2 ON pg_description; - --- rules -CREATE RULE r1 AS ON INSERT TO pg_description DO INSTEAD NOTHING; -ALTER RULE r1 ON pg_description RENAME TO r2; --- now make one to test dropping: -SET allow_system_table_mods TO on; -CREATE RULE r2 AS ON INSERT TO pg_description DO INSTEAD NOTHING; -RESET allow_system_table_mods; -DROP RULE r2 ON pg_description; --- cleanup: -SET allow_system_table_mods TO on; -DROP RULE r2 ON pg_description; -RESET allow_system_table_mods; - - -SET allow_system_table_mods = on; - --- create new table in pg_catalog -BEGIN; -CREATE TABLE pg_catalog.test (a int); -ROLLBACK; - --- anyarray column -BEGIN; -CREATE TABLE t1 (a int, b anyarray); -ROLLBACK; - --- index on system catalog -BEGIN; -ALTER TABLE pg_namespace ADD CONSTRAINT foo UNIQUE USING INDEX pg_namespace_nspname_index; -ROLLBACK; - --- write to system catalog table as superuser -BEGIN; -INSERT INTO pg_description (objoid, classoid, objsubid, description) VALUES (0, 0, 2, 'foo'); -ROLLBACK; - --- write to system catalog table as normal user --- (not allowed) -SET ROLE regress_user_ast; -INSERT INTO pg_description (objoid, classoid, objsubid, description) VALUES (0, 0, 3, 'foo'); -RESET ROLE; - --- policy on system catalog -BEGIN; -CREATE POLICY foo ON pg_description FOR SELECT USING (description NOT LIKE 'secret%'); -ROLLBACK; - --- reserved schema name -BEGIN; -CREATE SCHEMA pg_foo; -ROLLBACK; - --- drop system table --- (This will fail anyway because it's pinned.) -BEGIN; -DROP TABLE pg_description; -ROLLBACK; - --- truncate of system table -BEGIN; -TRUNCATE pg_description; -ROLLBACK; - --- rename column of system table -BEGIN; -ALTER TABLE pg_description RENAME COLUMN description TO comment; -ROLLBACK; - --- ATSimplePermissions() -BEGIN; -ALTER TABLE pg_description ALTER COLUMN description SET NOT NULL; -ROLLBACK; - --- SET STATISTICS -BEGIN; -ALTER TABLE pg_description ALTER COLUMN description SET STATISTICS -1; -ROLLBACK; - --- foreign key referencing catalog -BEGIN; -CREATE TABLE foo (a oid, b oid, c int, FOREIGN KEY (a, b, c) REFERENCES pg_description); -ROLLBACK; - --- RangeVarCallbackOwnsRelation() -BEGIN; -CREATE INDEX pg_description_test_index ON pg_description (description); -ROLLBACK; - --- RangeVarCallbackForAlterRelation() -BEGIN; -ALTER TABLE pg_description RENAME TO pg_comment; -ROLLBACK; -BEGIN; -ALTER TABLE pg_description SET SCHEMA public; -ROLLBACK; - --- reserved tablespace name -SET client_min_messages = error; -- disable ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS warning -CREATE TABLESPACE pg_foo LOCATION '/no/such/location'; -RESET client_min_messages; - --- triggers -CREATE TRIGGER t1 BEFORE INSERT ON pg_description EXECUTE FUNCTION tf1(); -ALTER TRIGGER t1 ON pg_description RENAME TO t2; -DROP TRIGGER t2 ON pg_description; - --- rules -CREATE RULE r1 AS ON INSERT TO pg_description DO INSTEAD NOTHING; -ALTER RULE r1 ON pg_description RENAME TO r2; -DROP RULE r2 ON pg_description; - - --- cleanup -REVOKE ALL ON pg_description FROM regress_user_ast; -DROP USER regress_user_ast; -DROP FUNCTION tf1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Funsafe_tests%2Fsql%2Frolenames.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Funsafe_tests%2Fsql%2Frolenames.sql deleted file mode 100644 index adac36536d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Funsafe_tests%2Fsql%2Frolenames.sql +++ /dev/null @@ -1,504 +0,0 @@ -CREATE FUNCTION chkrolattr() - RETURNS TABLE ("role" name, rolekeyword text, canlogin bool, replication bool) - AS $$ -SELECT r.rolname, v.keyword, r.rolcanlogin, r.rolreplication - FROM pg_roles r - JOIN (VALUES(CURRENT_ROLE, 'current_role'), - (CURRENT_USER, 'current_user'), - (SESSION_USER, 'session_user'), - ('current_role', '-'), - ('current_user', '-'), - ('session_user', '-'), - ('Public', '-'), - ('None', '-')) - AS v(uname, keyword) - ON (r.rolname = v.uname) - ORDER BY 1, 2; -$$ LANGUAGE SQL; - -CREATE FUNCTION chksetconfig() - RETURNS TABLE (db name, "role" name, rolkeyword text, setconfig text[]) - AS $$ -SELECT COALESCE(d.datname, 'ALL'), COALESCE(r.rolname, 'ALL'), - COALESCE(v.keyword, '-'), s.setconfig - FROM pg_db_role_setting s - LEFT JOIN pg_roles r ON (r.oid = s.setrole) - LEFT JOIN pg_database d ON (d.oid = s.setdatabase) - LEFT JOIN (VALUES(CURRENT_ROLE, 'current_role'), - (CURRENT_USER, 'current_user'), - (SESSION_USER, 'session_user')) - AS v(uname, keyword) - ON (r.rolname = v.uname) - WHERE (r.rolname) IN ('Public', 'current_user', 'regress_testrol1', 'regress_testrol2') -ORDER BY 1, 2, 3; -$$ LANGUAGE SQL; - -CREATE FUNCTION chkumapping() - RETURNS TABLE (umname name, umserver name, umoptions text[]) - AS $$ -SELECT r.rolname, s.srvname, m.umoptions - FROM pg_user_mapping m - LEFT JOIN pg_roles r ON (r.oid = m.umuser) - JOIN pg_foreign_server s ON (s.oid = m.umserver) - ORDER BY 2, 1; -$$ LANGUAGE SQL; - --- --- We test creation and use of these role names to ensure that the server --- correctly distinguishes role keywords from quoted names that look like --- those keywords. In a test environment, creation of these roles may --- provoke warnings, so hide the warnings by raising client_min_messages. --- -SET client_min_messages = ERROR; - -CREATE ROLE "Public"; -CREATE ROLE "None"; -CREATE ROLE "current_role"; -CREATE ROLE "current_user"; -CREATE ROLE "session_user"; -CREATE ROLE "user"; - -RESET client_min_messages; - -CREATE ROLE current_user; -- error -CREATE ROLE current_role; -- error -CREATE ROLE session_user; -- error -CREATE ROLE user; -- error -CREATE ROLE all; -- error - -CREATE ROLE public; -- error -CREATE ROLE "public"; -- error -CREATE ROLE none; -- error -CREATE ROLE "none"; -- error - -CREATE ROLE pg_abc; -- error -CREATE ROLE "pg_abc"; -- error -CREATE ROLE pg_abcdef; -- error -CREATE ROLE "pg_abcdef"; -- error - -CREATE ROLE regress_testrol0 SUPERUSER LOGIN; -CREATE ROLE regress_testrolx SUPERUSER LOGIN; -CREATE ROLE regress_testrol2 SUPERUSER; -CREATE ROLE regress_testrol1 SUPERUSER LOGIN IN ROLE regress_testrol2; - -\c - -SET SESSION AUTHORIZATION regress_testrol1; -SET ROLE regress_testrol2; - --- ALTER ROLE -BEGIN; -SELECT * FROM chkrolattr(); -ALTER ROLE CURRENT_ROLE WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER ROLE "current_role" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER ROLE CURRENT_ROLE WITH NOREPLICATION; -ALTER ROLE CURRENT_USER WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER ROLE "current_user" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER ROLE SESSION_USER WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER ROLE "session_user" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER "Public" WITH REPLICATION; -ALTER USER "None" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER regress_testrol1 WITH NOREPLICATION; -ALTER USER regress_testrol2 WITH NOREPLICATION; -SELECT * FROM chkrolattr(); -ROLLBACK; - -ALTER ROLE USER WITH LOGIN; -- error -ALTER ROLE ALL WITH REPLICATION; -- error -ALTER ROLE SESSION_ROLE WITH NOREPLICATION; -- error -ALTER ROLE PUBLIC WITH NOREPLICATION; -- error -ALTER ROLE "public" WITH NOREPLICATION; -- error -ALTER ROLE NONE WITH NOREPLICATION; -- error -ALTER ROLE "none" WITH NOREPLICATION; -- error -ALTER ROLE nonexistent WITH NOREPLICATION; -- error - --- ALTER USER -BEGIN; -SELECT * FROM chkrolattr(); -ALTER USER CURRENT_ROLE WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER "current_role" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER CURRENT_ROLE WITH NOREPLICATION; -ALTER USER CURRENT_USER WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER "current_user" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER SESSION_USER WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER "session_user" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER "Public" WITH REPLICATION; -ALTER USER "None" WITH REPLICATION; -SELECT * FROM chkrolattr(); -ALTER USER regress_testrol1 WITH NOREPLICATION; -ALTER USER regress_testrol2 WITH NOREPLICATION; -SELECT * FROM chkrolattr(); -ROLLBACK; - -ALTER USER USER WITH LOGIN; -- error -ALTER USER ALL WITH REPLICATION; -- error -ALTER USER SESSION_ROLE WITH NOREPLICATION; -- error -ALTER USER PUBLIC WITH NOREPLICATION; -- error -ALTER USER "public" WITH NOREPLICATION; -- error -ALTER USER NONE WITH NOREPLICATION; -- error -ALTER USER "none" WITH NOREPLICATION; -- error -ALTER USER nonexistent WITH NOREPLICATION; -- error - --- ALTER ROLE SET/RESET -SELECT * FROM chksetconfig(); -ALTER ROLE CURRENT_ROLE SET application_name to 'BAZ'; -ALTER ROLE CURRENT_USER SET application_name to 'FOO'; -ALTER ROLE SESSION_USER SET application_name to 'BAR'; -ALTER ROLE "current_user" SET application_name to 'FOOFOO'; -ALTER ROLE "Public" SET application_name to 'BARBAR'; -ALTER ROLE ALL SET application_name to 'SLAP'; -SELECT * FROM chksetconfig(); -ALTER ROLE regress_testrol1 SET application_name to 'SLAM'; -SELECT * FROM chksetconfig(); -ALTER ROLE CURRENT_ROLE RESET application_name; -ALTER ROLE CURRENT_USER RESET application_name; -ALTER ROLE SESSION_USER RESET application_name; -ALTER ROLE "current_user" RESET application_name; -ALTER ROLE "Public" RESET application_name; -ALTER ROLE ALL RESET application_name; -SELECT * FROM chksetconfig(); - - -ALTER ROLE USER SET application_name to 'BOOM'; -- error -ALTER ROLE PUBLIC SET application_name to 'BOMB'; -- error -ALTER ROLE nonexistent SET application_name to 'BOMB'; -- error - --- ALTER USER SET/RESET -SELECT * FROM chksetconfig(); -ALTER USER CURRENT_ROLE SET application_name to 'BAZ'; -ALTER USER CURRENT_USER SET application_name to 'FOO'; -ALTER USER SESSION_USER SET application_name to 'BAR'; -ALTER USER "current_user" SET application_name to 'FOOFOO'; -ALTER USER "Public" SET application_name to 'BARBAR'; -ALTER USER ALL SET application_name to 'SLAP'; -SELECT * FROM chksetconfig(); -ALTER USER regress_testrol1 SET application_name to 'SLAM'; -SELECT * FROM chksetconfig(); -ALTER USER CURRENT_ROLE RESET application_name; -ALTER USER CURRENT_USER RESET application_name; -ALTER USER SESSION_USER RESET application_name; -ALTER USER "current_user" RESET application_name; -ALTER USER "Public" RESET application_name; -ALTER USER ALL RESET application_name; -SELECT * FROM chksetconfig(); - - -ALTER USER USER SET application_name to 'BOOM'; -- error -ALTER USER PUBLIC SET application_name to 'BOMB'; -- error -ALTER USER NONE SET application_name to 'BOMB'; -- error -ALTER USER nonexistent SET application_name to 'BOMB'; -- error - --- CREATE SCHEMA -CREATE SCHEMA newschema1 AUTHORIZATION CURRENT_USER; -CREATE SCHEMA newschema2 AUTHORIZATION "current_user"; -CREATE SCHEMA newschema3 AUTHORIZATION CURRENT_ROLE; -CREATE SCHEMA newschema4 AUTHORIZATION SESSION_USER; -CREATE SCHEMA newschema5 AUTHORIZATION regress_testrolx; -CREATE SCHEMA newschema6 AUTHORIZATION "Public"; - -CREATE SCHEMA newschemax AUTHORIZATION USER; -- error -CREATE SCHEMA newschemax AUTHORIZATION PUBLIC; -- error -CREATE SCHEMA newschemax AUTHORIZATION "public"; -- error -CREATE SCHEMA newschemax AUTHORIZATION NONE; -- error -CREATE SCHEMA newschemax AUTHORIZATION nonexistent; -- error - -SELECT n.nspname, r.rolname FROM pg_namespace n - JOIN pg_roles r ON (r.oid = n.nspowner) - WHERE n.nspname LIKE 'newschema_' ORDER BY 1; - -CREATE SCHEMA IF NOT EXISTS newschema1 AUTHORIZATION CURRENT_USER; -CREATE SCHEMA IF NOT EXISTS newschema2 AUTHORIZATION "current_user"; -CREATE SCHEMA IF NOT EXISTS newschema3 AUTHORIZATION CURRENT_ROLE; -CREATE SCHEMA IF NOT EXISTS newschema4 AUTHORIZATION SESSION_USER; -CREATE SCHEMA IF NOT EXISTS newschema5 AUTHORIZATION regress_testrolx; -CREATE SCHEMA IF NOT EXISTS newschema6 AUTHORIZATION "Public"; - -CREATE SCHEMA IF NOT EXISTS newschemax AUTHORIZATION USER; -- error -CREATE SCHEMA IF NOT EXISTS newschemax AUTHORIZATION PUBLIC; -- error -CREATE SCHEMA IF NOT EXISTS newschemax AUTHORIZATION "public"; -- error -CREATE SCHEMA IF NOT EXISTS newschemax AUTHORIZATION NONE; -- error -CREATE SCHEMA IF NOT EXISTS newschemax AUTHORIZATION nonexistent; -- error - -SELECT n.nspname, r.rolname FROM pg_namespace n - JOIN pg_roles r ON (r.oid = n.nspowner) - WHERE n.nspname LIKE 'newschema_' ORDER BY 1; - --- ALTER TABLE OWNER TO -\c - -SET SESSION AUTHORIZATION regress_testrol0; -CREATE TABLE testtab1 (a int); -CREATE TABLE testtab2 (a int); -CREATE TABLE testtab3 (a int); -CREATE TABLE testtab4 (a int); -CREATE TABLE testtab5 (a int); -CREATE TABLE testtab6 (a int); -CREATE TABLE testtab7 (a int); - -\c - -SET SESSION AUTHORIZATION regress_testrol1; -SET ROLE regress_testrol2; - -ALTER TABLE testtab1 OWNER TO CURRENT_USER; -ALTER TABLE testtab2 OWNER TO "current_user"; -ALTER TABLE testtab3 OWNER TO CURRENT_ROLE; -ALTER TABLE testtab4 OWNER TO SESSION_USER; -ALTER TABLE testtab5 OWNER TO regress_testrolx; -ALTER TABLE testtab6 OWNER TO "Public"; - -ALTER TABLE testtab7 OWNER TO USER; --error -ALTER TABLE testtab7 OWNER TO PUBLIC; -- error -ALTER TABLE testtab7 OWNER TO "public"; -- error -ALTER TABLE testtab7 OWNER TO nonexistent; -- error - -SELECT c.relname, r.rolname - FROM pg_class c JOIN pg_roles r ON (r.oid = c.relowner) - WHERE relname LIKE 'testtab_' - ORDER BY 1; - --- ALTER TABLE, VIEW, MATERIALIZED VIEW, FOREIGN TABLE, SEQUENCE are --- changed their owner in the same way. - --- ALTER AGGREGATE -\c - -SET SESSION AUTHORIZATION regress_testrol0; -CREATE AGGREGATE testagg1(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg2(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg3(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg4(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg5(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg6(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg7(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg8(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagg9(int2) (SFUNC = int2_sum, STYPE = int8); -CREATE AGGREGATE testagga(int2) (SFUNC = int2_sum, STYPE = int8); - -\c - -SET SESSION AUTHORIZATION regress_testrol1; -SET ROLE regress_testrol2; - -ALTER AGGREGATE testagg1(int2) OWNER TO CURRENT_USER; -ALTER AGGREGATE testagg2(int2) OWNER TO "current_user"; -ALTER AGGREGATE testagg3(int2) OWNER TO CURRENT_ROLE; -ALTER AGGREGATE testagg4(int2) OWNER TO SESSION_USER; -ALTER AGGREGATE testagg5(int2) OWNER TO regress_testrolx; -ALTER AGGREGATE testagg6(int2) OWNER TO "Public"; - -ALTER AGGREGATE testagg6(int2) OWNER TO USER; -- error -ALTER AGGREGATE testagg6(int2) OWNER TO PUBLIC; -- error -ALTER AGGREGATE testagg6(int2) OWNER TO "public"; -- error -ALTER AGGREGATE testagg6(int2) OWNER TO nonexistent; -- error - -SELECT p.proname, r.rolname - FROM pg_proc p JOIN pg_roles r ON (r.oid = p.proowner) - WHERE proname LIKE 'testagg_' - ORDER BY 1; - --- CREATE USER MAPPING -CREATE FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv1 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv2 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv3 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv4 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv5 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv6 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv7 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv8 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv9 FOREIGN DATA WRAPPER test_wrapper; -CREATE SERVER sv10 FOREIGN DATA WRAPPER test_wrapper; - -CREATE USER MAPPING FOR CURRENT_USER SERVER sv1 OPTIONS (user 'CURRENT_USER'); -CREATE USER MAPPING FOR "current_user" SERVER sv2 OPTIONS (user '"current_user"'); -CREATE USER MAPPING FOR CURRENT_ROLE SERVER sv3 OPTIONS (user 'CURRENT_ROLE'); -CREATE USER MAPPING FOR USER SERVER sv4 OPTIONS (user 'USER'); -CREATE USER MAPPING FOR "user" SERVER sv5 OPTIONS (user '"USER"'); -CREATE USER MAPPING FOR SESSION_USER SERVER sv6 OPTIONS (user 'SESSION_USER'); -CREATE USER MAPPING FOR PUBLIC SERVER sv7 OPTIONS (user 'PUBLIC'); -CREATE USER MAPPING FOR "Public" SERVER sv8 OPTIONS (user '"Public"'); -CREATE USER MAPPING FOR regress_testrolx SERVER sv9 OPTIONS (user 'regress_testrolx'); - -CREATE USER MAPPING FOR nonexistent SERVER sv10 OPTIONS (user 'nonexistent'); -- error; - -SELECT * FROM chkumapping(); - --- ALTER USER MAPPING -ALTER USER MAPPING FOR CURRENT_USER SERVER sv1 - OPTIONS (SET user 'CURRENT_USER_alt'); -ALTER USER MAPPING FOR "current_user" SERVER sv2 - OPTIONS (SET user '"current_user"_alt'); -ALTER USER MAPPING FOR CURRENT_ROLE SERVER sv3 - OPTIONS (SET user 'CURRENT_ROLE_alt'); -ALTER USER MAPPING FOR USER SERVER sv4 - OPTIONS (SET user 'USER_alt'); -ALTER USER MAPPING FOR "user" SERVER sv5 - OPTIONS (SET user '"user"_alt'); -ALTER USER MAPPING FOR SESSION_USER SERVER sv6 - OPTIONS (SET user 'SESSION_USER_alt'); -ALTER USER MAPPING FOR PUBLIC SERVER sv7 - OPTIONS (SET user 'public_alt'); -ALTER USER MAPPING FOR "Public" SERVER sv8 - OPTIONS (SET user '"Public"_alt'); -ALTER USER MAPPING FOR regress_testrolx SERVER sv9 - OPTIONS (SET user 'regress_testrolx_alt'); - -ALTER USER MAPPING FOR nonexistent SERVER sv10 - OPTIONS (SET user 'nonexistent_alt'); -- error - -SELECT * FROM chkumapping(); - --- DROP USER MAPPING -DROP USER MAPPING FOR CURRENT_USER SERVER sv1; -DROP USER MAPPING FOR "current_user" SERVER sv2; -DROP USER MAPPING FOR CURRENT_ROLE SERVER sv3; -DROP USER MAPPING FOR USER SERVER sv4; -DROP USER MAPPING FOR "user" SERVER sv5; -DROP USER MAPPING FOR SESSION_USER SERVER sv6; -DROP USER MAPPING FOR PUBLIC SERVER sv7; -DROP USER MAPPING FOR "Public" SERVER sv8; -DROP USER MAPPING FOR regress_testrolx SERVER sv9; - -DROP USER MAPPING FOR nonexistent SERVER sv10; -- error -SELECT * FROM chkumapping(); - -CREATE USER MAPPING FOR CURRENT_USER SERVER sv1 OPTIONS (user 'CURRENT_USER'); -CREATE USER MAPPING FOR "current_user" SERVER sv2 OPTIONS (user '"current_user"'); -CREATE USER MAPPING FOR CURRENT_ROLE SERVER sv3 OPTIONS (user 'CURRENT_ROLE'); -CREATE USER MAPPING FOR USER SERVER sv4 OPTIONS (user 'USER'); -CREATE USER MAPPING FOR "user" SERVER sv5 OPTIONS (user '"USER"'); -CREATE USER MAPPING FOR SESSION_USER SERVER sv6 OPTIONS (user 'SESSION_USER'); -CREATE USER MAPPING FOR PUBLIC SERVER sv7 OPTIONS (user 'PUBLIC'); -CREATE USER MAPPING FOR "Public" SERVER sv8 OPTIONS (user '"Public"'); -CREATE USER MAPPING FOR regress_testrolx SERVER sv9 OPTIONS (user 'regress_testrolx'); -SELECT * FROM chkumapping(); - --- DROP USER MAPPING IF EXISTS -DROP USER MAPPING IF EXISTS FOR CURRENT_USER SERVER sv1; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR "current_user" SERVER sv2; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR CURRENT_USER SERVER sv3; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR USER SERVER sv4; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR "user" SERVER sv5; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR SESSION_USER SERVER sv6; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR PUBLIC SERVER sv7; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR "Public" SERVER sv8; -SELECT * FROM chkumapping(); -DROP USER MAPPING IF EXISTS FOR regress_testrolx SERVER sv9; -SELECT * FROM chkumapping(); - -DROP USER MAPPING IF EXISTS FOR nonexistent SERVER sv10; -- error - --- GRANT/REVOKE -GRANT regress_testrol0 TO pg_signal_backend; -- success - -SET ROLE pg_signal_backend; --success -RESET ROLE; -CREATE SCHEMA test_roles_schema AUTHORIZATION pg_signal_backend; --success -SET ROLE regress_testrol2; - -UPDATE pg_proc SET proacl = null WHERE proname LIKE 'testagg_'; -SELECT proname, proacl FROM pg_proc WHERE proname LIKE 'testagg_'; - -REVOKE ALL PRIVILEGES ON FUNCTION testagg1(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg2(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg3(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg4(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg5(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg6(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg7(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg8(int2) FROM PUBLIC; - -GRANT ALL PRIVILEGES ON FUNCTION testagg1(int2) TO PUBLIC; -GRANT ALL PRIVILEGES ON FUNCTION testagg2(int2) TO CURRENT_USER; -GRANT ALL PRIVILEGES ON FUNCTION testagg3(int2) TO "current_user"; -GRANT ALL PRIVILEGES ON FUNCTION testagg4(int2) TO CURRENT_ROLE; -GRANT ALL PRIVILEGES ON FUNCTION testagg5(int2) TO SESSION_USER; -GRANT ALL PRIVILEGES ON FUNCTION testagg6(int2) TO "Public"; -GRANT ALL PRIVILEGES ON FUNCTION testagg7(int2) TO regress_testrolx; -GRANT ALL PRIVILEGES ON FUNCTION testagg8(int2) TO "public"; -GRANT ALL PRIVILEGES ON FUNCTION testagg9(int2) - TO current_user, public, regress_testrolx; - -SELECT proname, proacl FROM pg_proc WHERE proname LIKE 'testagg_'; - -GRANT ALL PRIVILEGES ON FUNCTION testagga(int2) TO USER; --error -GRANT ALL PRIVILEGES ON FUNCTION testagga(int2) TO NONE; --error -GRANT ALL PRIVILEGES ON FUNCTION testagga(int2) TO "none"; --error - -SELECT proname, proacl FROM pg_proc WHERE proname LIKE 'testagg_'; - -REVOKE ALL PRIVILEGES ON FUNCTION testagg1(int2) FROM PUBLIC; -REVOKE ALL PRIVILEGES ON FUNCTION testagg2(int2) FROM CURRENT_USER; -REVOKE ALL PRIVILEGES ON FUNCTION testagg3(int2) FROM "current_user"; -REVOKE ALL PRIVILEGES ON FUNCTION testagg4(int2) FROM CURRENT_ROLE; -REVOKE ALL PRIVILEGES ON FUNCTION testagg5(int2) FROM SESSION_USER; -REVOKE ALL PRIVILEGES ON FUNCTION testagg6(int2) FROM "Public"; -REVOKE ALL PRIVILEGES ON FUNCTION testagg7(int2) FROM regress_testrolx; -REVOKE ALL PRIVILEGES ON FUNCTION testagg8(int2) FROM "public"; -REVOKE ALL PRIVILEGES ON FUNCTION testagg9(int2) - FROM current_user, public, regress_testrolx; - -SELECT proname, proacl FROM pg_proc WHERE proname LIKE 'testagg_'; - -REVOKE ALL PRIVILEGES ON FUNCTION testagga(int2) FROM USER; --error -REVOKE ALL PRIVILEGES ON FUNCTION testagga(int2) FROM NONE; --error -REVOKE ALL PRIVILEGES ON FUNCTION testagga(int2) FROM "none"; --error - -SELECT proname, proacl FROM pg_proc WHERE proname LIKE 'testagg_'; - --- DEFAULT MONITORING ROLES -CREATE ROLE regress_role_haspriv; -CREATE ROLE regress_role_nopriv; - --- pg_read_all_stats -GRANT pg_read_all_stats TO regress_role_haspriv; -SET SESSION AUTHORIZATION regress_role_haspriv; --- returns true with role member of pg_read_all_stats -SELECT COUNT(*) = 0 AS haspriv FROM pg_stat_activity - WHERE query = ''; -SET SESSION AUTHORIZATION regress_role_nopriv; --- returns false with role not member of pg_read_all_stats -SELECT COUNT(*) = 0 AS haspriv FROM pg_stat_activity - WHERE query = ''; -RESET SESSION AUTHORIZATION; -REVOKE pg_read_all_stats FROM regress_role_haspriv; - --- pg_read_all_settings -GRANT pg_read_all_settings TO regress_role_haspriv; -BEGIN; --- A GUC using GUC_SUPERUSER_ONLY is useful for negative tests. -SET LOCAL session_preload_libraries TO 'path-to-preload-libraries'; -SET SESSION AUTHORIZATION regress_role_haspriv; --- passes with role member of pg_read_all_settings -SHOW session_preload_libraries; -SET SESSION AUTHORIZATION regress_role_nopriv; --- fails with role not member of pg_read_all_settings -SHOW session_preload_libraries; -RESET SESSION AUTHORIZATION; -ROLLBACK; -REVOKE pg_read_all_settings FROM regress_role_haspriv; - --- clean up -\c - -DROP SCHEMA test_roles_schema; -DROP OWNED BY regress_testrol0, "Public", "current_role", "current_user", regress_testrol1, regress_testrol2, regress_testrolx CASCADE; -DROP ROLE regress_testrol0, regress_testrol1, regress_testrol2, regress_testrolx; -DROP ROLE "Public", "None", "current_role", "current_user", "session_user", "user"; -DROP ROLE regress_role_haspriv, regress_role_nopriv; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fworker_spi%2Fsql%2Fworker_spi.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fworker_spi%2Fsql%2Fworker_spi.sql deleted file mode 100644 index 4683523b29..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fmodules%2Fworker_spi%2Fsql%2Fworker_spi.sql +++ /dev/null @@ -1,35 +0,0 @@ -CREATE EXTENSION worker_spi; -SELECT worker_spi_launch(4) IS NOT NULL; --- wait until the worker completes its initialization -DO $$ -DECLARE - visible bool; - loops int := 0; -BEGIN - LOOP - visible := table_name IS NOT NULL - FROM information_schema.tables - WHERE table_schema = 'schema4' AND table_name = 'counted'; - IF visible OR loops > 120 * 10 THEN EXIT; END IF; - PERFORM pg_sleep(0.1); - loops := loops + 1; - END LOOP; -END -$$; -INSERT INTO schema4.counted VALUES ('total', 0), ('delta', 1); -SELECT pg_reload_conf(); --- wait until the worker has processed the tuple we just inserted -DO $$ -DECLARE - count int; - loops int := 0; -BEGIN - LOOP - count := count(*) FROM schema4.counted WHERE type = 'delta'; - IF count = 0 OR loops > 120 * 10 THEN EXIT; END IF; - PERFORM pg_sleep(0.1); - loops := loops + 1; - END LOOP; -END -$$; -SELECT * FROM schema4.counted; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fadvisory_lock.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fadvisory_lock.sql deleted file mode 100644 index 57c47c0fac..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fadvisory_lock.sql +++ /dev/null @@ -1,146 +0,0 @@ --- --- ADVISORY LOCKS --- - -BEGIN; - -SELECT - pg_advisory_xact_lock(1), pg_advisory_xact_lock_shared(2), - pg_advisory_xact_lock(1, 1), pg_advisory_xact_lock_shared(2, 2); - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - - --- pg_advisory_unlock_all() shouldn't release xact locks -SELECT pg_advisory_unlock_all(); - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; - - --- can't unlock xact locks -SELECT - pg_advisory_unlock(1), pg_advisory_unlock_shared(2), - pg_advisory_unlock(1, 1), pg_advisory_unlock_shared(2, 2); - - --- automatically release xact locks at commit -COMMIT; - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; - - -BEGIN; - --- holding both session and xact locks on the same objects, xact first -SELECT - pg_advisory_xact_lock(1), pg_advisory_xact_lock_shared(2), - pg_advisory_xact_lock(1, 1), pg_advisory_xact_lock_shared(2, 2); - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - -SELECT - pg_advisory_lock(1), pg_advisory_lock_shared(2), - pg_advisory_lock(1, 1), pg_advisory_lock_shared(2, 2); - -ROLLBACK; - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - - --- unlocking session locks -SELECT - pg_advisory_unlock(1), pg_advisory_unlock(1), - pg_advisory_unlock_shared(2), pg_advisory_unlock_shared(2), - pg_advisory_unlock(1, 1), pg_advisory_unlock(1, 1), - pg_advisory_unlock_shared(2, 2), pg_advisory_unlock_shared(2, 2); - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; - - -BEGIN; - --- holding both session and xact locks on the same objects, session first -SELECT - pg_advisory_lock(1), pg_advisory_lock_shared(2), - pg_advisory_lock(1, 1), pg_advisory_lock_shared(2, 2); - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - -SELECT - pg_advisory_xact_lock(1), pg_advisory_xact_lock_shared(2), - pg_advisory_xact_lock(1, 1), pg_advisory_xact_lock_shared(2, 2); - -ROLLBACK; - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - - --- releasing all session locks -SELECT pg_advisory_unlock_all(); - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; - - -BEGIN; - --- grabbing txn locks multiple times - -SELECT - pg_advisory_xact_lock(1), pg_advisory_xact_lock(1), - pg_advisory_xact_lock_shared(2), pg_advisory_xact_lock_shared(2), - pg_advisory_xact_lock(1, 1), pg_advisory_xact_lock(1, 1), - pg_advisory_xact_lock_shared(2, 2), pg_advisory_xact_lock_shared(2, 2); - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - -COMMIT; - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; - --- grabbing session locks multiple times - -SELECT - pg_advisory_lock(1), pg_advisory_lock(1), - pg_advisory_lock_shared(2), pg_advisory_lock_shared(2), - pg_advisory_lock(1, 1), pg_advisory_lock(1, 1), - pg_advisory_lock_shared(2, 2), pg_advisory_lock_shared(2, 2); - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - -SELECT - pg_advisory_unlock(1), pg_advisory_unlock(1), - pg_advisory_unlock_shared(2), pg_advisory_unlock_shared(2), - pg_advisory_unlock(1, 1), pg_advisory_unlock(1, 1), - pg_advisory_unlock_shared(2, 2), pg_advisory_unlock_shared(2, 2); - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; - --- .. and releasing them all at once - -SELECT - pg_advisory_lock(1), pg_advisory_lock(1), - pg_advisory_lock_shared(2), pg_advisory_lock_shared(2), - pg_advisory_lock(1, 1), pg_advisory_lock(1, 1), - pg_advisory_lock_shared(2, 2), pg_advisory_lock_shared(2, 2); - -SELECT locktype, classid, objid, objsubid, mode, granted - FROM pg_locks WHERE locktype = 'advisory' - ORDER BY classid, objid, objsubid; - -SELECT pg_advisory_unlock_all(); - -SELECT count(*) FROM pg_locks WHERE locktype = 'advisory'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Faggregates.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Faggregates.sql deleted file mode 100644 index c6e0d7ba2b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Faggregates.sql +++ /dev/null @@ -1,1361 +0,0 @@ --- --- AGGREGATES --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - --- avoid bit-exact output here because operations may not be bit-exact. -SET extra_float_digits = 0; - --- prepare some test data -CREATE TABLE aggtest ( - a int2, - b float4 -); - -\set filename :abs_srcdir '/data/agg.data' -COPY aggtest FROM :'filename'; - -ANALYZE aggtest; - - -SELECT avg(four) AS avg_1 FROM onek; - -SELECT avg(a) AS avg_32 FROM aggtest WHERE a < 100; - --- In 7.1, avg(float4) is computed using float8 arithmetic. --- Round the result to 3 digits to avoid platform-specific results. - -SELECT avg(b)::numeric(10,3) AS avg_107_943 FROM aggtest; - -SELECT avg(gpa) AS avg_3_4 FROM ONLY student; - - -SELECT sum(four) AS sum_1500 FROM onek; -SELECT sum(a) AS sum_198 FROM aggtest; -SELECT sum(b) AS avg_431_773 FROM aggtest; -SELECT sum(gpa) AS avg_6_8 FROM ONLY student; - -SELECT max(four) AS max_3 FROM onek; -SELECT max(a) AS max_100 FROM aggtest; -SELECT max(aggtest.b) AS max_324_78 FROM aggtest; -SELECT max(student.gpa) AS max_3_7 FROM student; - -SELECT stddev_pop(b) FROM aggtest; -SELECT stddev_samp(b) FROM aggtest; -SELECT var_pop(b) FROM aggtest; -SELECT var_samp(b) FROM aggtest; - -SELECT stddev_pop(b::numeric) FROM aggtest; -SELECT stddev_samp(b::numeric) FROM aggtest; -SELECT var_pop(b::numeric) FROM aggtest; -SELECT var_samp(b::numeric) FROM aggtest; - --- population variance is defined for a single tuple, sample variance --- is not -SELECT var_pop(1.0::float8), var_samp(2.0::float8); -SELECT stddev_pop(3.0::float8), stddev_samp(4.0::float8); -SELECT var_pop('inf'::float8), var_samp('inf'::float8); -SELECT stddev_pop('inf'::float8), stddev_samp('inf'::float8); -SELECT var_pop('nan'::float8), var_samp('nan'::float8); -SELECT stddev_pop('nan'::float8), stddev_samp('nan'::float8); -SELECT var_pop(1.0::float4), var_samp(2.0::float4); -SELECT stddev_pop(3.0::float4), stddev_samp(4.0::float4); -SELECT var_pop('inf'::float4), var_samp('inf'::float4); -SELECT stddev_pop('inf'::float4), stddev_samp('inf'::float4); -SELECT var_pop('nan'::float4), var_samp('nan'::float4); -SELECT stddev_pop('nan'::float4), stddev_samp('nan'::float4); -SELECT var_pop(1.0::numeric), var_samp(2.0::numeric); -SELECT stddev_pop(3.0::numeric), stddev_samp(4.0::numeric); -SELECT var_pop('inf'::numeric), var_samp('inf'::numeric); -SELECT stddev_pop('inf'::numeric), stddev_samp('inf'::numeric); -SELECT var_pop('nan'::numeric), var_samp('nan'::numeric); -SELECT stddev_pop('nan'::numeric), stddev_samp('nan'::numeric); - --- verify correct results for null and NaN inputs -select sum(null::int4) from generate_series(1,3); -select sum(null::int8) from generate_series(1,3); -select sum(null::numeric) from generate_series(1,3); -select sum(null::float8) from generate_series(1,3); -select avg(null::int4) from generate_series(1,3); -select avg(null::int8) from generate_series(1,3); -select avg(null::numeric) from generate_series(1,3); -select avg(null::float8) from generate_series(1,3); -select sum('NaN'::numeric) from generate_series(1,3); -select avg('NaN'::numeric) from generate_series(1,3); - --- verify correct results for infinite inputs -SELECT sum(x::float8), avg(x::float8), var_pop(x::float8) -FROM (VALUES ('1'), ('infinity')) v(x); -SELECT sum(x::float8), avg(x::float8), var_pop(x::float8) -FROM (VALUES ('infinity'), ('1')) v(x); -SELECT sum(x::float8), avg(x::float8), var_pop(x::float8) -FROM (VALUES ('infinity'), ('infinity')) v(x); -SELECT sum(x::float8), avg(x::float8), var_pop(x::float8) -FROM (VALUES ('-infinity'), ('infinity')) v(x); -SELECT sum(x::float8), avg(x::float8), var_pop(x::float8) -FROM (VALUES ('-infinity'), ('-infinity')) v(x); -SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric) -FROM (VALUES ('1'), ('infinity')) v(x); -SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric) -FROM (VALUES ('infinity'), ('1')) v(x); -SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric) -FROM (VALUES ('infinity'), ('infinity')) v(x); -SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric) -FROM (VALUES ('-infinity'), ('infinity')) v(x); -SELECT sum(x::numeric), avg(x::numeric), var_pop(x::numeric) -FROM (VALUES ('-infinity'), ('-infinity')) v(x); - --- test accuracy with a large input offset -SELECT avg(x::float8), var_pop(x::float8) -FROM (VALUES (100000003), (100000004), (100000006), (100000007)) v(x); -SELECT avg(x::float8), var_pop(x::float8) -FROM (VALUES (7000000000005), (7000000000007)) v(x); - --- SQL2003 binary aggregates -SELECT regr_count(b, a) FROM aggtest; -SELECT regr_sxx(b, a) FROM aggtest; -SELECT regr_syy(b, a) FROM aggtest; -SELECT regr_sxy(b, a) FROM aggtest; -SELECT regr_avgx(b, a), regr_avgy(b, a) FROM aggtest; -SELECT regr_r2(b, a) FROM aggtest; -SELECT regr_slope(b, a), regr_intercept(b, a) FROM aggtest; -SELECT covar_pop(b, a), covar_samp(b, a) FROM aggtest; -SELECT corr(b, a) FROM aggtest; - --- check single-tuple behavior -SELECT covar_pop(1::float8,2::float8), covar_samp(3::float8,4::float8); -SELECT covar_pop(1::float8,'inf'::float8), covar_samp(3::float8,'inf'::float8); -SELECT covar_pop(1::float8,'nan'::float8), covar_samp(3::float8,'nan'::float8); - --- test accum and combine functions directly -CREATE TABLE regr_test (x float8, y float8); -INSERT INTO regr_test VALUES (10,150),(20,250),(30,350),(80,540),(100,200); -SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x) -FROM regr_test WHERE x IN (10,20,30,80); -SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x) -FROM regr_test; -SELECT float8_accum('{4,140,2900}'::float8[], 100); -SELECT float8_regr_accum('{4,140,2900,1290,83075,15050}'::float8[], 200, 100); -SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x) -FROM regr_test WHERE x IN (10,20,30); -SELECT count(*), sum(x), regr_sxx(y,x), sum(y),regr_syy(y,x), regr_sxy(y,x) -FROM regr_test WHERE x IN (80,100); -SELECT float8_combine('{3,60,200}'::float8[], '{0,0,0}'::float8[]); -SELECT float8_combine('{0,0,0}'::float8[], '{2,180,200}'::float8[]); -SELECT float8_combine('{3,60,200}'::float8[], '{2,180,200}'::float8[]); -SELECT float8_regr_combine('{3,60,200,750,20000,2000}'::float8[], - '{0,0,0,0,0,0}'::float8[]); -SELECT float8_regr_combine('{0,0,0,0,0,0}'::float8[], - '{2,180,200,740,57800,-3400}'::float8[]); -SELECT float8_regr_combine('{3,60,200,750,20000,2000}'::float8[], - '{2,180,200,740,57800,-3400}'::float8[]); -DROP TABLE regr_test; - --- test count, distinct -SELECT count(four) AS cnt_1000 FROM onek; -SELECT count(DISTINCT four) AS cnt_4 FROM onek; - -select ten, count(*), sum(four) from onek -group by ten order by ten; - -select ten, count(four), sum(DISTINCT four) from onek -group by ten order by ten; - --- user-defined aggregates -SELECT newavg(four) AS avg_1 FROM onek; -SELECT newsum(four) AS sum_1500 FROM onek; -SELECT newcnt(four) AS cnt_1000 FROM onek; -SELECT newcnt(*) AS cnt_1000 FROM onek; -SELECT oldcnt(*) AS cnt_1000 FROM onek; -SELECT sum2(q1,q2) FROM int8_tbl; - --- test for outer-level aggregates - --- this should work -select ten, sum(distinct four) from onek a -group by ten -having exists (select 1 from onek b where sum(distinct a.four) = b.four); - --- this should fail because subquery has an agg of its own in WHERE -select ten, sum(distinct four) from onek a -group by ten -having exists (select 1 from onek b - where sum(distinct a.four + b.four) = b.four); - --- Test handling of sublinks within outer-level aggregates. --- Per bug report from Daniel Grace. -select - (select max((select i.unique2 from tenk1 i where i.unique1 = o.unique1))) -from tenk1 o; - --- Test handling of Params within aggregate arguments in hashed aggregation. --- Per bug report from Jeevan Chalke. -explain (verbose, costs off) -select s1, s2, sm -from generate_series(1, 3) s1, - lateral (select s2, sum(s1 + s2) sm - from generate_series(1, 3) s2 group by s2) ss -order by 1, 2; -select s1, s2, sm -from generate_series(1, 3) s1, - lateral (select s2, sum(s1 + s2) sm - from generate_series(1, 3) s2 group by s2) ss -order by 1, 2; - -explain (verbose, costs off) -select array(select sum(x+y) s - from generate_series(1,3) y group by y order by s) - from generate_series(1,3) x; -select array(select sum(x+y) s - from generate_series(1,3) y group by y order by s) - from generate_series(1,3) x; - --- --- test for bitwise integer aggregates --- -CREATE TEMPORARY TABLE bitwise_test( - i2 INT2, - i4 INT4, - i8 INT8, - i INTEGER, - x INT2, - y BIT(4) -); - --- empty case -SELECT - BIT_AND(i2) AS "?", - BIT_OR(i4) AS "?", - BIT_XOR(i8) AS "?" -FROM bitwise_test; - -COPY bitwise_test FROM STDIN NULL 'null'; -1 1 1 1 1 B0101 -3 3 3 null 2 B0100 -7 7 7 3 4 B1100 -\. - -SELECT - BIT_AND(i2) AS "1", - BIT_AND(i4) AS "1", - BIT_AND(i8) AS "1", - BIT_AND(i) AS "?", - BIT_AND(x) AS "0", - BIT_AND(y) AS "0100", - - BIT_OR(i2) AS "7", - BIT_OR(i4) AS "7", - BIT_OR(i8) AS "7", - BIT_OR(i) AS "?", - BIT_OR(x) AS "7", - BIT_OR(y) AS "1101", - - BIT_XOR(i2) AS "5", - BIT_XOR(i4) AS "5", - BIT_XOR(i8) AS "5", - BIT_XOR(i) AS "?", - BIT_XOR(x) AS "7", - BIT_XOR(y) AS "1101" -FROM bitwise_test; - --- --- test boolean aggregates --- --- first test all possible transition and final states - -SELECT - -- boolean and transitions - -- null because strict - booland_statefunc(NULL, NULL) IS NULL AS "t", - booland_statefunc(TRUE, NULL) IS NULL AS "t", - booland_statefunc(FALSE, NULL) IS NULL AS "t", - booland_statefunc(NULL, TRUE) IS NULL AS "t", - booland_statefunc(NULL, FALSE) IS NULL AS "t", - -- and actual computations - booland_statefunc(TRUE, TRUE) AS "t", - NOT booland_statefunc(TRUE, FALSE) AS "t", - NOT booland_statefunc(FALSE, TRUE) AS "t", - NOT booland_statefunc(FALSE, FALSE) AS "t"; - -SELECT - -- boolean or transitions - -- null because strict - boolor_statefunc(NULL, NULL) IS NULL AS "t", - boolor_statefunc(TRUE, NULL) IS NULL AS "t", - boolor_statefunc(FALSE, NULL) IS NULL AS "t", - boolor_statefunc(NULL, TRUE) IS NULL AS "t", - boolor_statefunc(NULL, FALSE) IS NULL AS "t", - -- actual computations - boolor_statefunc(TRUE, TRUE) AS "t", - boolor_statefunc(TRUE, FALSE) AS "t", - boolor_statefunc(FALSE, TRUE) AS "t", - NOT boolor_statefunc(FALSE, FALSE) AS "t"; - -CREATE TEMPORARY TABLE bool_test( - b1 BOOL, - b2 BOOL, - b3 BOOL, - b4 BOOL); - --- empty case -SELECT - BOOL_AND(b1) AS "n", - BOOL_OR(b3) AS "n" -FROM bool_test; - -COPY bool_test FROM STDIN NULL 'null'; -TRUE null FALSE null -FALSE TRUE null null -null TRUE FALSE null -\. - -SELECT - BOOL_AND(b1) AS "f", - BOOL_AND(b2) AS "t", - BOOL_AND(b3) AS "f", - BOOL_AND(b4) AS "n", - BOOL_AND(NOT b2) AS "f", - BOOL_AND(NOT b3) AS "t" -FROM bool_test; - -SELECT - EVERY(b1) AS "f", - EVERY(b2) AS "t", - EVERY(b3) AS "f", - EVERY(b4) AS "n", - EVERY(NOT b2) AS "f", - EVERY(NOT b3) AS "t" -FROM bool_test; - -SELECT - BOOL_OR(b1) AS "t", - BOOL_OR(b2) AS "t", - BOOL_OR(b3) AS "f", - BOOL_OR(b4) AS "n", - BOOL_OR(NOT b2) AS "f", - BOOL_OR(NOT b3) AS "t" -FROM bool_test; - --- --- Test cases that should be optimized into indexscans instead of --- the generic aggregate implementation. --- - --- Basic cases -explain (costs off) - select min(unique1) from tenk1; -select min(unique1) from tenk1; -explain (costs off) - select max(unique1) from tenk1; -select max(unique1) from tenk1; -explain (costs off) - select max(unique1) from tenk1 where unique1 < 42; -select max(unique1) from tenk1 where unique1 < 42; -explain (costs off) - select max(unique1) from tenk1 where unique1 > 42; -select max(unique1) from tenk1 where unique1 > 42; - --- the planner may choose a generic aggregate here if parallel query is --- enabled, since that plan will be parallel safe and the "optimized" --- plan, which has almost identical cost, will not be. we want to test --- the optimized plan, so temporarily disable parallel query. -begin; -set local max_parallel_workers_per_gather = 0; -explain (costs off) - select max(unique1) from tenk1 where unique1 > 42000; -select max(unique1) from tenk1 where unique1 > 42000; -rollback; - --- multi-column index (uses tenk1_thous_tenthous) -explain (costs off) - select max(tenthous) from tenk1 where thousand = 33; -select max(tenthous) from tenk1 where thousand = 33; -explain (costs off) - select min(tenthous) from tenk1 where thousand = 33; -select min(tenthous) from tenk1 where thousand = 33; - --- check parameter propagation into an indexscan subquery -explain (costs off) - select f1, (select min(unique1) from tenk1 where unique1 > f1) AS gt - from int4_tbl; -select f1, (select min(unique1) from tenk1 where unique1 > f1) AS gt - from int4_tbl; - --- check some cases that were handled incorrectly in 8.3.0 -explain (costs off) - select distinct max(unique2) from tenk1; -select distinct max(unique2) from tenk1; -explain (costs off) - select max(unique2) from tenk1 order by 1; -select max(unique2) from tenk1 order by 1; -explain (costs off) - select max(unique2) from tenk1 order by max(unique2); -select max(unique2) from tenk1 order by max(unique2); -explain (costs off) - select max(unique2) from tenk1 order by max(unique2)+1; -select max(unique2) from tenk1 order by max(unique2)+1; -explain (costs off) - select max(unique2), generate_series(1,3) as g from tenk1 order by g desc; -select max(unique2), generate_series(1,3) as g from tenk1 order by g desc; - --- interesting corner case: constant gets optimized into a seqscan -explain (costs off) - select max(100) from tenk1; -select max(100) from tenk1; - --- try it on an inheritance tree -create table minmaxtest(f1 int); -create table minmaxtest1() inherits (minmaxtest); -create table minmaxtest2() inherits (minmaxtest); -create table minmaxtest3() inherits (minmaxtest); -create index minmaxtesti on minmaxtest(f1); -create index minmaxtest1i on minmaxtest1(f1); -create index minmaxtest2i on minmaxtest2(f1 desc); -create index minmaxtest3i on minmaxtest3(f1) where f1 is not null; - -insert into minmaxtest values(11), (12); -insert into minmaxtest1 values(13), (14); -insert into minmaxtest2 values(15), (16); -insert into minmaxtest3 values(17), (18); - -explain (costs off) - select min(f1), max(f1) from minmaxtest; -select min(f1), max(f1) from minmaxtest; - --- DISTINCT doesn't do anything useful here, but it shouldn't fail -explain (costs off) - select distinct min(f1), max(f1) from minmaxtest; -select distinct min(f1), max(f1) from minmaxtest; - -drop table minmaxtest cascade; - --- check for correct detection of nested-aggregate errors -select max(min(unique1)) from tenk1; -select (select max(min(unique1)) from int8_tbl) from tenk1; - --- --- Test removal of redundant GROUP BY columns --- - -create temp table t1 (a int, b int, c int, d int, primary key (a, b)); -create temp table t2 (x int, y int, z int, primary key (x, y)); -create temp table t3 (a int, b int, c int, primary key(a, b) deferrable); - --- Non-primary-key columns can be removed from GROUP BY -explain (costs off) select * from t1 group by a,b,c,d; - --- No removal can happen if the complete PK is not present in GROUP BY -explain (costs off) select a,c from t1 group by a,c,d; - --- Test removal across multiple relations -explain (costs off) select * -from t1 inner join t2 on t1.a = t2.x and t1.b = t2.y -group by t1.a,t1.b,t1.c,t1.d,t2.x,t2.y,t2.z; - --- Test case where t1 can be optimized but not t2 -explain (costs off) select t1.*,t2.x,t2.z -from t1 inner join t2 on t1.a = t2.x and t1.b = t2.y -group by t1.a,t1.b,t1.c,t1.d,t2.x,t2.z; - --- Cannot optimize when PK is deferrable -explain (costs off) select * from t3 group by a,b,c; - -create temp table t1c () inherits (t1); - --- Ensure we don't remove any columns when t1 has a child table -explain (costs off) select * from t1 group by a,b,c,d; - --- Okay to remove columns if we're only querying the parent. -explain (costs off) select * from only t1 group by a,b,c,d; - -create temp table p_t1 ( - a int, - b int, - c int, - d int, - primary key(a,b) -) partition by list(a); -create temp table p_t1_1 partition of p_t1 for values in(1); -create temp table p_t1_2 partition of p_t1 for values in(2); - --- Ensure we can remove non-PK columns for partitioned tables. -explain (costs off) select * from p_t1 group by a,b,c,d; - -drop table t1 cascade; -drop table t2; -drop table t3; -drop table p_t1; - --- --- Test GROUP BY matching of join columns that are type-coerced due to USING --- - -create temp table t1(f1 int, f2 bigint); -create temp table t2(f1 bigint, f22 bigint); - -select f1 from t1 left join t2 using (f1) group by f1; -select f1 from t1 left join t2 using (f1) group by t1.f1; -select t1.f1 from t1 left join t2 using (f1) group by t1.f1; --- only this one should fail: -select t1.f1 from t1 left join t2 using (f1) group by f1; - -drop table t1, t2; - --- --- Test combinations of DISTINCT and/or ORDER BY --- - -select array_agg(a order by b) - from (values (1,4),(2,3),(3,1),(4,2)) v(a,b); -select array_agg(a order by a) - from (values (1,4),(2,3),(3,1),(4,2)) v(a,b); -select array_agg(a order by a desc) - from (values (1,4),(2,3),(3,1),(4,2)) v(a,b); -select array_agg(b order by a desc) - from (values (1,4),(2,3),(3,1),(4,2)) v(a,b); - -select array_agg(distinct a) - from (values (1),(2),(1),(3),(null),(2)) v(a); -select array_agg(distinct a order by a) - from (values (1),(2),(1),(3),(null),(2)) v(a); -select array_agg(distinct a order by a desc) - from (values (1),(2),(1),(3),(null),(2)) v(a); -select array_agg(distinct a order by a desc nulls last) - from (values (1),(2),(1),(3),(null),(2)) v(a); - --- multi-arg aggs, strict/nonstrict, distinct/order by - -select aggfstr(a,b,c) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c); -select aggfns(a,b,c) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c); - -select aggfstr(distinct a,b,c) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,3) i; -select aggfns(distinct a,b,c) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,3) i; - -select aggfstr(distinct a,b,c order by b) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,3) i; -select aggfns(distinct a,b,c order by b) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,3) i; - --- test specific code paths - -select aggfns(distinct a,a,c order by c using ~<~,a) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,2) i; -select aggfns(distinct a,a,c order by c using ~<~) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,2) i; -select aggfns(distinct a,a,c order by a) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,2) i; -select aggfns(distinct a,b,c order by a,c using ~<~,b) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,2) i; - --- check node I/O via view creation and usage, also deparsing logic - -create view agg_view1 as - select aggfns(a,b,c) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c); - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -create or replace view agg_view1 as - select aggfns(distinct a,b,c) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,3) i; - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -create or replace view agg_view1 as - select aggfns(distinct a,b,c order by b) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,3) i; - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -create or replace view agg_view1 as - select aggfns(a,b,c order by b+1) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c); - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -create or replace view agg_view1 as - select aggfns(a,a,c order by b) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c); - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -create or replace view agg_view1 as - select aggfns(a,b,c order by c using ~<~) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c); - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -create or replace view agg_view1 as - select aggfns(distinct a,b,c order by a,c using ~<~,b) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,2) i; - -select * from agg_view1; -select pg_get_viewdef('agg_view1'::regclass); - -drop view agg_view1; - --- incorrect DISTINCT usage errors - -select aggfns(distinct a,b,c order by i) - from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i; -select aggfns(distinct a,b,c order by a,b+1) - from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i; -select aggfns(distinct a,b,c order by a,b,i,c) - from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i; -select aggfns(distinct a,a,c order by a,b) - from (values (1,1,'foo')) v(a,b,c), generate_series(1,2) i; - --- string_agg tests -select string_agg(a,',') from (values('aaaa'),('bbbb'),('cccc')) g(a); -select string_agg(a,',') from (values('aaaa'),(null),('bbbb'),('cccc')) g(a); -select string_agg(a,'AB') from (values(null),(null),('bbbb'),('cccc')) g(a); -select string_agg(a,',') from (values(null),(null)) g(a); - --- check some implicit casting cases, as per bug #5564 -select string_agg(distinct f1, ',' order by f1) from varchar_tbl; -- ok -select string_agg(distinct f1::text, ',' order by f1) from varchar_tbl; -- not ok -select string_agg(distinct f1, ',' order by f1::text) from varchar_tbl; -- not ok -select string_agg(distinct f1::text, ',' order by f1::text) from varchar_tbl; -- ok - --- string_agg bytea tests -create table bytea_test_table(v bytea); - -select string_agg(v, '') from bytea_test_table; - -insert into bytea_test_table values(decode('ff','hex')); - -select string_agg(v, '') from bytea_test_table; - -insert into bytea_test_table values(decode('aa','hex')); - -select string_agg(v, '') from bytea_test_table; -select string_agg(v, NULL) from bytea_test_table; -select string_agg(v, decode('ee', 'hex')) from bytea_test_table; - -drop table bytea_test_table; - --- FILTER tests - -select min(unique1) filter (where unique1 > 100) from tenk1; - -select sum(1/ten) filter (where ten > 0) from tenk1; - -select ten, sum(distinct four) filter (where four::text ~ '123') from onek a -group by ten; - -select ten, sum(distinct four) filter (where four > 10) from onek a -group by ten -having exists (select 1 from onek b where sum(distinct a.four) = b.four); - -select max(foo COLLATE "C") filter (where (bar collate "POSIX") > '0') -from (values ('a', 'b')) AS v(foo,bar); - --- outer reference in FILTER (PostgreSQL extension) -select (select count(*) - from (values (1)) t0(inner_c)) -from (values (2),(3)) t1(outer_c); -- inner query is aggregation query -select (select count(*) filter (where outer_c <> 0) - from (values (1)) t0(inner_c)) -from (values (2),(3)) t1(outer_c); -- outer query is aggregation query -select (select count(inner_c) filter (where outer_c <> 0) - from (values (1)) t0(inner_c)) -from (values (2),(3)) t1(outer_c); -- inner query is aggregation query -select - (select max((select i.unique2 from tenk1 i where i.unique1 = o.unique1)) - filter (where o.unique1 < 10)) -from tenk1 o; -- outer query is aggregation query - --- subquery in FILTER clause (PostgreSQL extension) -select sum(unique1) FILTER (WHERE - unique1 IN (SELECT unique1 FROM onek where unique1 < 100)) FROM tenk1; - --- exercise lots of aggregate parts with FILTER -select aggfns(distinct a,b,c order by a,c using ~<~,b) filter (where a > 1) - from (values (1,3,'foo'),(0,null,null),(2,2,'bar'),(3,1,'baz')) v(a,b,c), - generate_series(1,2) i; - --- check handling of bare boolean Var in FILTER -select max(0) filter (where b1) from bool_test; -select (select max(0) filter (where b1)) from bool_test; - --- check for correct detection of nested-aggregate errors in FILTER -select max(unique1) filter (where sum(ten) > 0) from tenk1; -select (select max(unique1) filter (where sum(ten) > 0) from int8_tbl) from tenk1; -select max(unique1) filter (where bool_or(ten > 0)) from tenk1; -select (select max(unique1) filter (where bool_or(ten > 0)) from int8_tbl) from tenk1; - - --- ordered-set aggregates - -select p, percentile_cont(p) within group (order by x::float8) -from generate_series(1,5) x, - (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p) -group by p order by p; - -select p, percentile_cont(p order by p) within group (order by x) -- error -from generate_series(1,5) x, - (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p) -group by p order by p; - -select p, sum() within group (order by x::float8) -- error -from generate_series(1,5) x, - (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p) -group by p order by p; - -select p, percentile_cont(p,p) -- error -from generate_series(1,5) x, - (values (0::float8),(0.1),(0.25),(0.4),(0.5),(0.6),(0.75),(0.9),(1)) v(p) -group by p order by p; - -select percentile_cont(0.5) within group (order by b) from aggtest; -select percentile_cont(0.5) within group (order by b), sum(b) from aggtest; -select percentile_cont(0.5) within group (order by thousand) from tenk1; -select percentile_disc(0.5) within group (order by thousand) from tenk1; -select rank(3) within group (order by x) -from (values (1),(1),(2),(2),(3),(3),(4)) v(x); -select cume_dist(3) within group (order by x) -from (values (1),(1),(2),(2),(3),(3),(4)) v(x); -select percent_rank(3) within group (order by x) -from (values (1),(1),(2),(2),(3),(3),(4),(5)) v(x); -select dense_rank(3) within group (order by x) -from (values (1),(1),(2),(2),(3),(3),(4)) v(x); - -select percentile_disc(array[0,0.1,0.25,0.5,0.75,0.9,1]) within group (order by thousand) -from tenk1; -select percentile_cont(array[0,0.25,0.5,0.75,1]) within group (order by thousand) -from tenk1; -select percentile_disc(array[[null,1,0.5],[0.75,0.25,null]]) within group (order by thousand) -from tenk1; -select percentile_cont(array[0,1,0.25,0.75,0.5,1,0.3,0.32,0.35,0.38,0.4]) within group (order by x) -from generate_series(1,6) x; - -select ten, mode() within group (order by string4) from tenk1 group by ten; - -select percentile_disc(array[0.25,0.5,0.75]) within group (order by x) -from unnest('{fred,jim,fred,jack,jill,fred,jill,jim,jim,sheila,jim,sheila}'::text[]) u(x); - --- check collation propagates up in suitable cases: -select pg_collation_for(percentile_disc(1) within group (order by x collate "POSIX")) - from (values ('fred'),('jim')) v(x); - --- ordered-set aggs created with CREATE AGGREGATE -select test_rank(3) within group (order by x) -from (values (1),(1),(2),(2),(3),(3),(4)) v(x); -select test_percentile_disc(0.5) within group (order by thousand) from tenk1; - --- ordered-set aggs can't use ungrouped vars in direct args: -select rank(x) within group (order by x) from generate_series(1,5) x; - --- outer-level agg can't use a grouped arg of a lower level, either: -select array(select percentile_disc(a) within group (order by x) - from (values (0.3),(0.7)) v(a) group by a) - from generate_series(1,5) g(x); - --- agg in the direct args is a grouping violation, too: -select rank(sum(x)) within group (order by x) from generate_series(1,5) x; - --- hypothetical-set type unification and argument-count failures: -select rank(3) within group (order by x) from (values ('fred'),('jim')) v(x); -select rank(3) within group (order by stringu1,stringu2) from tenk1; -select rank('fred') within group (order by x) from generate_series(1,5) x; -select rank('adam'::text collate "C") within group (order by x collate "POSIX") - from (values ('fred'),('jim')) v(x); --- hypothetical-set type unification successes: -select rank('adam'::varchar) within group (order by x) from (values ('fred'),('jim')) v(x); -select rank('3') within group (order by x) from generate_series(1,5) x; - --- divide by zero check -select percent_rank(0) within group (order by x) from generate_series(1,0) x; - --- deparse and multiple features: -create view aggordview1 as -select ten, - percentile_disc(0.5) within group (order by thousand) as p50, - percentile_disc(0.5) within group (order by thousand) filter (where hundred=1) as px, - rank(5,'AZZZZ',50) within group (order by hundred, string4 desc, hundred) - from tenk1 - group by ten order by ten; - -select pg_get_viewdef('aggordview1'); -select * from aggordview1 order by ten; -drop view aggordview1; - --- variadic aggregates -select least_agg(q1,q2) from int8_tbl; -select least_agg(variadic array[q1,q2]) from int8_tbl; - -select cleast_agg(q1,q2) from int8_tbl; -select cleast_agg(4.5,f1) from int4_tbl; -select cleast_agg(variadic array[4.5,f1]) from int4_tbl; -select pg_typeof(cleast_agg(variadic array[4.5,f1])) from int4_tbl; - --- test aggregates with common transition functions share the same states -begin work; - -create type avg_state as (total bigint, count bigint); - -create or replace function avg_transfn(state avg_state, n int) returns avg_state as -$$ -declare new_state avg_state; -begin - raise notice 'avg_transfn called with %', n; - if state is null then - if n is not null then - new_state.total := n; - new_state.count := 1; - return new_state; - end if; - return null; - elsif n is not null then - state.total := state.total + n; - state.count := state.count + 1; - return state; - end if; - - return null; -end -$$ language plpgsql; - -create function avg_finalfn(state avg_state) returns int4 as -$$ -begin - if state is null then - return NULL; - else - return state.total / state.count; - end if; -end -$$ language plpgsql; - -create function sum_finalfn(state avg_state) returns int4 as -$$ -begin - if state is null then - return NULL; - else - return state.total; - end if; -end -$$ language plpgsql; - -create aggregate my_avg(int4) -( - stype = avg_state, - sfunc = avg_transfn, - finalfunc = avg_finalfn -); - -create aggregate my_sum(int4) -( - stype = avg_state, - sfunc = avg_transfn, - finalfunc = sum_finalfn -); - --- aggregate state should be shared as aggs are the same. -select my_avg(one),my_avg(one) from (values(1),(3)) t(one); - --- aggregate state should be shared as transfn is the same for both aggs. -select my_avg(one),my_sum(one) from (values(1),(3)) t(one); - --- same as previous one, but with DISTINCT, which requires sorting the input. -select my_avg(distinct one),my_sum(distinct one) from (values(1),(3),(1)) t(one); - --- shouldn't share states due to the distinctness not matching. -select my_avg(distinct one),my_sum(one) from (values(1),(3)) t(one); - --- shouldn't share states due to the filter clause not matching. -select my_avg(one) filter (where one > 1),my_sum(one) from (values(1),(3)) t(one); - --- this should not share the state due to different input columns. -select my_avg(one),my_sum(two) from (values(1,2),(3,4)) t(one,two); - --- exercise cases where OSAs share state -select - percentile_cont(0.5) within group (order by a), - percentile_disc(0.5) within group (order by a) -from (values(1::float8),(3),(5),(7)) t(a); - -select - percentile_cont(0.25) within group (order by a), - percentile_disc(0.5) within group (order by a) -from (values(1::float8),(3),(5),(7)) t(a); - --- these can't share state currently -select - rank(4) within group (order by a), - dense_rank(4) within group (order by a) -from (values(1),(3),(5),(7)) t(a); - --- test that aggs with the same sfunc and initcond share the same agg state -create aggregate my_sum_init(int4) -( - stype = avg_state, - sfunc = avg_transfn, - finalfunc = sum_finalfn, - initcond = '(10,0)' -); - -create aggregate my_avg_init(int4) -( - stype = avg_state, - sfunc = avg_transfn, - finalfunc = avg_finalfn, - initcond = '(10,0)' -); - -create aggregate my_avg_init2(int4) -( - stype = avg_state, - sfunc = avg_transfn, - finalfunc = avg_finalfn, - initcond = '(4,0)' -); - --- state should be shared if INITCONDs are matching -select my_sum_init(one),my_avg_init(one) from (values(1),(3)) t(one); - --- Varying INITCONDs should cause the states not to be shared. -select my_sum_init(one),my_avg_init2(one) from (values(1),(3)) t(one); - -rollback; - --- test aggregate state sharing to ensure it works if one aggregate has a --- finalfn and the other one has none. -begin work; - -create or replace function sum_transfn(state int4, n int4) returns int4 as -$$ -declare new_state int4; -begin - raise notice 'sum_transfn called with %', n; - if state is null then - if n is not null then - new_state := n; - return new_state; - end if; - return null; - elsif n is not null then - state := state + n; - return state; - end if; - - return null; -end -$$ language plpgsql; - -create function halfsum_finalfn(state int4) returns int4 as -$$ -begin - if state is null then - return NULL; - else - return state / 2; - end if; -end -$$ language plpgsql; - -create aggregate my_sum(int4) -( - stype = int4, - sfunc = sum_transfn -); - -create aggregate my_half_sum(int4) -( - stype = int4, - sfunc = sum_transfn, - finalfunc = halfsum_finalfn -); - --- Agg state should be shared even though my_sum has no finalfn -select my_sum(one),my_half_sum(one) from (values(1),(2),(3),(4)) t(one); - -rollback; - - --- test that the aggregate transition logic correctly handles --- transition / combine functions returning NULL - --- First test the case of a normal transition function returning NULL -BEGIN; -CREATE FUNCTION balkifnull(int8, int4) -RETURNS int8 -STRICT -LANGUAGE plpgsql AS $$ -BEGIN - IF $1 IS NULL THEN - RAISE 'erroneously called with NULL argument'; - END IF; - RETURN NULL; -END$$; - -CREATE AGGREGATE balk(int4) -( - SFUNC = balkifnull(int8, int4), - STYPE = int8, - PARALLEL = SAFE, - INITCOND = '0' -); - -SELECT balk(hundred) FROM tenk1; - -ROLLBACK; - --- GROUP BY optimization by reorder columns - -SELECT - i AS id, - i/2 AS p, - format('%60s', i%2) AS v, - i/4 AS c, - i/8 AS d, - (random() * (10000/8))::int as e --the same as d but no correlation with p - INTO btg -FROM - generate_series(1, 10000) i; - -VACUUM btg; -ANALYZE btg; - --- GROUP BY optimization by reorder columns by frequency - -SET enable_hashagg=off; -SET max_parallel_workers= 0; -SET max_parallel_workers_per_gather = 0; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, v; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, c; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, c ORDER BY v, p, c; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, d, c; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, d, c ORDER BY v, p, d ,c; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, d, c ORDER BY p, v, d ,c; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, d, e; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, e, d; - -CREATE STATISTICS btg_dep ON d, e, p FROM btg; -ANALYZE btg; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, d, e; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, e, d; - - --- GROUP BY optimization by reorder columns by index scan - -CREATE INDEX ON btg(p, v); -SET enable_seqscan=off; -SET enable_bitmapscan=off; -VACUUM btg; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, v; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY p, v ORDER BY p, v; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p ORDER BY p, v; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, c; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, p, c ORDER BY p, v; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, c, p, d; - -EXPLAIN (COSTS off) -SELECT count(*) FROM btg GROUP BY v, c, p, d ORDER BY p, v; - -DROP TABLE btg; - -RESET enable_hashagg; -RESET max_parallel_workers; -RESET max_parallel_workers_per_gather; -RESET enable_seqscan; -RESET enable_bitmapscan; - - --- Secondly test the case of a parallel aggregate combiner function --- returning NULL. For that use normal transition function, but a --- combiner function returning NULL. -BEGIN; -CREATE FUNCTION balkifnull(int8, int8) -RETURNS int8 -PARALLEL SAFE -STRICT -LANGUAGE plpgsql AS $$ -BEGIN - IF $1 IS NULL THEN - RAISE 'erroneously called with NULL argument'; - END IF; - RETURN NULL; -END$$; - -CREATE AGGREGATE balk(int4) -( - SFUNC = int4_sum(int8, int4), - STYPE = int8, - COMBINEFUNC = balkifnull(int8, int8), - PARALLEL = SAFE, - INITCOND = '0' -); - --- force use of parallelism -ALTER TABLE tenk1 set (parallel_workers = 4); -SET LOCAL parallel_setup_cost=0; -SET LOCAL max_parallel_workers_per_gather=4; - -EXPLAIN (COSTS OFF) SELECT balk(hundred) FROM tenk1; -SELECT balk(hundred) FROM tenk1; - -ROLLBACK; - --- test coverage for aggregate combine/serial/deserial functions -BEGIN; - -SET parallel_setup_cost = 0; -SET parallel_tuple_cost = 0; -SET min_parallel_table_scan_size = 0; -SET max_parallel_workers_per_gather = 4; -SET parallel_leader_participation = off; -SET enable_indexonlyscan = off; - --- variance(int4) covers numeric_poly_combine --- sum(int8) covers int8_avg_combine --- regr_count(float8, float8) covers int8inc_float8_float8 and aggregates with > 1 arg -EXPLAIN (COSTS OFF, VERBOSE) -SELECT variance(unique1::int4), sum(unique1::int8), regr_count(unique1::float8, unique1::float8) -FROM (SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1) u; - -SELECT variance(unique1::int4), sum(unique1::int8), regr_count(unique1::float8, unique1::float8) -FROM (SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1) u; - --- variance(int8) covers numeric_combine --- avg(numeric) covers numeric_avg_combine -EXPLAIN (COSTS OFF, VERBOSE) -SELECT variance(unique1::int8), avg(unique1::numeric) -FROM (SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1) u; - -SELECT variance(unique1::int8), avg(unique1::numeric) -FROM (SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1 - UNION ALL SELECT * FROM tenk1) u; - -ROLLBACK; - --- test coverage for dense_rank -SELECT dense_rank(x) WITHIN GROUP (ORDER BY x) FROM (VALUES (1),(1),(2),(2),(3),(3)) v(x) GROUP BY (x) ORDER BY 1; - - --- Ensure that the STRICT checks for aggregates does not take NULLness --- of ORDER BY columns into account. See bug report around --- 2a505161-2727-2473-7c46-591ed108ac52@email.cz -SELECT min(x ORDER BY y) FROM (VALUES(1, NULL)) AS d(x,y); -SELECT min(x ORDER BY y) FROM (VALUES(1, 2)) AS d(x,y); - --- check collation-sensitive matching between grouping expressions -select v||'a', case v||'a' when 'aa' then 1 else 0 end, count(*) - from unnest(array['a','b']) u(v) - group by v||'a' order by 1; -select v||'a', case when v||'a' = 'aa' then 1 else 0 end, count(*) - from unnest(array['a','b']) u(v) - group by v||'a' order by 1; - --- Make sure that generation of HashAggregate for uniqification purposes --- does not lead to array overflow due to unexpected duplicate hash keys --- see CAFeeJoKKu0u+A_A9R9316djW-YW3-+Gtgvy3ju655qRHR3jtdA@mail.gmail.com -set enable_memoize to off; -explain (costs off) - select 1 from tenk1 - where (hundred, thousand) in (select twothousand, twothousand from onek); -reset enable_memoize; - --- --- Hash Aggregation Spill tests --- - -set enable_sort=false; -set work_mem='64kB'; - -select unique1, count(*), sum(twothousand) from tenk1 -group by unique1 -having sum(fivethous) > 4975 -order by sum(twothousand); - -set work_mem to default; -set enable_sort to default; - --- --- Compare results between plans using sorting and plans using hash --- aggregation. Force spilling in both cases by setting work_mem low. --- - -set work_mem='64kB'; - -create table agg_data_2k as -select g from generate_series(0, 1999) g; -analyze agg_data_2k; - -create table agg_data_20k as -select g from generate_series(0, 19999) g; -analyze agg_data_20k; - --- Produce results with sorting. - -set enable_hashagg = false; - -set jit_above_cost = 0; - -explain (costs off) -select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3 - from agg_data_20k group by g%10000; - -create table agg_group_1 as -select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3 - from agg_data_20k group by g%10000; - -create table agg_group_2 as -select * from - (values (100), (300), (500)) as r(a), - lateral ( - select (g/2)::numeric as c1, - array_agg(g::numeric) as c2, - count(*) as c3 - from agg_data_2k - where g < r.a - group by g/2) as s; - -set jit_above_cost to default; - -create table agg_group_3 as -select (g/2)::numeric as c1, sum(7::int4) as c2, count(*) as c3 - from agg_data_2k group by g/2; - -create table agg_group_4 as -select (g/2)::numeric as c1, array_agg(g::numeric) as c2, count(*) as c3 - from agg_data_2k group by g/2; - --- Produce results with hash aggregation - -set enable_hashagg = true; -set enable_sort = false; - -set jit_above_cost = 0; - -explain (costs off) -select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3 - from agg_data_20k group by g%10000; - -create table agg_hash_1 as -select g%10000 as c1, sum(g::numeric) as c2, count(*) as c3 - from agg_data_20k group by g%10000; - -create table agg_hash_2 as -select * from - (values (100), (300), (500)) as r(a), - lateral ( - select (g/2)::numeric as c1, - array_agg(g::numeric) as c2, - count(*) as c3 - from agg_data_2k - where g < r.a - group by g/2) as s; - -set jit_above_cost to default; - -create table agg_hash_3 as -select (g/2)::numeric as c1, sum(7::int4) as c2, count(*) as c3 - from agg_data_2k group by g/2; - -create table agg_hash_4 as -select (g/2)::numeric as c1, array_agg(g::numeric) as c2, count(*) as c3 - from agg_data_2k group by g/2; - -set enable_sort = true; -set work_mem to default; - --- Compare group aggregation results to hash aggregation results - -(select * from agg_hash_1 except select * from agg_group_1) - union all -(select * from agg_group_1 except select * from agg_hash_1); - -(select * from agg_hash_2 except select * from agg_group_2) - union all -(select * from agg_group_2 except select * from agg_hash_2); - -(select * from agg_hash_3 except select * from agg_group_3) - union all -(select * from agg_group_3 except select * from agg_hash_3); - -(select * from agg_hash_4 except select * from agg_group_4) - union all -(select * from agg_group_4 except select * from agg_hash_4); - -drop table agg_group_1; -drop table agg_group_2; -drop table agg_group_3; -drop table agg_group_4; -drop table agg_hash_1; -drop table agg_hash_2; -drop table agg_hash_3; -drop table agg_hash_4; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Falter_operator.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Falter_operator.sql deleted file mode 100644 index fd40370165..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Falter_operator.sql +++ /dev/null @@ -1,100 +0,0 @@ -CREATE FUNCTION alter_op_test_fn(boolean, boolean) -RETURNS boolean AS $$ SELECT NULL::BOOLEAN; $$ LANGUAGE sql IMMUTABLE; - -CREATE FUNCTION customcontsel(internal, oid, internal, integer) -RETURNS float8 AS 'contsel' LANGUAGE internal STABLE STRICT; - -CREATE OPERATOR === ( - LEFTARG = boolean, - RIGHTARG = boolean, - PROCEDURE = alter_op_test_fn, - COMMUTATOR = ===, - NEGATOR = !==, - RESTRICT = customcontsel, - JOIN = contjoinsel, - HASHES, MERGES -); - -SELECT pg_describe_object(refclassid,refobjid,refobjsubid) as ref, deptype -FROM pg_depend -WHERE classid = 'pg_operator'::regclass AND - objid = '===(bool,bool)'::regoperator -ORDER BY 1; - --- --- Reset and set params --- - -ALTER OPERATOR === (boolean, boolean) SET (RESTRICT = NONE); -ALTER OPERATOR === (boolean, boolean) SET (JOIN = NONE); - -SELECT oprrest, oprjoin FROM pg_operator WHERE oprname = '===' - AND oprleft = 'boolean'::regtype AND oprright = 'boolean'::regtype; - -SELECT pg_describe_object(refclassid,refobjid,refobjsubid) as ref, deptype -FROM pg_depend -WHERE classid = 'pg_operator'::regclass AND - objid = '===(bool,bool)'::regoperator -ORDER BY 1; - -ALTER OPERATOR === (boolean, boolean) SET (RESTRICT = contsel); -ALTER OPERATOR === (boolean, boolean) SET (JOIN = contjoinsel); - -SELECT oprrest, oprjoin FROM pg_operator WHERE oprname = '===' - AND oprleft = 'boolean'::regtype AND oprright = 'boolean'::regtype; - -SELECT pg_describe_object(refclassid,refobjid,refobjsubid) as ref, deptype -FROM pg_depend -WHERE classid = 'pg_operator'::regclass AND - objid = '===(bool,bool)'::regoperator -ORDER BY 1; - -ALTER OPERATOR === (boolean, boolean) SET (RESTRICT = NONE, JOIN = NONE); - -SELECT oprrest, oprjoin FROM pg_operator WHERE oprname = '===' - AND oprleft = 'boolean'::regtype AND oprright = 'boolean'::regtype; - -SELECT pg_describe_object(refclassid,refobjid,refobjsubid) as ref, deptype -FROM pg_depend -WHERE classid = 'pg_operator'::regclass AND - objid = '===(bool,bool)'::regoperator -ORDER BY 1; - -ALTER OPERATOR === (boolean, boolean) SET (RESTRICT = customcontsel, JOIN = contjoinsel); - -SELECT oprrest, oprjoin FROM pg_operator WHERE oprname = '===' - AND oprleft = 'boolean'::regtype AND oprright = 'boolean'::regtype; - -SELECT pg_describe_object(refclassid,refobjid,refobjsubid) as ref, deptype -FROM pg_depend -WHERE classid = 'pg_operator'::regclass AND - objid = '===(bool,bool)'::regoperator -ORDER BY 1; - --- --- Test invalid options. --- -ALTER OPERATOR === (boolean, boolean) SET (COMMUTATOR = ====); -ALTER OPERATOR === (boolean, boolean) SET (NEGATOR = ====); -ALTER OPERATOR === (boolean, boolean) SET (RESTRICT = non_existent_func); -ALTER OPERATOR === (boolean, boolean) SET (JOIN = non_existent_func); -ALTER OPERATOR === (boolean, boolean) SET (COMMUTATOR = !==); -ALTER OPERATOR === (boolean, boolean) SET (NEGATOR = !==); - --- invalid: non-lowercase quoted identifiers -ALTER OPERATOR & (bit, bit) SET ("Restrict" = _int_contsel, "Join" = _int_contjoinsel); - --- --- Test permission check. Must be owner to ALTER OPERATOR. --- -CREATE USER regress_alter_op_user; -SET SESSION AUTHORIZATION regress_alter_op_user; - -ALTER OPERATOR === (boolean, boolean) SET (RESTRICT = NONE); - --- Clean up -RESET SESSION AUTHORIZATION; -DROP USER regress_alter_op_user; -DROP OPERATOR === (boolean, boolean); -DROP FUNCTION customcontsel(internal, oid, internal, integer); -DROP FUNCTION alter_op_test_fn(boolean, boolean); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Falter_table.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Falter_table.sql deleted file mode 100644 index 52001e3135..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Falter_table.sql +++ /dev/null @@ -1,3034 +0,0 @@ --- --- ALTER_TABLE --- - --- Clean up in case a prior regression run failed -SET client_min_messages TO 'warning'; -DROP ROLE IF EXISTS regress_alter_table_user1; -RESET client_min_messages; - -CREATE USER regress_alter_table_user1; - --- --- add attribute --- - -CREATE TABLE attmp (initial int4); - -COMMENT ON TABLE attmp_wrong IS 'table comment'; -COMMENT ON TABLE attmp IS 'table comment'; -COMMENT ON TABLE attmp IS NULL; - -ALTER TABLE attmp ADD COLUMN xmin integer; -- fails - -ALTER TABLE attmp ADD COLUMN a int4 default 3; - -ALTER TABLE attmp ADD COLUMN b name; - -ALTER TABLE attmp ADD COLUMN c text; - -ALTER TABLE attmp ADD COLUMN d float8; - -ALTER TABLE attmp ADD COLUMN e float4; - -ALTER TABLE attmp ADD COLUMN f int2; - -ALTER TABLE attmp ADD COLUMN g polygon; - -ALTER TABLE attmp ADD COLUMN i char; - -ALTER TABLE attmp ADD COLUMN k int4; - -ALTER TABLE attmp ADD COLUMN l tid; - -ALTER TABLE attmp ADD COLUMN m xid; - -ALTER TABLE attmp ADD COLUMN n oidvector; - ---ALTER TABLE attmp ADD COLUMN o lock; -ALTER TABLE attmp ADD COLUMN p boolean; - -ALTER TABLE attmp ADD COLUMN q point; - -ALTER TABLE attmp ADD COLUMN r lseg; - -ALTER TABLE attmp ADD COLUMN s path; - -ALTER TABLE attmp ADD COLUMN t box; - -ALTER TABLE attmp ADD COLUMN v timestamp; - -ALTER TABLE attmp ADD COLUMN w interval; - -ALTER TABLE attmp ADD COLUMN x float8[]; - -ALTER TABLE attmp ADD COLUMN y float4[]; - -ALTER TABLE attmp ADD COLUMN z int2[]; - -INSERT INTO attmp (a, b, c, d, e, f, g, i, k, l, m, n, p, q, r, s, t, - v, w, x, y, z) - VALUES (4, 'name', 'text', 4.1, 4.1, 2, '(4.1,4.1,3.1,3.1)', - 'c', - 314159, '(1,1)', '512', - '1 2 3 4 5 6 7 8', true, '(1.1,1.1)', '(4.1,4.1,3.1,3.1)', - '(0,2,4.1,4.1,3.1,3.1)', '(4.1,4.1,3.1,3.1)', - 'epoch', '01:00:10', '{1.0,2.0,3.0,4.0}', '{1.0,2.0,3.0,4.0}', '{1,2,3,4}'); - -SELECT * FROM attmp; - -DROP TABLE attmp; - --- the wolf bug - schema mods caused inconsistent row descriptors -CREATE TABLE attmp ( - initial int4 -); - -ALTER TABLE attmp ADD COLUMN a int4; - -ALTER TABLE attmp ADD COLUMN b name; - -ALTER TABLE attmp ADD COLUMN c text; - -ALTER TABLE attmp ADD COLUMN d float8; - -ALTER TABLE attmp ADD COLUMN e float4; - -ALTER TABLE attmp ADD COLUMN f int2; - -ALTER TABLE attmp ADD COLUMN g polygon; - -ALTER TABLE attmp ADD COLUMN i char; - -ALTER TABLE attmp ADD COLUMN k int4; - -ALTER TABLE attmp ADD COLUMN l tid; - -ALTER TABLE attmp ADD COLUMN m xid; - -ALTER TABLE attmp ADD COLUMN n oidvector; - ---ALTER TABLE attmp ADD COLUMN o lock; -ALTER TABLE attmp ADD COLUMN p boolean; - -ALTER TABLE attmp ADD COLUMN q point; - -ALTER TABLE attmp ADD COLUMN r lseg; - -ALTER TABLE attmp ADD COLUMN s path; - -ALTER TABLE attmp ADD COLUMN t box; - -ALTER TABLE attmp ADD COLUMN v timestamp; - -ALTER TABLE attmp ADD COLUMN w interval; - -ALTER TABLE attmp ADD COLUMN x float8[]; - -ALTER TABLE attmp ADD COLUMN y float4[]; - -ALTER TABLE attmp ADD COLUMN z int2[]; - -INSERT INTO attmp (a, b, c, d, e, f, g, i, k, l, m, n, p, q, r, s, t, - v, w, x, y, z) - VALUES (4, 'name', 'text', 4.1, 4.1, 2, '(4.1,4.1,3.1,3.1)', - 'c', - 314159, '(1,1)', '512', - '1 2 3 4 5 6 7 8', true, '(1.1,1.1)', '(4.1,4.1,3.1,3.1)', - '(0,2,4.1,4.1,3.1,3.1)', '(4.1,4.1,3.1,3.1)', - 'epoch', '01:00:10', '{1.0,2.0,3.0,4.0}', '{1.0,2.0,3.0,4.0}', '{1,2,3,4}'); - -SELECT * FROM attmp; - -CREATE INDEX attmp_idx ON attmp (a, (d + e), b); - -ALTER INDEX attmp_idx ALTER COLUMN 0 SET STATISTICS 1000; - -ALTER INDEX attmp_idx ALTER COLUMN 1 SET STATISTICS 1000; - -ALTER INDEX attmp_idx ALTER COLUMN 2 SET STATISTICS 1000; - -\d+ attmp_idx - -ALTER INDEX attmp_idx ALTER COLUMN 3 SET STATISTICS 1000; - -ALTER INDEX attmp_idx ALTER COLUMN 4 SET STATISTICS 1000; - -ALTER INDEX attmp_idx ALTER COLUMN 2 SET STATISTICS -1; - -DROP TABLE attmp; - - --- --- rename - check on both non-temp and temp tables --- -CREATE TABLE attmp (regtable int); -CREATE TEMP TABLE attmp (attmptable int); - -ALTER TABLE attmp RENAME TO attmp_new; - -SELECT * FROM attmp; -SELECT * FROM attmp_new; - -ALTER TABLE attmp RENAME TO attmp_new2; - -SELECT * FROM attmp; -- should fail -SELECT * FROM attmp_new; -SELECT * FROM attmp_new2; - -DROP TABLE attmp_new; -DROP TABLE attmp_new2; - --- check rename of partitioned tables and indexes also -CREATE TABLE part_attmp (a int primary key) partition by range (a); -CREATE TABLE part_attmp1 PARTITION OF part_attmp FOR VALUES FROM (0) TO (100); -ALTER INDEX part_attmp_pkey RENAME TO part_attmp_index; -ALTER INDEX part_attmp1_pkey RENAME TO part_attmp1_index; -ALTER TABLE part_attmp RENAME TO part_at2tmp; -ALTER TABLE part_attmp1 RENAME TO part_at2tmp1; -SET ROLE regress_alter_table_user1; -ALTER INDEX part_attmp_index RENAME TO fail; -ALTER INDEX part_attmp1_index RENAME TO fail; -ALTER TABLE part_at2tmp RENAME TO fail; -ALTER TABLE part_at2tmp1 RENAME TO fail; -RESET ROLE; -DROP TABLE part_at2tmp; - --- --- check renaming to a table's array type's autogenerated name --- (the array type's name should get out of the way) --- -CREATE TABLE attmp_array (id int); -CREATE TABLE attmp_array2 (id int); -SELECT typname FROM pg_type WHERE oid = 'attmp_array[]'::regtype; -SELECT typname FROM pg_type WHERE oid = 'attmp_array2[]'::regtype; -ALTER TABLE attmp_array2 RENAME TO _attmp_array; -SELECT typname FROM pg_type WHERE oid = 'attmp_array[]'::regtype; -SELECT typname FROM pg_type WHERE oid = '_attmp_array[]'::regtype; -DROP TABLE _attmp_array; -DROP TABLE attmp_array; - --- renaming to table's own array type's name is an interesting corner case -CREATE TABLE attmp_array (id int); -SELECT typname FROM pg_type WHERE oid = 'attmp_array[]'::regtype; -ALTER TABLE attmp_array RENAME TO _attmp_array; -SELECT typname FROM pg_type WHERE oid = '_attmp_array[]'::regtype; -DROP TABLE _attmp_array; - --- ALTER TABLE ... RENAME on non-table relations --- renaming indexes (FIXME: this should probably test the index's functionality) -ALTER INDEX IF EXISTS __onek_unique1 RENAME TO attmp_onek_unique1; -ALTER INDEX IF EXISTS __attmp_onek_unique1 RENAME TO onek_unique1; - -ALTER INDEX onek_unique1 RENAME TO attmp_onek_unique1; -ALTER INDEX attmp_onek_unique1 RENAME TO onek_unique1; - -SET ROLE regress_alter_table_user1; -ALTER INDEX onek_unique1 RENAME TO fail; -- permission denied -RESET ROLE; - --- rename statements with mismatching statement and object types -CREATE TABLE alter_idx_rename_test (a INT); -CREATE INDEX alter_idx_rename_test_idx ON alter_idx_rename_test (a); -CREATE TABLE alter_idx_rename_test_parted (a INT) PARTITION BY LIST (a); -CREATE INDEX alter_idx_rename_test_parted_idx ON alter_idx_rename_test_parted (a); -BEGIN; -ALTER INDEX alter_idx_rename_test RENAME TO alter_idx_rename_test_2; -ALTER INDEX alter_idx_rename_test_parted RENAME TO alter_idx_rename_test_parted_2; -SELECT relation::regclass, mode FROM pg_locks -WHERE pid = pg_backend_pid() AND locktype = 'relation' - AND relation::regclass::text LIKE 'alter\_idx%' -ORDER BY relation::regclass::text COLLATE "C"; -COMMIT; -BEGIN; -ALTER INDEX alter_idx_rename_test_idx RENAME TO alter_idx_rename_test_idx_2; -ALTER INDEX alter_idx_rename_test_parted_idx RENAME TO alter_idx_rename_test_parted_idx_2; -SELECT relation::regclass, mode FROM pg_locks -WHERE pid = pg_backend_pid() AND locktype = 'relation' - AND relation::regclass::text LIKE 'alter\_idx%' -ORDER BY relation::regclass::text COLLATE "C"; -COMMIT; -BEGIN; -ALTER TABLE alter_idx_rename_test_idx_2 RENAME TO alter_idx_rename_test_idx_3; -ALTER TABLE alter_idx_rename_test_parted_idx_2 RENAME TO alter_idx_rename_test_parted_idx_3; -SELECT relation::regclass, mode FROM pg_locks -WHERE pid = pg_backend_pid() AND locktype = 'relation' - AND relation::regclass::text LIKE 'alter\_idx%' -ORDER BY relation::regclass::text COLLATE "C"; -COMMIT; -DROP TABLE alter_idx_rename_test_2; - --- renaming views -CREATE VIEW attmp_view (unique1) AS SELECT unique1 FROM tenk1; -ALTER TABLE attmp_view RENAME TO attmp_view_new; - -SET ROLE regress_alter_table_user1; -ALTER VIEW attmp_view_new RENAME TO fail; -- permission denied -RESET ROLE; - --- hack to ensure we get an indexscan here -set enable_seqscan to off; -set enable_bitmapscan to off; --- 5 values, sorted -SELECT unique1 FROM tenk1 WHERE unique1 < 5; -reset enable_seqscan; -reset enable_bitmapscan; - -DROP VIEW attmp_view_new; --- toast-like relation name -alter table stud_emp rename to pg_toast_stud_emp; -alter table pg_toast_stud_emp rename to stud_emp; - --- renaming index should rename constraint as well -ALTER TABLE onek ADD CONSTRAINT onek_unique1_constraint UNIQUE (unique1); -ALTER INDEX onek_unique1_constraint RENAME TO onek_unique1_constraint_foo; -ALTER TABLE onek DROP CONSTRAINT onek_unique1_constraint_foo; - --- renaming constraint -ALTER TABLE onek ADD CONSTRAINT onek_check_constraint CHECK (unique1 >= 0); -ALTER TABLE onek RENAME CONSTRAINT onek_check_constraint TO onek_check_constraint_foo; -ALTER TABLE onek DROP CONSTRAINT onek_check_constraint_foo; - --- renaming constraint should rename index as well -ALTER TABLE onek ADD CONSTRAINT onek_unique1_constraint UNIQUE (unique1); -DROP INDEX onek_unique1_constraint; -- to see whether it's there -ALTER TABLE onek RENAME CONSTRAINT onek_unique1_constraint TO onek_unique1_constraint_foo; -DROP INDEX onek_unique1_constraint_foo; -- to see whether it's there -ALTER TABLE onek DROP CONSTRAINT onek_unique1_constraint_foo; - --- renaming constraints vs. inheritance -CREATE TABLE constraint_rename_test (a int CONSTRAINT con1 CHECK (a > 0), b int, c int); -\d constraint_rename_test -CREATE TABLE constraint_rename_test2 (a int CONSTRAINT con1 CHECK (a > 0), d int) INHERITS (constraint_rename_test); -\d constraint_rename_test2 -ALTER TABLE constraint_rename_test2 RENAME CONSTRAINT con1 TO con1foo; -- fail -ALTER TABLE ONLY constraint_rename_test RENAME CONSTRAINT con1 TO con1foo; -- fail -ALTER TABLE constraint_rename_test RENAME CONSTRAINT con1 TO con1foo; -- ok -\d constraint_rename_test -\d constraint_rename_test2 -ALTER TABLE constraint_rename_test ADD CONSTRAINT con2 CHECK (b > 0) NO INHERIT; -ALTER TABLE ONLY constraint_rename_test RENAME CONSTRAINT con2 TO con2foo; -- ok -ALTER TABLE constraint_rename_test RENAME CONSTRAINT con2foo TO con2bar; -- ok -\d constraint_rename_test -\d constraint_rename_test2 -ALTER TABLE constraint_rename_test ADD CONSTRAINT con3 PRIMARY KEY (a); -ALTER TABLE constraint_rename_test RENAME CONSTRAINT con3 TO con3foo; -- ok -\d constraint_rename_test -\d constraint_rename_test2 -DROP TABLE constraint_rename_test2; -DROP TABLE constraint_rename_test; -ALTER TABLE IF EXISTS constraint_not_exist RENAME CONSTRAINT con3 TO con3foo; -- ok -ALTER TABLE IF EXISTS constraint_rename_test ADD CONSTRAINT con4 UNIQUE (a); - --- renaming constraints with cache reset of target relation -CREATE TABLE constraint_rename_cache (a int, - CONSTRAINT chk_a CHECK (a > 0), - PRIMARY KEY (a)); -ALTER TABLE constraint_rename_cache - RENAME CONSTRAINT chk_a TO chk_a_new; -ALTER TABLE constraint_rename_cache - RENAME CONSTRAINT constraint_rename_cache_pkey TO constraint_rename_pkey_new; -CREATE TABLE like_constraint_rename_cache - (LIKE constraint_rename_cache INCLUDING ALL); -\d like_constraint_rename_cache -DROP TABLE constraint_rename_cache; -DROP TABLE like_constraint_rename_cache; - --- FOREIGN KEY CONSTRAINT adding TEST - -CREATE TABLE attmp2 (a int primary key); - -CREATE TABLE attmp3 (a int, b int); - -CREATE TABLE attmp4 (a int, b int, unique(a,b)); - -CREATE TABLE attmp5 (a int, b int); - --- Insert rows into attmp2 (pktable) -INSERT INTO attmp2 values (1); -INSERT INTO attmp2 values (2); -INSERT INTO attmp2 values (3); -INSERT INTO attmp2 values (4); - --- Insert rows into attmp3 -INSERT INTO attmp3 values (1,10); -INSERT INTO attmp3 values (1,20); -INSERT INTO attmp3 values (5,50); - --- Try (and fail) to add constraint due to invalid source columns -ALTER TABLE attmp3 add constraint attmpconstr foreign key(c) references attmp2 match full; - --- Try (and fail) to add constraint due to invalid destination columns explicitly given -ALTER TABLE attmp3 add constraint attmpconstr foreign key(a) references attmp2(b) match full; - --- Try (and fail) to add constraint due to invalid data -ALTER TABLE attmp3 add constraint attmpconstr foreign key (a) references attmp2 match full; - --- Delete failing row -DELETE FROM attmp3 where a=5; - --- Try (and succeed) -ALTER TABLE attmp3 add constraint attmpconstr foreign key (a) references attmp2 match full; -ALTER TABLE attmp3 drop constraint attmpconstr; - -INSERT INTO attmp3 values (5,50); - --- Try NOT VALID and then VALIDATE CONSTRAINT, but fails. Delete failure then re-validate -ALTER TABLE attmp3 add constraint attmpconstr foreign key (a) references attmp2 match full NOT VALID; -ALTER TABLE attmp3 validate constraint attmpconstr; - --- Delete failing row -DELETE FROM attmp3 where a=5; - --- Try (and succeed) and repeat to show it works on already valid constraint -ALTER TABLE attmp3 validate constraint attmpconstr; -ALTER TABLE attmp3 validate constraint attmpconstr; - --- Try a non-verified CHECK constraint -ALTER TABLE attmp3 ADD CONSTRAINT b_greater_than_ten CHECK (b > 10); -- fail -ALTER TABLE attmp3 ADD CONSTRAINT b_greater_than_ten CHECK (b > 10) NOT VALID; -- succeeds -ALTER TABLE attmp3 VALIDATE CONSTRAINT b_greater_than_ten; -- fails -DELETE FROM attmp3 WHERE NOT b > 10; -ALTER TABLE attmp3 VALIDATE CONSTRAINT b_greater_than_ten; -- succeeds -ALTER TABLE attmp3 VALIDATE CONSTRAINT b_greater_than_ten; -- succeeds - --- Test inherited NOT VALID CHECK constraints -select * from attmp3; -CREATE TABLE attmp6 () INHERITS (attmp3); -CREATE TABLE attmp7 () INHERITS (attmp3); - -INSERT INTO attmp6 VALUES (6, 30), (7, 16); -ALTER TABLE attmp3 ADD CONSTRAINT b_le_20 CHECK (b <= 20) NOT VALID; -ALTER TABLE attmp3 VALIDATE CONSTRAINT b_le_20; -- fails -DELETE FROM attmp6 WHERE b > 20; -ALTER TABLE attmp3 VALIDATE CONSTRAINT b_le_20; -- succeeds - --- An already validated constraint must not be revalidated -CREATE FUNCTION boo(int) RETURNS int IMMUTABLE STRICT LANGUAGE plpgsql AS $$ BEGIN RAISE NOTICE 'boo: %', $1; RETURN $1; END; $$; -INSERT INTO attmp7 VALUES (8, 18); -ALTER TABLE attmp7 ADD CONSTRAINT identity CHECK (b = boo(b)); -ALTER TABLE attmp3 ADD CONSTRAINT IDENTITY check (b = boo(b)) NOT VALID; -ALTER TABLE attmp3 VALIDATE CONSTRAINT identity; - --- A NO INHERIT constraint should not be looked for in children during VALIDATE CONSTRAINT -create table parent_noinh_convalid (a int); -create table child_noinh_convalid () inherits (parent_noinh_convalid); -insert into parent_noinh_convalid values (1); -insert into child_noinh_convalid values (1); -alter table parent_noinh_convalid add constraint check_a_is_2 check (a = 2) no inherit not valid; --- fail, because of the row in parent -alter table parent_noinh_convalid validate constraint check_a_is_2; -delete from only parent_noinh_convalid; --- ok (parent itself contains no violating rows) -alter table parent_noinh_convalid validate constraint check_a_is_2; -select convalidated from pg_constraint where conrelid = 'parent_noinh_convalid'::regclass and conname = 'check_a_is_2'; --- cleanup -drop table parent_noinh_convalid, child_noinh_convalid; - --- Try (and fail) to create constraint from attmp5(a) to attmp4(a) - unique constraint on --- attmp4 is a,b - -ALTER TABLE attmp5 add constraint attmpconstr foreign key(a) references attmp4(a) match full; - -DROP TABLE attmp7; - -DROP TABLE attmp6; - -DROP TABLE attmp5; - -DROP TABLE attmp4; - -DROP TABLE attmp3; - -DROP TABLE attmp2; - --- NOT VALID with plan invalidation -- ensure we don't use a constraint for --- exclusion until validated -set constraint_exclusion TO 'partition'; -create table nv_parent (d date, check (false) no inherit not valid); --- not valid constraint added at creation time should automatically become valid -\d nv_parent - -create table nv_child_2010 () inherits (nv_parent); -create table nv_child_2011 () inherits (nv_parent); -alter table nv_child_2010 add check (d between '2010-01-01'::date and '2010-12-31'::date) not valid; -alter table nv_child_2011 add check (d between '2011-01-01'::date and '2011-12-31'::date) not valid; -explain (costs off) select * from nv_parent where d between '2011-08-01' and '2011-08-31'; -create table nv_child_2009 (check (d between '2009-01-01'::date and '2009-12-31'::date)) inherits (nv_parent); -explain (costs off) select * from nv_parent where d between '2011-08-01'::date and '2011-08-31'::date; -explain (costs off) select * from nv_parent where d between '2009-08-01'::date and '2009-08-31'::date; --- after validation, the constraint should be used -alter table nv_child_2011 VALIDATE CONSTRAINT nv_child_2011_d_check; -explain (costs off) select * from nv_parent where d between '2009-08-01'::date and '2009-08-31'::date; - --- add an inherited NOT VALID constraint -alter table nv_parent add check (d between '2001-01-01'::date and '2099-12-31'::date) not valid; -\d nv_child_2009 --- we leave nv_parent and children around to help test pg_dump logic - --- Foreign key adding test with mixed types - --- Note: these tables are TEMP to avoid name conflicts when this test --- is run in parallel with foreign_key.sql. - -CREATE TEMP TABLE PKTABLE (ptest1 int PRIMARY KEY); -INSERT INTO PKTABLE VALUES(42); -CREATE TEMP TABLE FKTABLE (ftest1 inet); --- This next should fail, because int=inet does not exist -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1) references pktable; --- This should also fail for the same reason, but here we --- give the column name -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1) references pktable(ptest1); -DROP TABLE FKTABLE; --- This should succeed, even though they are different types, --- because int=int8 exists and is a member of the integer opfamily -CREATE TEMP TABLE FKTABLE (ftest1 int8); -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1) references pktable; --- Check it actually works -INSERT INTO FKTABLE VALUES(42); -- should succeed -INSERT INTO FKTABLE VALUES(43); -- should fail -DROP TABLE FKTABLE; --- This should fail, because we'd have to cast numeric to int which is --- not an implicit coercion (or use numeric=numeric, but that's not part --- of the integer opfamily) -CREATE TEMP TABLE FKTABLE (ftest1 numeric); -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1) references pktable; -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; --- On the other hand, this should work because int implicitly promotes to --- numeric, and we allow promotion on the FK side -CREATE TEMP TABLE PKTABLE (ptest1 numeric PRIMARY KEY); -INSERT INTO PKTABLE VALUES(42); -CREATE TEMP TABLE FKTABLE (ftest1 int); -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1) references pktable; --- Check it actually works -INSERT INTO FKTABLE VALUES(42); -- should succeed -INSERT INTO FKTABLE VALUES(43); -- should fail -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - -CREATE TEMP TABLE PKTABLE (ptest1 int, ptest2 inet, - PRIMARY KEY(ptest1, ptest2)); --- This should fail, because we just chose really odd types -CREATE TEMP TABLE FKTABLE (ftest1 cidr, ftest2 timestamp); -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1, ftest2) references pktable; -DROP TABLE FKTABLE; --- Again, so should this... -CREATE TEMP TABLE FKTABLE (ftest1 cidr, ftest2 timestamp); -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1, ftest2) - references pktable(ptest1, ptest2); -DROP TABLE FKTABLE; --- This fails because we mixed up the column ordering -CREATE TEMP TABLE FKTABLE (ftest1 int, ftest2 inet); -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1, ftest2) - references pktable(ptest2, ptest1); --- As does this... -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest2, ftest1) - references pktable(ptest1, ptest2); -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- Test that ALTER CONSTRAINT updates trigger deferrability properly - -CREATE TEMP TABLE PKTABLE (ptest1 int primary key); -CREATE TEMP TABLE FKTABLE (ftest1 int); - -ALTER TABLE FKTABLE ADD CONSTRAINT fknd FOREIGN KEY(ftest1) REFERENCES pktable - ON DELETE CASCADE ON UPDATE NO ACTION NOT DEFERRABLE; -ALTER TABLE FKTABLE ADD CONSTRAINT fkdd FOREIGN KEY(ftest1) REFERENCES pktable - ON DELETE CASCADE ON UPDATE NO ACTION DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE FKTABLE ADD CONSTRAINT fkdi FOREIGN KEY(ftest1) REFERENCES pktable - ON DELETE CASCADE ON UPDATE NO ACTION DEFERRABLE INITIALLY IMMEDIATE; - -ALTER TABLE FKTABLE ADD CONSTRAINT fknd2 FOREIGN KEY(ftest1) REFERENCES pktable - ON DELETE CASCADE ON UPDATE NO ACTION DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE FKTABLE ALTER CONSTRAINT fknd2 NOT DEFERRABLE; -ALTER TABLE FKTABLE ADD CONSTRAINT fkdd2 FOREIGN KEY(ftest1) REFERENCES pktable - ON DELETE CASCADE ON UPDATE NO ACTION NOT DEFERRABLE; -ALTER TABLE FKTABLE ALTER CONSTRAINT fkdd2 DEFERRABLE INITIALLY DEFERRED; -ALTER TABLE FKTABLE ADD CONSTRAINT fkdi2 FOREIGN KEY(ftest1) REFERENCES pktable - ON DELETE CASCADE ON UPDATE NO ACTION NOT DEFERRABLE; -ALTER TABLE FKTABLE ALTER CONSTRAINT fkdi2 DEFERRABLE INITIALLY IMMEDIATE; - -SELECT conname, tgfoid::regproc, tgtype, tgdeferrable, tginitdeferred -FROM pg_trigger JOIN pg_constraint con ON con.oid = tgconstraint -WHERE tgrelid = 'pktable'::regclass -ORDER BY 1,2,3; -SELECT conname, tgfoid::regproc, tgtype, tgdeferrable, tginitdeferred -FROM pg_trigger JOIN pg_constraint con ON con.oid = tgconstraint -WHERE tgrelid = 'fktable'::regclass -ORDER BY 1,2,3; - --- temp tables should go away by themselves, need not drop them. - --- test check constraint adding - -create table atacc1 ( test int ); --- add a check constraint -alter table atacc1 add constraint atacc_test1 check (test>3); --- should fail -insert into atacc1 (test) values (2); --- should succeed -insert into atacc1 (test) values (4); -drop table atacc1; - --- let's do one where the check fails when added -create table atacc1 ( test int ); --- insert a soon to be failing row -insert into atacc1 (test) values (2); --- add a check constraint (fails) -alter table atacc1 add constraint atacc_test1 check (test>3); -insert into atacc1 (test) values (4); -drop table atacc1; - --- let's do one where the check fails because the column doesn't exist -create table atacc1 ( test int ); --- add a check constraint (fails) -alter table atacc1 add constraint atacc_test1 check (test1>3); -drop table atacc1; - --- something a little more complicated -create table atacc1 ( test int, test2 int, test3 int); --- add a check constraint (fails) -alter table atacc1 add constraint atacc_test1 check (test+test23), test2 int); -alter table atacc1 add check (test2>test); --- should fail for $2 -insert into atacc1 (test2, test) values (3, 4); -drop table atacc1; - --- inheritance related tests -create table atacc1 (test int); -create table atacc2 (test2 int); -create table atacc3 (test3 int) inherits (atacc1, atacc2); -alter table atacc2 add constraint foo check (test2>0); --- fail and then succeed on atacc2 -insert into atacc2 (test2) values (-3); -insert into atacc2 (test2) values (3); --- fail and then succeed on atacc3 -insert into atacc3 (test2) values (-3); -insert into atacc3 (test2) values (3); -drop table atacc3; -drop table atacc2; -drop table atacc1; - --- same things with one created with INHERIT -create table atacc1 (test int); -create table atacc2 (test2 int); -create table atacc3 (test3 int) inherits (atacc1, atacc2); -alter table atacc3 no inherit atacc2; --- fail -alter table atacc3 no inherit atacc2; --- make sure it really isn't a child -insert into atacc3 (test2) values (3); -select test2 from atacc2; --- fail due to missing constraint -alter table atacc2 add constraint foo check (test2>0); -alter table atacc3 inherit atacc2; --- fail due to missing column -alter table atacc3 rename test2 to testx; -alter table atacc3 inherit atacc2; --- fail due to mismatched data type -alter table atacc3 add test2 bool; -alter table atacc3 inherit atacc2; -alter table atacc3 drop test2; --- succeed -alter table atacc3 add test2 int; -update atacc3 set test2 = 4 where test2 is null; -alter table atacc3 add constraint foo check (test2>0); -alter table atacc3 inherit atacc2; --- fail due to duplicates and circular inheritance -alter table atacc3 inherit atacc2; -alter table atacc2 inherit atacc3; -alter table atacc2 inherit atacc2; --- test that we really are a child now (should see 4 not 3 and cascade should go through) -select test2 from atacc2; -drop table atacc2 cascade; -drop table atacc1; - --- adding only to a parent is allowed as of 9.2 - -create table atacc1 (test int); -create table atacc2 (test2 int) inherits (atacc1); --- ok: -alter table atacc1 add constraint foo check (test>0) no inherit; --- check constraint is not there on child -insert into atacc2 (test) values (-3); --- check constraint is there on parent -insert into atacc1 (test) values (-3); -insert into atacc1 (test) values (3); --- fail, violating row: -alter table atacc2 add constraint foo check (test>0) no inherit; -drop table atacc2; -drop table atacc1; - --- test unique constraint adding - -create table atacc1 ( test int ) ; --- add a unique constraint -alter table atacc1 add constraint atacc_test1 unique (test); --- insert first value -insert into atacc1 (test) values (2); --- should fail -insert into atacc1 (test) values (2); --- should succeed -insert into atacc1 (test) values (4); --- try to create duplicates via alter table using - should fail -alter table atacc1 alter column test type integer using 0; -drop table atacc1; - --- let's do one where the unique constraint fails when added -create table atacc1 ( test int ); --- insert soon to be failing rows -insert into atacc1 (test) values (2); -insert into atacc1 (test) values (2); --- add a unique constraint (fails) -alter table atacc1 add constraint atacc_test1 unique (test); -insert into atacc1 (test) values (3); -drop table atacc1; - --- let's do one where the unique constraint fails --- because the column doesn't exist -create table atacc1 ( test int ); --- add a unique constraint (fails) -alter table atacc1 add constraint atacc_test1 unique (test1); -drop table atacc1; - --- something a little more complicated -create table atacc1 ( test int, test2 int); --- add a unique constraint -alter table atacc1 add constraint atacc_test1 unique (test, test2); --- insert initial value -insert into atacc1 (test,test2) values (4,4); --- should fail -insert into atacc1 (test,test2) values (4,4); --- should all succeed -insert into atacc1 (test,test2) values (4,5); -insert into atacc1 (test,test2) values (5,4); -insert into atacc1 (test,test2) values (5,5); -drop table atacc1; - --- lets do some naming tests -create table atacc1 (test int, test2 int, unique(test)); -alter table atacc1 add unique (test2); --- should fail for @@ second one @@ -insert into atacc1 (test2, test) values (3, 3); -insert into atacc1 (test2, test) values (2, 3); -drop table atacc1; - --- test primary key constraint adding - -create table atacc1 ( id serial, test int) ; --- add a primary key constraint -alter table atacc1 add constraint atacc_test1 primary key (test); --- insert first value -insert into atacc1 (test) values (2); --- should fail -insert into atacc1 (test) values (2); --- should succeed -insert into atacc1 (test) values (4); --- inserting NULL should fail -insert into atacc1 (test) values(NULL); --- try adding a second primary key (should fail) -alter table atacc1 add constraint atacc_oid1 primary key(id); --- drop first primary key constraint -alter table atacc1 drop constraint atacc_test1 restrict; --- try adding a primary key on oid (should succeed) -alter table atacc1 add constraint atacc_oid1 primary key(id); -drop table atacc1; - --- let's do one where the primary key constraint fails when added -create table atacc1 ( test int ); --- insert soon to be failing rows -insert into atacc1 (test) values (2); -insert into atacc1 (test) values (2); --- add a primary key (fails) -alter table atacc1 add constraint atacc_test1 primary key (test); -insert into atacc1 (test) values (3); -drop table atacc1; - --- let's do another one where the primary key constraint fails when added -create table atacc1 ( test int ); --- insert soon to be failing row -insert into atacc1 (test) values (NULL); --- add a primary key (fails) -alter table atacc1 add constraint atacc_test1 primary key (test); -insert into atacc1 (test) values (3); -drop table atacc1; - --- let's do one where the primary key constraint fails --- because the column doesn't exist -create table atacc1 ( test int ); --- add a primary key constraint (fails) -alter table atacc1 add constraint atacc_test1 primary key (test1); -drop table atacc1; - --- adding a new column as primary key to a non-empty table. --- should fail unless the column has a non-null default value. -create table atacc1 ( test int ); -insert into atacc1 (test) values (0); --- add a primary key column without a default (fails). -alter table atacc1 add column test2 int primary key; --- now add a primary key column with a default (succeeds). -alter table atacc1 add column test2 int default 0 primary key; -drop table atacc1; - --- this combination used to have order-of-execution problems (bug #15580) -create table atacc1 (a int); -insert into atacc1 values(1); -alter table atacc1 - add column b float8 not null default random(), - add primary key(a); -drop table atacc1; - --- additionally, we've seen issues with foreign key validation not being --- properly delayed until after a table rewrite. Check that works ok. -create table atacc1 (a int primary key); -alter table atacc1 add constraint atacc1_fkey foreign key (a) references atacc1 (a) not valid; -alter table atacc1 validate constraint atacc1_fkey, alter a type bigint; -drop table atacc1; - --- we've also seen issues with check constraints being validated at the wrong --- time when there's a pending table rewrite. -create table atacc1 (a bigint, b int); -insert into atacc1 values(1,1); -alter table atacc1 add constraint atacc1_chk check(b = 1) not valid; -alter table atacc1 validate constraint atacc1_chk, alter a type int; -drop table atacc1; - --- same as above, but ensure the constraint violation is detected -create table atacc1 (a bigint, b int); -insert into atacc1 values(1,2); -alter table atacc1 add constraint atacc1_chk check(b = 1) not valid; -alter table atacc1 validate constraint atacc1_chk, alter a type int; -drop table atacc1; - --- something a little more complicated -create table atacc1 ( test int, test2 int); --- add a primary key constraint -alter table atacc1 add constraint atacc_test1 primary key (test, test2); --- try adding a second primary key - should fail -alter table atacc1 add constraint atacc_test2 primary key (test); --- insert initial value -insert into atacc1 (test,test2) values (4,4); --- should fail -insert into atacc1 (test,test2) values (4,4); -insert into atacc1 (test,test2) values (NULL,3); -insert into atacc1 (test,test2) values (3, NULL); -insert into atacc1 (test,test2) values (NULL,NULL); --- should all succeed -insert into atacc1 (test,test2) values (4,5); -insert into atacc1 (test,test2) values (5,4); -insert into atacc1 (test,test2) values (5,5); -drop table atacc1; - --- lets do some naming tests -create table atacc1 (test int, test2 int, primary key(test)); --- only first should succeed -insert into atacc1 (test2, test) values (3, 3); -insert into atacc1 (test2, test) values (2, 3); -insert into atacc1 (test2, test) values (1, NULL); -drop table atacc1; - --- alter table / alter column [set/drop] not null tests --- try altering system catalogs, should fail -alter table pg_class alter column relname drop not null; -alter table pg_class alter relname set not null; - --- try altering non-existent table, should fail -alter table non_existent alter column bar set not null; -alter table non_existent alter column bar drop not null; - --- test setting columns to null and not null and vice versa --- test checking for null values and primary key -create table atacc1 (test int not null); -alter table atacc1 add constraint "atacc1_pkey" primary key (test); -alter table atacc1 alter column test drop not null; -alter table atacc1 drop constraint "atacc1_pkey"; -alter table atacc1 alter column test drop not null; -insert into atacc1 values (null); -alter table atacc1 alter test set not null; -delete from atacc1; -alter table atacc1 alter test set not null; - --- try altering a non-existent column, should fail -alter table atacc1 alter bar set not null; -alter table atacc1 alter bar drop not null; - --- try creating a view and altering that, should fail -create view myview as select * from atacc1; -alter table myview alter column test drop not null; -alter table myview alter column test set not null; -drop view myview; - -drop table atacc1; - --- set not null verified by constraints -create table atacc1 (test_a int, test_b int); -insert into atacc1 values (null, 1); --- constraint not cover all values, should fail -alter table atacc1 add constraint atacc1_constr_or check(test_a is not null or test_b < 10); -alter table atacc1 alter test_a set not null; -alter table atacc1 drop constraint atacc1_constr_or; --- not valid constraint, should fail -alter table atacc1 add constraint atacc1_constr_invalid check(test_a is not null) not valid; -alter table atacc1 alter test_a set not null; -alter table atacc1 drop constraint atacc1_constr_invalid; --- with valid constraint -update atacc1 set test_a = 1; -alter table atacc1 add constraint atacc1_constr_a_valid check(test_a is not null); -alter table atacc1 alter test_a set not null; -delete from atacc1; - -insert into atacc1 values (2, null); -alter table atacc1 alter test_a drop not null; --- test multiple set not null at same time --- test_a checked by atacc1_constr_a_valid, test_b should fail by table scan -alter table atacc1 alter test_a set not null, alter test_b set not null; --- commands order has no importance -alter table atacc1 alter test_b set not null, alter test_a set not null; - --- valid one by table scan, one by check constraints -update atacc1 set test_b = 1; -alter table atacc1 alter test_b set not null, alter test_a set not null; - -alter table atacc1 alter test_a drop not null, alter test_b drop not null; --- both column has check constraints -alter table atacc1 add constraint atacc1_constr_b_valid check(test_b is not null); -alter table atacc1 alter test_b set not null, alter test_a set not null; -drop table atacc1; - --- test inheritance -create table parent (a int); -create table child (b varchar(255)) inherits (parent); - -alter table parent alter a set not null; -insert into parent values (NULL); -insert into child (a, b) values (NULL, 'foo'); -alter table parent alter a drop not null; -insert into parent values (NULL); -insert into child (a, b) values (NULL, 'foo'); -alter table only parent alter a set not null; -alter table child alter a set not null; -delete from parent; -alter table only parent alter a set not null; -insert into parent values (NULL); -alter table child alter a set not null; -insert into child (a, b) values (NULL, 'foo'); -delete from child; -alter table child alter a set not null; -insert into child (a, b) values (NULL, 'foo'); -drop table child; -drop table parent; - --- test setting and removing default values -create table def_test ( - c1 int4 default 5, - c2 text default 'initial_default' -); -insert into def_test default values; -alter table def_test alter column c1 drop default; -insert into def_test default values; -alter table def_test alter column c2 drop default; -insert into def_test default values; -alter table def_test alter column c1 set default 10; -alter table def_test alter column c2 set default 'new_default'; -insert into def_test default values; -select * from def_test; - --- set defaults to an incorrect type: this should fail -alter table def_test alter column c1 set default 'wrong_datatype'; -alter table def_test alter column c2 set default 20; - --- set defaults on a non-existent column: this should fail -alter table def_test alter column c3 set default 30; - --- set defaults on views: we need to create a view, add a rule --- to allow insertions into it, and then alter the view to add --- a default -create view def_view_test as select * from def_test; -create rule def_view_test_ins as - on insert to def_view_test - do instead insert into def_test select new.*; -insert into def_view_test default values; -alter table def_view_test alter column c1 set default 45; -insert into def_view_test default values; -alter table def_view_test alter column c2 set default 'view_default'; -insert into def_view_test default values; -select * from def_view_test; - -drop rule def_view_test_ins on def_view_test; -drop view def_view_test; -drop table def_test; - --- alter table / drop column tests --- try altering system catalogs, should fail -alter table pg_class drop column relname; - --- try altering non-existent table, should fail -alter table nosuchtable drop column bar; - --- test dropping columns -create table atacc1 (a int4 not null, b int4, c int4 not null, d int4); -insert into atacc1 values (1, 2, 3, 4); -alter table atacc1 drop a; -alter table atacc1 drop a; - --- SELECTs -select * from atacc1; -select * from atacc1 order by a; -select * from atacc1 order by "........pg.dropped.1........"; -select * from atacc1 group by a; -select * from atacc1 group by "........pg.dropped.1........"; -select atacc1.* from atacc1; -select a from atacc1; -select atacc1.a from atacc1; -select b,c,d from atacc1; -select a,b,c,d from atacc1; -select * from atacc1 where a = 1; -select "........pg.dropped.1........" from atacc1; -select atacc1."........pg.dropped.1........" from atacc1; -select "........pg.dropped.1........",b,c,d from atacc1; -select * from atacc1 where "........pg.dropped.1........" = 1; - --- UPDATEs -update atacc1 set a = 3; -update atacc1 set b = 2 where a = 3; -update atacc1 set "........pg.dropped.1........" = 3; -update atacc1 set b = 2 where "........pg.dropped.1........" = 3; - --- INSERTs -insert into atacc1 values (10, 11, 12, 13); -insert into atacc1 values (default, 11, 12, 13); -insert into atacc1 values (11, 12, 13); -insert into atacc1 (a) values (10); -insert into atacc1 (a) values (default); -insert into atacc1 (a,b,c,d) values (10,11,12,13); -insert into atacc1 (a,b,c,d) values (default,11,12,13); -insert into atacc1 (b,c,d) values (11,12,13); -insert into atacc1 ("........pg.dropped.1........") values (10); -insert into atacc1 ("........pg.dropped.1........") values (default); -insert into atacc1 ("........pg.dropped.1........",b,c,d) values (10,11,12,13); -insert into atacc1 ("........pg.dropped.1........",b,c,d) values (default,11,12,13); - --- DELETEs -delete from atacc1 where a = 3; -delete from atacc1 where "........pg.dropped.1........" = 3; -delete from atacc1; - --- try dropping a non-existent column, should fail -alter table atacc1 drop bar; - --- try removing an oid column, should succeed (as it's nonexistent) -alter table atacc1 SET WITHOUT OIDS; - --- try adding an oid column, should fail (not supported) -alter table atacc1 SET WITH OIDS; - --- try dropping the xmin column, should fail -alter table atacc1 drop xmin; - --- try creating a view and altering that, should fail -create view myview as select * from atacc1; -select * from myview; -alter table myview drop d; -drop view myview; - --- test some commands to make sure they fail on the dropped column -analyze atacc1(a); -analyze atacc1("........pg.dropped.1........"); -vacuum analyze atacc1(a); -vacuum analyze atacc1("........pg.dropped.1........"); -comment on column atacc1.a is 'testing'; -comment on column atacc1."........pg.dropped.1........" is 'testing'; -alter table atacc1 alter a set storage plain; -alter table atacc1 alter "........pg.dropped.1........" set storage plain; -alter table atacc1 alter a set statistics 0; -alter table atacc1 alter "........pg.dropped.1........" set statistics 0; -alter table atacc1 alter a set default 3; -alter table atacc1 alter "........pg.dropped.1........" set default 3; -alter table atacc1 alter a drop default; -alter table atacc1 alter "........pg.dropped.1........" drop default; -alter table atacc1 alter a set not null; -alter table atacc1 alter "........pg.dropped.1........" set not null; -alter table atacc1 alter a drop not null; -alter table atacc1 alter "........pg.dropped.1........" drop not null; -alter table atacc1 rename a to x; -alter table atacc1 rename "........pg.dropped.1........" to x; -alter table atacc1 add primary key(a); -alter table atacc1 add primary key("........pg.dropped.1........"); -alter table atacc1 add unique(a); -alter table atacc1 add unique("........pg.dropped.1........"); -alter table atacc1 add check (a > 3); -alter table atacc1 add check ("........pg.dropped.1........" > 3); -create table atacc2 (id int4 unique); -alter table atacc1 add foreign key (a) references atacc2(id); -alter table atacc1 add foreign key ("........pg.dropped.1........") references atacc2(id); -alter table atacc2 add foreign key (id) references atacc1(a); -alter table atacc2 add foreign key (id) references atacc1("........pg.dropped.1........"); -drop table atacc2; -create index "testing_idx" on atacc1(a); -create index "testing_idx" on atacc1("........pg.dropped.1........"); - --- test create as and select into -insert into atacc1 values (21, 22, 23); -create table attest1 as select * from atacc1; -select * from attest1; -drop table attest1; -select * into attest2 from atacc1; -select * from attest2; -drop table attest2; - --- try dropping all columns -alter table atacc1 drop c; -alter table atacc1 drop d; -alter table atacc1 drop b; -select * from atacc1; - -drop table atacc1; - --- test constraint error reporting in presence of dropped columns -create table atacc1 (id serial primary key, value int check (value < 10)); -insert into atacc1(value) values (100); -alter table atacc1 drop column value; -alter table atacc1 add column value int check (value < 10); -insert into atacc1(value) values (100); -insert into atacc1(id, value) values (null, 0); -drop table atacc1; - --- test inheritance -create table parent (a int, b int, c int); -insert into parent values (1, 2, 3); -alter table parent drop a; -create table child (d varchar(255)) inherits (parent); -insert into child values (12, 13, 'testing'); - -select * from parent; -select * from child; -alter table parent drop c; -select * from parent; -select * from child; - -drop table child; -drop table parent; - --- check error cases for inheritance column merging -create table parent (a float8, b numeric(10,4), c text collate "C"); - -create table child (a float4) inherits (parent); -- fail -create table child (b decimal(10,7)) inherits (parent); -- fail -create table child (c text collate "POSIX") inherits (parent); -- fail -create table child (a double precision, b decimal(10,4)) inherits (parent); - -drop table child; -drop table parent; - --- test copy in/out -create table attest (a int4, b int4, c int4); -insert into attest values (1,2,3); -alter table attest drop a; -copy attest to stdout; -copy attest(a) to stdout; -copy attest("........pg.dropped.1........") to stdout; -copy attest from stdin; -10 11 12 -\. -select * from attest; -copy attest from stdin; -21 22 -\. -select * from attest; -copy attest(a) from stdin; -copy attest("........pg.dropped.1........") from stdin; -copy attest(b,c) from stdin; -31 32 -\. -select * from attest; -drop table attest; - --- test inheritance - -create table dropColumn (a int, b int, e int); -create table dropColumnChild (c int) inherits (dropColumn); -create table dropColumnAnother (d int) inherits (dropColumnChild); - --- these two should fail -alter table dropColumnchild drop column a; -alter table only dropColumnChild drop column b; - - - --- these three should work -alter table only dropColumn drop column e; -alter table dropColumnChild drop column c; -alter table dropColumn drop column a; - -create table renameColumn (a int); -create table renameColumnChild (b int) inherits (renameColumn); -create table renameColumnAnother (c int) inherits (renameColumnChild); - --- these three should fail -alter table renameColumnChild rename column a to d; -alter table only renameColumnChild rename column a to d; -alter table only renameColumn rename column a to d; - --- these should work -alter table renameColumn rename column a to d; -alter table renameColumnChild rename column b to a; - --- these should work -alter table if exists doesnt_exist_tab rename column a to d; -alter table if exists doesnt_exist_tab rename column b to a; - --- this should work -alter table renameColumn add column w int; - --- this should fail -alter table only renameColumn add column x int; - - --- Test corner cases in dropping of inherited columns - -create table p1 (f1 int, f2 int); -create table c1 (f1 int not null) inherits(p1); - --- should be rejected since c1.f1 is inherited -alter table c1 drop column f1; --- should work -alter table p1 drop column f1; --- c1.f1 is still there, but no longer inherited -select f1 from c1; -alter table c1 drop column f1; -select f1 from c1; - -drop table p1 cascade; - -create table p1 (f1 int, f2 int); -create table c1 () inherits(p1); - --- should be rejected since c1.f1 is inherited -alter table c1 drop column f1; -alter table p1 drop column f1; --- c1.f1 is dropped now, since there is no local definition for it -select f1 from c1; - -drop table p1 cascade; - -create table p1 (f1 int, f2 int); -create table c1 () inherits(p1); - --- should be rejected since c1.f1 is inherited -alter table c1 drop column f1; -alter table only p1 drop column f1; --- c1.f1 is NOT dropped, but must now be considered non-inherited -alter table c1 drop column f1; - -drop table p1 cascade; - -create table p1 (f1 int, f2 int); -create table c1 (f1 int not null) inherits(p1); - --- should be rejected since c1.f1 is inherited -alter table c1 drop column f1; -alter table only p1 drop column f1; --- c1.f1 is still there, but no longer inherited -alter table c1 drop column f1; - -drop table p1 cascade; - -create table p1(id int, name text); -create table p2(id2 int, name text, height int); -create table c1(age int) inherits(p1,p2); -create table gc1() inherits (c1); - -select relname, attname, attinhcount, attislocal -from pg_class join pg_attribute on (pg_class.oid = pg_attribute.attrelid) -where relname in ('p1','p2','c1','gc1') and attnum > 0 and not attisdropped -order by relname, attnum; - --- should work -alter table only p1 drop column name; --- should work. Now c1.name is local and inhcount is 0. -alter table p2 drop column name; --- should be rejected since its inherited -alter table gc1 drop column name; --- should work, and drop gc1.name along -alter table c1 drop column name; --- should fail: column does not exist -alter table gc1 drop column name; --- should work and drop the attribute in all tables -alter table p2 drop column height; - --- IF EXISTS test -create table dropColumnExists (); -alter table dropColumnExists drop column non_existing; --fail -alter table dropColumnExists drop column if exists non_existing; --succeed - -select relname, attname, attinhcount, attislocal -from pg_class join pg_attribute on (pg_class.oid = pg_attribute.attrelid) -where relname in ('p1','p2','c1','gc1') and attnum > 0 and not attisdropped -order by relname, attnum; - -drop table p1, p2 cascade; - --- test attinhcount tracking with merged columns - -create table depth0(); -create table depth1(c text) inherits (depth0); -create table depth2() inherits (depth1); -alter table depth0 add c text; - -select attrelid::regclass, attname, attinhcount, attislocal -from pg_attribute -where attnum > 0 and attrelid::regclass in ('depth0', 'depth1', 'depth2') -order by attrelid::regclass::text, attnum; - --- test renumbering of child-table columns in inherited operations - -create table p1 (f1 int); -create table c1 (f2 text, f3 int) inherits (p1); - -alter table p1 add column a1 int check (a1 > 0); -alter table p1 add column f2 text; - -insert into p1 values (1,2,'abc'); -insert into c1 values(11,'xyz',33,0); -- should fail -insert into c1 values(11,'xyz',33,22); - -select * from p1; -update p1 set a1 = a1 + 1, f2 = upper(f2); -select * from p1; - -drop table p1 cascade; - --- test that operations with a dropped column do not try to reference --- its datatype - -create domain mytype as text; -create temp table foo (f1 text, f2 mytype, f3 text); - -insert into foo values('bb','cc','dd'); -select * from foo; - -drop domain mytype cascade; - -select * from foo; -insert into foo values('qq','rr'); -select * from foo; -update foo set f3 = 'zz'; -select * from foo; -select f3,max(f1) from foo group by f3; - --- Simple tests for alter table column type -alter table foo alter f1 TYPE integer; -- fails -alter table foo alter f1 TYPE varchar(10); - -create table anothertab (atcol1 serial8, atcol2 boolean, - constraint anothertab_chk check (atcol1 <= 3)); - -insert into anothertab (atcol1, atcol2) values (default, true); -insert into anothertab (atcol1, atcol2) values (default, false); -select * from anothertab; - -alter table anothertab alter column atcol1 type boolean; -- fails -alter table anothertab alter column atcol1 type boolean using atcol1::int; -- fails -alter table anothertab alter column atcol1 type integer; - -select * from anothertab; - -insert into anothertab (atcol1, atcol2) values (45, null); -- fails -insert into anothertab (atcol1, atcol2) values (default, null); - -select * from anothertab; - -alter table anothertab alter column atcol2 type text - using case when atcol2 is true then 'IT WAS TRUE' - when atcol2 is false then 'IT WAS FALSE' - else 'IT WAS NULL!' end; - -select * from anothertab; -alter table anothertab alter column atcol1 type boolean - using case when atcol1 % 2 = 0 then true else false end; -- fails -alter table anothertab alter column atcol1 drop default; -alter table anothertab alter column atcol1 type boolean - using case when atcol1 % 2 = 0 then true else false end; -- fails -alter table anothertab drop constraint anothertab_chk; -alter table anothertab drop constraint anothertab_chk; -- fails -alter table anothertab drop constraint IF EXISTS anothertab_chk; -- succeeds - -alter table anothertab alter column atcol1 type boolean - using case when atcol1 % 2 = 0 then true else false end; - -select * from anothertab; - -drop table anothertab; - --- Test index handling in alter table column type (cf. bugs #15835, #15865) -create table anothertab(f1 int primary key, f2 int unique, - f3 int, f4 int, f5 int); -alter table anothertab - add exclude using btree (f3 with =); -alter table anothertab - add exclude using btree (f4 with =) where (f4 is not null); -alter table anothertab - add exclude using btree (f4 with =) where (f5 > 0); -alter table anothertab - add unique(f1,f4); -create index on anothertab(f2,f3); -create unique index on anothertab(f4); - -\d anothertab -alter table anothertab alter column f1 type bigint; -alter table anothertab - alter column f2 type bigint, - alter column f3 type bigint, - alter column f4 type bigint; -alter table anothertab alter column f5 type bigint; -\d anothertab - -drop table anothertab; - --- test that USING expressions are parsed before column alter type / drop steps -create table another (f1 int, f2 text, f3 text); - -insert into another values(1, 'one', 'uno'); -insert into another values(2, 'two', 'due'); -insert into another values(3, 'three', 'tre'); - -select * from another; - -alter table another - alter f1 type text using f2 || ' and ' || f3 || ' more', - alter f2 type bigint using f1 * 10, - drop column f3; - -select * from another; - -drop table another; - --- Create an index that skips WAL, then perform a SET DATA TYPE that skips --- rewriting the index. -begin; -create table skip_wal_skip_rewrite_index (c varchar(10) primary key); -alter table skip_wal_skip_rewrite_index alter c type varchar(20); -commit; - --- We disallow changing table's row type if it's used for storage -create table at_tab1 (a int, b text); -create table at_tab2 (x int, y at_tab1); -alter table at_tab1 alter column b type varchar; -- fails -drop table at_tab2; --- Use of row type in an expression is defended differently -create table at_tab2 (x int, y text, check((x,y)::at_tab1 = (1,'42')::at_tab1)); -alter table at_tab1 alter column b type varchar; -- allowed, but ... -insert into at_tab2 values(1,'42'); -- ... this will fail -drop table at_tab1, at_tab2; --- Check it for a partitioned table, too -create table at_tab1 (a int, b text) partition by list(a); -create table at_tab2 (x int, y at_tab1); -alter table at_tab1 alter column b type varchar; -- fails -drop table at_tab1, at_tab2; - --- Alter column type that's part of a partitioned index -create table at_partitioned (a int, b text) partition by range (a); -create table at_part_1 partition of at_partitioned for values from (0) to (1000); -insert into at_partitioned values (512, '0.123'); -create table at_part_2 (b text, a int); -insert into at_part_2 values ('1.234', 1024); -create index on at_partitioned (b); -create index on at_partitioned (a); -\d at_part_1 -\d at_part_2 -alter table at_partitioned attach partition at_part_2 for values from (1000) to (2000); -\d at_part_2 -alter table at_partitioned alter column b type numeric using b::numeric; -\d at_part_1 -\d at_part_2 -drop table at_partitioned; - --- Alter column type when no table rewrite is required --- Also check that comments are preserved -create table at_partitioned(id int, name varchar(64), unique (id, name)) - partition by hash(id); -comment on constraint at_partitioned_id_name_key on at_partitioned is 'parent constraint'; -comment on index at_partitioned_id_name_key is 'parent index'; -create table at_partitioned_0 partition of at_partitioned - for values with (modulus 2, remainder 0); -comment on constraint at_partitioned_0_id_name_key on at_partitioned_0 is 'child 0 constraint'; -comment on index at_partitioned_0_id_name_key is 'child 0 index'; -create table at_partitioned_1 partition of at_partitioned - for values with (modulus 2, remainder 1); -comment on constraint at_partitioned_1_id_name_key on at_partitioned_1 is 'child 1 constraint'; -comment on index at_partitioned_1_id_name_key is 'child 1 index'; -insert into at_partitioned values(1, 'foo'); -insert into at_partitioned values(3, 'bar'); - -create temp table old_oids as - select relname, oid as oldoid, relfilenode as oldfilenode - from pg_class where relname like 'at_partitioned%'; - -select relname, - c.oid = oldoid as orig_oid, - case relfilenode - when 0 then 'none' - when c.oid then 'own' - when oldfilenode then 'orig' - else 'OTHER' - end as storage, - obj_description(c.oid, 'pg_class') as desc - from pg_class c left join old_oids using (relname) - where relname like 'at_partitioned%' - order by relname; - -select conname, obj_description(oid, 'pg_constraint') as desc - from pg_constraint where conname like 'at_partitioned%' - order by conname; - -alter table at_partitioned alter column name type varchar(127); - --- Note: these tests currently show the wrong behavior for comments :-( - -select relname, - c.oid = oldoid as orig_oid, - case relfilenode - when 0 then 'none' - when c.oid then 'own' - when oldfilenode then 'orig' - else 'OTHER' - end as storage, - obj_description(c.oid, 'pg_class') as desc - from pg_class c left join old_oids using (relname) - where relname like 'at_partitioned%' - order by relname; - -select conname, obj_description(oid, 'pg_constraint') as desc - from pg_constraint where conname like 'at_partitioned%' - order by conname; - --- Don't remove this DROP, it exposes bug #15672 -drop table at_partitioned; - --- disallow recursive containment of row types -create temp table recur1 (f1 int); -alter table recur1 add column f2 recur1; -- fails -alter table recur1 add column f2 recur1[]; -- fails -create domain array_of_recur1 as recur1[]; -alter table recur1 add column f2 array_of_recur1; -- fails -create temp table recur2 (f1 int, f2 recur1); -alter table recur1 add column f2 recur2; -- fails -alter table recur1 add column f2 int; -alter table recur1 alter column f2 type recur2; -- fails - --- SET STORAGE may need to add a TOAST table -create table test_storage (a text); -alter table test_storage alter a set storage plain; -alter table test_storage add b int default 0; -- rewrite table to remove its TOAST table -alter table test_storage alter a set storage extended; -- re-add TOAST table - -select reltoastrelid <> 0 as has_toast_table -from pg_class -where oid = 'test_storage'::regclass; - --- test that SET STORAGE propagates to index correctly -create index test_storage_idx on test_storage (b, a); -alter table test_storage alter column a set storage external; -\d+ test_storage -\d+ test_storage_idx - --- ALTER COLUMN TYPE with a check constraint and a child table (bug #13779) -CREATE TABLE test_inh_check (a float check (a > 10.2), b float); -CREATE TABLE test_inh_check_child() INHERITS(test_inh_check); -\d test_inh_check -\d test_inh_check_child -select relname, conname, coninhcount, conislocal, connoinherit - from pg_constraint c, pg_class r - where relname like 'test_inh_check%' and c.conrelid = r.oid - order by 1, 2; -ALTER TABLE test_inh_check ALTER COLUMN a TYPE numeric; -\d test_inh_check -\d test_inh_check_child -select relname, conname, coninhcount, conislocal, connoinherit - from pg_constraint c, pg_class r - where relname like 'test_inh_check%' and c.conrelid = r.oid - order by 1, 2; --- also try noinherit, local, and local+inherited cases -ALTER TABLE test_inh_check ADD CONSTRAINT bnoinherit CHECK (b > 100) NO INHERIT; -ALTER TABLE test_inh_check_child ADD CONSTRAINT blocal CHECK (b < 1000); -ALTER TABLE test_inh_check_child ADD CONSTRAINT bmerged CHECK (b > 1); -ALTER TABLE test_inh_check ADD CONSTRAINT bmerged CHECK (b > 1); -\d test_inh_check -\d test_inh_check_child -select relname, conname, coninhcount, conislocal, connoinherit - from pg_constraint c, pg_class r - where relname like 'test_inh_check%' and c.conrelid = r.oid - order by 1, 2; -ALTER TABLE test_inh_check ALTER COLUMN b TYPE numeric; -\d test_inh_check -\d test_inh_check_child -select relname, conname, coninhcount, conislocal, connoinherit - from pg_constraint c, pg_class r - where relname like 'test_inh_check%' and c.conrelid = r.oid - order by 1, 2; - --- ALTER COLUMN TYPE with different schema in children --- Bug at https://postgr.es/m/20170102225618.GA10071@telsasoft.com -CREATE TABLE test_type_diff (f1 int); -CREATE TABLE test_type_diff_c (extra smallint) INHERITS (test_type_diff); -ALTER TABLE test_type_diff ADD COLUMN f2 int; -INSERT INTO test_type_diff_c VALUES (1, 2, 3); -ALTER TABLE test_type_diff ALTER COLUMN f2 TYPE bigint USING f2::bigint; - -CREATE TABLE test_type_diff2 (int_two int2, int_four int4, int_eight int8); -CREATE TABLE test_type_diff2_c1 (int_four int4, int_eight int8, int_two int2); -CREATE TABLE test_type_diff2_c2 (int_eight int8, int_two int2, int_four int4); -CREATE TABLE test_type_diff2_c3 (int_two int2, int_four int4, int_eight int8); -ALTER TABLE test_type_diff2_c1 INHERIT test_type_diff2; -ALTER TABLE test_type_diff2_c2 INHERIT test_type_diff2; -ALTER TABLE test_type_diff2_c3 INHERIT test_type_diff2; -INSERT INTO test_type_diff2_c1 VALUES (1, 2, 3); -INSERT INTO test_type_diff2_c2 VALUES (4, 5, 6); -INSERT INTO test_type_diff2_c3 VALUES (7, 8, 9); -ALTER TABLE test_type_diff2 ALTER COLUMN int_four TYPE int8 USING int_four::int8; --- whole-row references are disallowed -ALTER TABLE test_type_diff2 ALTER COLUMN int_four TYPE int4 USING (pg_column_size(test_type_diff2)); - --- check for rollback of ANALYZE corrupting table property flags (bug #11638) -CREATE TABLE check_fk_presence_1 (id int PRIMARY KEY, t text); -CREATE TABLE check_fk_presence_2 (id int REFERENCES check_fk_presence_1, t text); -BEGIN; -ALTER TABLE check_fk_presence_2 DROP CONSTRAINT check_fk_presence_2_id_fkey; -ANALYZE check_fk_presence_2; -ROLLBACK; -\d check_fk_presence_2 -DROP TABLE check_fk_presence_1, check_fk_presence_2; - --- check column addition within a view (bug #14876) -create table at_base_table(id int, stuff text); -insert into at_base_table values (23, 'skidoo'); -create view at_view_1 as select * from at_base_table bt; -create view at_view_2 as select *, to_json(v1) as j from at_view_1 v1; -\d+ at_view_1 -\d+ at_view_2 -explain (verbose, costs off) select * from at_view_2; -select * from at_view_2; - -create or replace view at_view_1 as select *, 2+2 as more from at_base_table bt; -\d+ at_view_1 -\d+ at_view_2 -explain (verbose, costs off) select * from at_view_2; -select * from at_view_2; - -drop view at_view_2; -drop view at_view_1; -drop table at_base_table; - --- check adding a column not iself requiring a rewrite, together with --- a column requiring a default (bug #16038) - --- ensure that rewrites aren't silently optimized away, removing the --- value of the test -CREATE FUNCTION check_ddl_rewrite(p_tablename regclass, p_ddl text) -RETURNS boolean -LANGUAGE plpgsql AS $$ -DECLARE - v_relfilenode oid; -BEGIN - v_relfilenode := relfilenode FROM pg_class WHERE oid = p_tablename; - - EXECUTE p_ddl; - - RETURN v_relfilenode <> (SELECT relfilenode FROM pg_class WHERE oid = p_tablename); -END; -$$; - -CREATE TABLE rewrite_test(col text); -INSERT INTO rewrite_test VALUES ('something'); -INSERT INTO rewrite_test VALUES (NULL); - --- empty[12] don't need rewrite, but notempty[12]_rewrite will force one -SELECT check_ddl_rewrite('rewrite_test', $$ - ALTER TABLE rewrite_test - ADD COLUMN empty1 text, - ADD COLUMN notempty1_rewrite serial; -$$); -SELECT check_ddl_rewrite('rewrite_test', $$ - ALTER TABLE rewrite_test - ADD COLUMN notempty2_rewrite serial, - ADD COLUMN empty2 text; -$$); --- also check that fast defaults cause no problem, first without rewrite -SELECT check_ddl_rewrite('rewrite_test', $$ - ALTER TABLE rewrite_test - ADD COLUMN empty3 text, - ADD COLUMN notempty3_norewrite int default 42; -$$); -SELECT check_ddl_rewrite('rewrite_test', $$ - ALTER TABLE rewrite_test - ADD COLUMN notempty4_norewrite int default 42, - ADD COLUMN empty4 text; -$$); --- then with rewrite -SELECT check_ddl_rewrite('rewrite_test', $$ - ALTER TABLE rewrite_test - ADD COLUMN empty5 text, - ADD COLUMN notempty5_norewrite int default 42, - ADD COLUMN notempty5_rewrite serial; -$$); -SELECT check_ddl_rewrite('rewrite_test', $$ - ALTER TABLE rewrite_test - ADD COLUMN notempty6_rewrite serial, - ADD COLUMN empty6 text, - ADD COLUMN notempty6_norewrite int default 42; -$$); - --- cleanup -DROP FUNCTION check_ddl_rewrite(regclass, text); -DROP TABLE rewrite_test; - --- --- lock levels --- -drop type lockmodes; -create type lockmodes as enum ( - 'SIReadLock' -,'AccessShareLock' -,'RowShareLock' -,'RowExclusiveLock' -,'ShareUpdateExclusiveLock' -,'ShareLock' -,'ShareRowExclusiveLock' -,'ExclusiveLock' -,'AccessExclusiveLock' -); - -drop view my_locks; -create or replace view my_locks as -select case when c.relname like 'pg_toast%' then 'pg_toast' else c.relname end, max(mode::lockmodes) as max_lockmode -from pg_locks l join pg_class c on l.relation = c.oid -where virtualtransaction = ( - select virtualtransaction - from pg_locks - where transactionid = pg_current_xact_id()::xid) -and locktype = 'relation' -and relnamespace != (select oid from pg_namespace where nspname = 'pg_catalog') -and c.relname != 'my_locks' -group by c.relname; - -create table alterlock (f1 int primary key, f2 text); -insert into alterlock values (1, 'foo'); -create table alterlock2 (f3 int primary key, f1 int); -insert into alterlock2 values (1, 1); - -begin; alter table alterlock alter column f2 set statistics 150; -select * from my_locks order by 1; -rollback; - -begin; alter table alterlock cluster on alterlock_pkey; -select * from my_locks order by 1; -commit; - -begin; alter table alterlock set without cluster; -select * from my_locks order by 1; -commit; - -begin; alter table alterlock set (fillfactor = 100); -select * from my_locks order by 1; -commit; - -begin; alter table alterlock reset (fillfactor); -select * from my_locks order by 1; -commit; - -begin; alter table alterlock set (toast.autovacuum_enabled = off); -select * from my_locks order by 1; -commit; - -begin; alter table alterlock set (autovacuum_enabled = off); -select * from my_locks order by 1; -commit; - -begin; alter table alterlock alter column f2 set (n_distinct = 1); -select * from my_locks order by 1; -rollback; - --- test that mixing options with different lock levels works as expected -begin; alter table alterlock set (autovacuum_enabled = off, fillfactor = 80); -select * from my_locks order by 1; -commit; - -begin; alter table alterlock alter column f2 set storage extended; -select * from my_locks order by 1; -rollback; - -begin; alter table alterlock alter column f2 set default 'x'; -select * from my_locks order by 1; -rollback; - -begin; -create trigger ttdummy - before delete or update on alterlock - for each row - execute procedure - ttdummy (1, 1); -select * from my_locks order by 1; -rollback; - -begin; -select * from my_locks order by 1; -alter table alterlock2 add foreign key (f1) references alterlock (f1); -select * from my_locks order by 1; -rollback; - -begin; -alter table alterlock2 -add constraint alterlock2nv foreign key (f1) references alterlock (f1) NOT VALID; -select * from my_locks order by 1; -commit; -begin; -alter table alterlock2 validate constraint alterlock2nv; -select * from my_locks order by 1; -rollback; - -create or replace view my_locks as -select case when c.relname like 'pg_toast%' then 'pg_toast' else c.relname end, max(mode::lockmodes) as max_lockmode -from pg_locks l join pg_class c on l.relation = c.oid -where virtualtransaction = ( - select virtualtransaction - from pg_locks - where transactionid = pg_current_xact_id()::xid) -and locktype = 'relation' -and relnamespace != (select oid from pg_namespace where nspname = 'pg_catalog') -and c.relname = 'my_locks' -group by c.relname; - --- raise exception -alter table my_locks set (autovacuum_enabled = false); -alter view my_locks set (autovacuum_enabled = false); -alter table my_locks reset (autovacuum_enabled); -alter view my_locks reset (autovacuum_enabled); - -begin; -alter view my_locks set (security_barrier=off); -select * from my_locks order by 1; -alter view my_locks reset (security_barrier); -rollback; - --- this test intentionally applies the ALTER TABLE command against a view, but --- uses a view option so we expect this to succeed. This form of SQL is --- accepted for historical reasons, as shown in the docs for ALTER VIEW -begin; -alter table my_locks set (security_barrier=off); -select * from my_locks order by 1; -alter table my_locks reset (security_barrier); -rollback; - --- cleanup -drop table alterlock2; -drop table alterlock; -drop view my_locks; -drop type lockmodes; - --- --- alter function --- -create function test_strict(text) returns text as - 'select coalesce($1, ''got passed a null'');' - language sql returns null on null input; -select test_strict(NULL); -alter function test_strict(text) called on null input; -select test_strict(NULL); - -create function non_strict(text) returns text as - 'select coalesce($1, ''got passed a null'');' - language sql called on null input; -select non_strict(NULL); -alter function non_strict(text) returns null on null input; -select non_strict(NULL); - --- --- alter object set schema --- - -create schema alter1; -create schema alter2; - -create table alter1.t1(f1 serial primary key, f2 int check (f2 > 0)); - -create view alter1.v1 as select * from alter1.t1; - -create function alter1.plus1(int) returns int as 'select $1+1' language sql; - -create domain alter1.posint integer check (value > 0); - -create type alter1.ctype as (f1 int, f2 text); - -create function alter1.same(alter1.ctype, alter1.ctype) returns boolean language sql -as 'select $1.f1 is not distinct from $2.f1 and $1.f2 is not distinct from $2.f2'; - -create operator alter1.=(procedure = alter1.same, leftarg = alter1.ctype, rightarg = alter1.ctype); - -create operator class alter1.ctype_hash_ops default for type alter1.ctype using hash as - operator 1 alter1.=(alter1.ctype, alter1.ctype); - -create conversion alter1.latin1_to_utf8 for 'latin1' to 'utf8' from iso8859_1_to_utf8; - -create text search parser alter1.prs(start = prsd_start, gettoken = prsd_nexttoken, end = prsd_end, lextypes = prsd_lextype); -create text search configuration alter1.cfg(parser = alter1.prs); -create text search template alter1.tmpl(init = dsimple_init, lexize = dsimple_lexize); -create text search dictionary alter1.dict(template = alter1.tmpl); - -insert into alter1.t1(f2) values(11); -insert into alter1.t1(f2) values(12); - -alter table alter1.t1 set schema alter1; -- no-op, same schema -alter table alter1.t1 set schema alter2; -alter table alter1.v1 set schema alter2; -alter function alter1.plus1(int) set schema alter2; -alter domain alter1.posint set schema alter2; -alter operator class alter1.ctype_hash_ops using hash set schema alter2; -alter operator family alter1.ctype_hash_ops using hash set schema alter2; -alter operator alter1.=(alter1.ctype, alter1.ctype) set schema alter2; -alter function alter1.same(alter1.ctype, alter1.ctype) set schema alter2; -alter type alter1.ctype set schema alter1; -- no-op, same schema -alter type alter1.ctype set schema alter2; -alter conversion alter1.latin1_to_utf8 set schema alter2; -alter text search parser alter1.prs set schema alter2; -alter text search configuration alter1.cfg set schema alter2; -alter text search template alter1.tmpl set schema alter2; -alter text search dictionary alter1.dict set schema alter2; - --- this should succeed because nothing is left in alter1 -drop schema alter1; - -insert into alter2.t1(f2) values(13); -insert into alter2.t1(f2) values(14); - -select * from alter2.t1; - -select * from alter2.v1; - -select alter2.plus1(41); - --- clean up -drop schema alter2 cascade; - --- --- composite types --- - -CREATE TYPE test_type AS (a int); -\d test_type - -ALTER TYPE nosuchtype ADD ATTRIBUTE b text; -- fails - -ALTER TYPE test_type ADD ATTRIBUTE b text; -\d test_type - -ALTER TYPE test_type ADD ATTRIBUTE b text; -- fails - -ALTER TYPE test_type ALTER ATTRIBUTE b SET DATA TYPE varchar; -\d test_type - -ALTER TYPE test_type ALTER ATTRIBUTE b SET DATA TYPE integer; -\d test_type - -ALTER TYPE test_type DROP ATTRIBUTE b; -\d test_type - -ALTER TYPE test_type DROP ATTRIBUTE c; -- fails - -ALTER TYPE test_type DROP ATTRIBUTE IF EXISTS c; - -ALTER TYPE test_type DROP ATTRIBUTE a, ADD ATTRIBUTE d boolean; -\d test_type - -ALTER TYPE test_type RENAME ATTRIBUTE a TO aa; -ALTER TYPE test_type RENAME ATTRIBUTE d TO dd; -\d test_type - -DROP TYPE test_type; - -CREATE TYPE test_type1 AS (a int, b text); -CREATE TABLE test_tbl1 (x int, y test_type1); -ALTER TYPE test_type1 ALTER ATTRIBUTE b TYPE varchar; -- fails - -CREATE TYPE test_type2 AS (a int, b text); -CREATE TABLE test_tbl2 OF test_type2; -CREATE TABLE test_tbl2_subclass () INHERITS (test_tbl2); -\d test_type2 -\d test_tbl2 - -ALTER TYPE test_type2 ADD ATTRIBUTE c text; -- fails -ALTER TYPE test_type2 ADD ATTRIBUTE c text CASCADE; -\d test_type2 -\d test_tbl2 - -ALTER TYPE test_type2 ALTER ATTRIBUTE b TYPE varchar; -- fails -ALTER TYPE test_type2 ALTER ATTRIBUTE b TYPE varchar CASCADE; -\d test_type2 -\d test_tbl2 - -ALTER TYPE test_type2 DROP ATTRIBUTE b; -- fails -ALTER TYPE test_type2 DROP ATTRIBUTE b CASCADE; -\d test_type2 -\d test_tbl2 - -ALTER TYPE test_type2 RENAME ATTRIBUTE a TO aa; -- fails -ALTER TYPE test_type2 RENAME ATTRIBUTE a TO aa CASCADE; -\d test_type2 -\d test_tbl2 -\d test_tbl2_subclass - -DROP TABLE test_tbl2_subclass; - -CREATE TYPE test_typex AS (a int, b text); -CREATE TABLE test_tblx (x int, y test_typex check ((y).a > 0)); -ALTER TYPE test_typex DROP ATTRIBUTE a; -- fails -ALTER TYPE test_typex DROP ATTRIBUTE a CASCADE; -\d test_tblx -DROP TABLE test_tblx; -DROP TYPE test_typex; - --- This test isn't that interesting on its own, but the purpose is to leave --- behind a table to test pg_upgrade with. The table has a composite type --- column in it, and the composite type has a dropped attribute. -CREATE TYPE test_type3 AS (a int); -CREATE TABLE test_tbl3 (c) AS SELECT '(1)'::test_type3; -ALTER TYPE test_type3 DROP ATTRIBUTE a, ADD ATTRIBUTE b int; - -CREATE TYPE test_type_empty AS (); -DROP TYPE test_type_empty; - --- --- typed tables: OF / NOT OF --- - -CREATE TYPE tt_t0 AS (z inet, x int, y numeric(8,2)); -ALTER TYPE tt_t0 DROP ATTRIBUTE z; -CREATE TABLE tt0 (x int NOT NULL, y numeric(8,2)); -- OK -CREATE TABLE tt1 (x int, y bigint); -- wrong base type -CREATE TABLE tt2 (x int, y numeric(9,2)); -- wrong typmod -CREATE TABLE tt3 (y numeric(8,2), x int); -- wrong column order -CREATE TABLE tt4 (x int); -- too few columns -CREATE TABLE tt5 (x int, y numeric(8,2), z int); -- too few columns -CREATE TABLE tt6 () INHERITS (tt0); -- can't have a parent -CREATE TABLE tt7 (x int, q text, y numeric(8,2)); -ALTER TABLE tt7 DROP q; -- OK - -ALTER TABLE tt0 OF tt_t0; -ALTER TABLE tt1 OF tt_t0; -ALTER TABLE tt2 OF tt_t0; -ALTER TABLE tt3 OF tt_t0; -ALTER TABLE tt4 OF tt_t0; -ALTER TABLE tt5 OF tt_t0; -ALTER TABLE tt6 OF tt_t0; -ALTER TABLE tt7 OF tt_t0; - -CREATE TYPE tt_t1 AS (x int, y numeric(8,2)); -ALTER TABLE tt7 OF tt_t1; -- reassign an already-typed table -ALTER TABLE tt7 NOT OF; -\d tt7 - --- make sure we can drop a constraint on the parent but it remains on the child -CREATE TABLE test_drop_constr_parent (c text CHECK (c IS NOT NULL)); -CREATE TABLE test_drop_constr_child () INHERITS (test_drop_constr_parent); -ALTER TABLE ONLY test_drop_constr_parent DROP CONSTRAINT "test_drop_constr_parent_c_check"; --- should fail -INSERT INTO test_drop_constr_child (c) VALUES (NULL); -DROP TABLE test_drop_constr_parent CASCADE; - --- --- IF EXISTS test --- -ALTER TABLE IF EXISTS tt8 ADD COLUMN f int; -ALTER TABLE IF EXISTS tt8 ADD CONSTRAINT xxx PRIMARY KEY(f); -ALTER TABLE IF EXISTS tt8 ADD CHECK (f BETWEEN 0 AND 10); -ALTER TABLE IF EXISTS tt8 ALTER COLUMN f SET DEFAULT 0; -ALTER TABLE IF EXISTS tt8 RENAME COLUMN f TO f1; -ALTER TABLE IF EXISTS tt8 SET SCHEMA alter2; - -CREATE TABLE tt8(a int); -CREATE SCHEMA alter2; - -ALTER TABLE IF EXISTS tt8 ADD COLUMN f int; -ALTER TABLE IF EXISTS tt8 ADD CONSTRAINT xxx PRIMARY KEY(f); -ALTER TABLE IF EXISTS tt8 ADD CHECK (f BETWEEN 0 AND 10); -ALTER TABLE IF EXISTS tt8 ALTER COLUMN f SET DEFAULT 0; -ALTER TABLE IF EXISTS tt8 RENAME COLUMN f TO f1; -ALTER TABLE IF EXISTS tt8 SET SCHEMA alter2; - -\d alter2.tt8 - -DROP TABLE alter2.tt8; -DROP SCHEMA alter2; - --- --- Check conflicts between index and CHECK constraint names --- -CREATE TABLE tt9(c integer); -ALTER TABLE tt9 ADD CHECK(c > 1); -ALTER TABLE tt9 ADD CHECK(c > 2); -- picks nonconflicting name -ALTER TABLE tt9 ADD CONSTRAINT foo CHECK(c > 3); -ALTER TABLE tt9 ADD CONSTRAINT foo CHECK(c > 4); -- fail, dup name -ALTER TABLE tt9 ADD UNIQUE(c); -ALTER TABLE tt9 ADD UNIQUE(c); -- picks nonconflicting name -ALTER TABLE tt9 ADD CONSTRAINT tt9_c_key UNIQUE(c); -- fail, dup name -ALTER TABLE tt9 ADD CONSTRAINT foo UNIQUE(c); -- fail, dup name -ALTER TABLE tt9 ADD CONSTRAINT tt9_c_key CHECK(c > 5); -- fail, dup name -ALTER TABLE tt9 ADD CONSTRAINT tt9_c_key2 CHECK(c > 6); -ALTER TABLE tt9 ADD UNIQUE(c); -- picks nonconflicting name -\d tt9 -DROP TABLE tt9; - - --- Check that comments on constraints and indexes are not lost at ALTER TABLE. -CREATE TABLE comment_test ( - id int, - positive_col int CHECK (positive_col > 0), - indexed_col int, - CONSTRAINT comment_test_pk PRIMARY KEY (id)); -CREATE INDEX comment_test_index ON comment_test(indexed_col); - -COMMENT ON COLUMN comment_test.id IS 'Column ''id'' on comment_test'; -COMMENT ON INDEX comment_test_index IS 'Simple index on comment_test'; -COMMENT ON CONSTRAINT comment_test_positive_col_check ON comment_test IS 'CHECK constraint on comment_test.positive_col'; -COMMENT ON CONSTRAINT comment_test_pk ON comment_test IS 'PRIMARY KEY constraint of comment_test'; -COMMENT ON INDEX comment_test_pk IS 'Index backing the PRIMARY KEY of comment_test'; - -SELECT col_description('comment_test'::regclass, 1) as comment; -SELECT indexrelid::regclass::text as index, obj_description(indexrelid, 'pg_class') as comment FROM pg_index where indrelid = 'comment_test'::regclass ORDER BY 1, 2; -SELECT conname as constraint, obj_description(oid, 'pg_constraint') as comment FROM pg_constraint where conrelid = 'comment_test'::regclass ORDER BY 1, 2; - --- Change the datatype of all the columns. ALTER TABLE is optimized to not --- rebuild an index if the new data type is binary compatible with the old --- one. Check do a dummy ALTER TABLE that doesn't change the datatype --- first, to test that no-op codepath, and another one that does. -ALTER TABLE comment_test ALTER COLUMN indexed_col SET DATA TYPE int; -ALTER TABLE comment_test ALTER COLUMN indexed_col SET DATA TYPE text; -ALTER TABLE comment_test ALTER COLUMN id SET DATA TYPE int; -ALTER TABLE comment_test ALTER COLUMN id SET DATA TYPE text; -ALTER TABLE comment_test ALTER COLUMN positive_col SET DATA TYPE int; -ALTER TABLE comment_test ALTER COLUMN positive_col SET DATA TYPE bigint; - --- Check that the comments are intact. -SELECT col_description('comment_test'::regclass, 1) as comment; -SELECT indexrelid::regclass::text as index, obj_description(indexrelid, 'pg_class') as comment FROM pg_index where indrelid = 'comment_test'::regclass ORDER BY 1, 2; -SELECT conname as constraint, obj_description(oid, 'pg_constraint') as comment FROM pg_constraint where conrelid = 'comment_test'::regclass ORDER BY 1, 2; - --- Check compatibility for foreign keys and comments. This is done --- separately as rebuilding the column type of the parent leads --- to an error and would reduce the test scope. -CREATE TABLE comment_test_child ( - id text CONSTRAINT comment_test_child_fk REFERENCES comment_test); -CREATE INDEX comment_test_child_fk ON comment_test_child(id); -COMMENT ON COLUMN comment_test_child.id IS 'Column ''id'' on comment_test_child'; -COMMENT ON INDEX comment_test_child_fk IS 'Index backing the FOREIGN KEY of comment_test_child'; -COMMENT ON CONSTRAINT comment_test_child_fk ON comment_test_child IS 'FOREIGN KEY constraint of comment_test_child'; - --- Change column type of parent -ALTER TABLE comment_test ALTER COLUMN id SET DATA TYPE text; -ALTER TABLE comment_test ALTER COLUMN id SET DATA TYPE int USING id::integer; - --- Comments should be intact -SELECT col_description('comment_test_child'::regclass, 1) as comment; -SELECT indexrelid::regclass::text as index, obj_description(indexrelid, 'pg_class') as comment FROM pg_index where indrelid = 'comment_test_child'::regclass ORDER BY 1, 2; -SELECT conname as constraint, obj_description(oid, 'pg_constraint') as comment FROM pg_constraint where conrelid = 'comment_test_child'::regclass ORDER BY 1, 2; - --- Check that we map relation oids to filenodes and back correctly. Only --- display bad mappings so the test output doesn't change all the time. A --- filenode function call can return NULL for a relation dropped concurrently --- with the call's surrounding query, so ignore a NULL mapped_oid for --- relations that no longer exist after all calls finish. -CREATE TEMP TABLE filenode_mapping AS -SELECT - oid, mapped_oid, reltablespace, relfilenode, relname -FROM pg_class, - pg_filenode_relation(reltablespace, pg_relation_filenode(oid)) AS mapped_oid -WHERE relkind IN ('r', 'i', 'S', 't', 'm') AND mapped_oid IS DISTINCT FROM oid; - -SELECT m.* FROM filenode_mapping m LEFT JOIN pg_class c ON c.oid = m.oid -WHERE c.oid IS NOT NULL OR m.mapped_oid IS NOT NULL; - --- Checks on creating and manipulation of user defined relations in --- pg_catalog. - -SHOW allow_system_table_mods; --- disallowed because of search_path issues with pg_dump -CREATE TABLE pg_catalog.new_system_table(); --- instead create in public first, move to catalog -CREATE TABLE new_system_table(id serial primary key, othercol text); -ALTER TABLE new_system_table SET SCHEMA pg_catalog; -ALTER TABLE new_system_table SET SCHEMA public; -ALTER TABLE new_system_table SET SCHEMA pg_catalog; --- will be ignored -- already there: -ALTER TABLE new_system_table SET SCHEMA pg_catalog; -ALTER TABLE new_system_table RENAME TO old_system_table; -CREATE INDEX old_system_table__othercol ON old_system_table (othercol); -INSERT INTO old_system_table(othercol) VALUES ('somedata'), ('otherdata'); -UPDATE old_system_table SET id = -id; -DELETE FROM old_system_table WHERE othercol = 'somedata'; -TRUNCATE old_system_table; -ALTER TABLE old_system_table DROP CONSTRAINT new_system_table_pkey; -ALTER TABLE old_system_table DROP COLUMN othercol; -DROP TABLE old_system_table; - --- set logged -CREATE UNLOGGED TABLE unlogged1(f1 SERIAL PRIMARY KEY, f2 TEXT); -- has sequence, toast --- check relpersistence of an unlogged table -SELECT relname, relkind, relpersistence FROM pg_class WHERE relname ~ '^unlogged1' -UNION ALL -SELECT r.relname || ' toast table', t.relkind, t.relpersistence FROM pg_class r JOIN pg_class t ON t.oid = r.reltoastrelid WHERE r.relname ~ '^unlogged1' -UNION ALL -SELECT r.relname || ' toast index', ri.relkind, ri.relpersistence FROM pg_class r join pg_class t ON t.oid = r.reltoastrelid JOIN pg_index i ON i.indrelid = t.oid JOIN pg_class ri ON ri.oid = i.indexrelid WHERE r.relname ~ '^unlogged1' -ORDER BY relname; -CREATE UNLOGGED TABLE unlogged2(f1 SERIAL PRIMARY KEY, f2 INTEGER REFERENCES unlogged1); -- foreign key -CREATE UNLOGGED TABLE unlogged3(f1 SERIAL PRIMARY KEY, f2 INTEGER REFERENCES unlogged3); -- self-referencing foreign key -ALTER TABLE unlogged3 SET LOGGED; -- skip self-referencing foreign key -ALTER TABLE unlogged2 SET LOGGED; -- fails because a foreign key to an unlogged table exists -ALTER TABLE unlogged1 SET LOGGED; --- check relpersistence of an unlogged table after changing to permanent -SELECT relname, relkind, relpersistence FROM pg_class WHERE relname ~ '^unlogged1' -UNION ALL -SELECT r.relname || ' toast table', t.relkind, t.relpersistence FROM pg_class r JOIN pg_class t ON t.oid = r.reltoastrelid WHERE r.relname ~ '^unlogged1' -UNION ALL -SELECT r.relname || ' toast index', ri.relkind, ri.relpersistence FROM pg_class r join pg_class t ON t.oid = r.reltoastrelid JOIN pg_index i ON i.indrelid = t.oid JOIN pg_class ri ON ri.oid = i.indexrelid WHERE r.relname ~ '^unlogged1' -ORDER BY relname; -ALTER TABLE unlogged1 SET LOGGED; -- silently do nothing -DROP TABLE unlogged3; -DROP TABLE unlogged2; -DROP TABLE unlogged1; - --- set unlogged -CREATE TABLE logged1(f1 SERIAL PRIMARY KEY, f2 TEXT); -- has sequence, toast --- check relpersistence of a permanent table -SELECT relname, relkind, relpersistence FROM pg_class WHERE relname ~ '^logged1' -UNION ALL -SELECT r.relname || ' toast table', t.relkind, t.relpersistence FROM pg_class r JOIN pg_class t ON t.oid = r.reltoastrelid WHERE r.relname ~ '^logged1' -UNION ALL -SELECT r.relname ||' toast index', ri.relkind, ri.relpersistence FROM pg_class r join pg_class t ON t.oid = r.reltoastrelid JOIN pg_index i ON i.indrelid = t.oid JOIN pg_class ri ON ri.oid = i.indexrelid WHERE r.relname ~ '^logged1' -ORDER BY relname; -CREATE TABLE logged2(f1 SERIAL PRIMARY KEY, f2 INTEGER REFERENCES logged1); -- foreign key -CREATE TABLE logged3(f1 SERIAL PRIMARY KEY, f2 INTEGER REFERENCES logged3); -- self-referencing foreign key -ALTER TABLE logged1 SET UNLOGGED; -- fails because a foreign key from a permanent table exists -ALTER TABLE logged3 SET UNLOGGED; -- skip self-referencing foreign key -ALTER TABLE logged2 SET UNLOGGED; -ALTER TABLE logged1 SET UNLOGGED; --- check relpersistence of a permanent table after changing to unlogged -SELECT relname, relkind, relpersistence FROM pg_class WHERE relname ~ '^logged1' -UNION ALL -SELECT r.relname || ' toast table', t.relkind, t.relpersistence FROM pg_class r JOIN pg_class t ON t.oid = r.reltoastrelid WHERE r.relname ~ '^logged1' -UNION ALL -SELECT r.relname || ' toast index', ri.relkind, ri.relpersistence FROM pg_class r join pg_class t ON t.oid = r.reltoastrelid JOIN pg_index i ON i.indrelid = t.oid JOIN pg_class ri ON ri.oid = i.indexrelid WHERE r.relname ~ '^logged1' -ORDER BY relname; -ALTER TABLE logged1 SET UNLOGGED; -- silently do nothing -DROP TABLE logged3; -DROP TABLE logged2; -DROP TABLE logged1; - --- test ADD COLUMN IF NOT EXISTS -CREATE TABLE test_add_column(c1 integer); -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN c2 integer; -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN c2 integer; -- fail because c2 already exists -ALTER TABLE ONLY test_add_column - ADD COLUMN c2 integer; -- fail because c2 already exists -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c2 integer; -- skipping because c2 already exists -ALTER TABLE ONLY test_add_column - ADD COLUMN IF NOT EXISTS c2 integer; -- skipping because c2 already exists -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN c2 integer, -- fail because c2 already exists - ADD COLUMN c3 integer primary key; -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c2 integer, -- skipping because c2 already exists - ADD COLUMN c3 integer primary key; -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c2 integer, -- skipping because c2 already exists - ADD COLUMN IF NOT EXISTS c3 integer primary key; -- skipping because c3 already exists -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c2 integer, -- skipping because c2 already exists - ADD COLUMN IF NOT EXISTS c3 integer, -- skipping because c3 already exists - ADD COLUMN c4 integer REFERENCES test_add_column; -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c4 integer REFERENCES test_add_column; -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c5 SERIAL CHECK (c5 > 8); -\d test_add_column -ALTER TABLE test_add_column - ADD COLUMN IF NOT EXISTS c5 SERIAL CHECK (c5 > 10); -\d test_add_column* -DROP TABLE test_add_column; -\d test_add_column* - --- assorted cases with multiple ALTER TABLE steps -CREATE TABLE ataddindex(f1 INT); -INSERT INTO ataddindex VALUES (42), (43); -CREATE UNIQUE INDEX ataddindexi0 ON ataddindex(f1); -ALTER TABLE ataddindex - ADD PRIMARY KEY USING INDEX ataddindexi0, - ALTER f1 TYPE BIGINT; -\d ataddindex -DROP TABLE ataddindex; - -CREATE TABLE ataddindex(f1 VARCHAR(10)); -INSERT INTO ataddindex(f1) VALUES ('foo'), ('a'); -ALTER TABLE ataddindex - ALTER f1 SET DATA TYPE TEXT, - ADD EXCLUDE ((f1 LIKE 'a') WITH =); -\d ataddindex -DROP TABLE ataddindex; - -CREATE TABLE ataddindex(id int, ref_id int); -ALTER TABLE ataddindex - ADD PRIMARY KEY (id), - ADD FOREIGN KEY (ref_id) REFERENCES ataddindex; -\d ataddindex -DROP TABLE ataddindex; - -CREATE TABLE ataddindex(id int, ref_id int); -ALTER TABLE ataddindex - ADD UNIQUE (id), - ADD FOREIGN KEY (ref_id) REFERENCES ataddindex (id); -\d ataddindex -DROP TABLE ataddindex; - --- unsupported constraint types for partitioned tables -CREATE TABLE partitioned ( - a int, - b int -) PARTITION BY RANGE (a, (a+b+1)); -ALTER TABLE partitioned ADD EXCLUDE USING gist (a WITH &&); - --- cannot drop column that is part of the partition key -ALTER TABLE partitioned DROP COLUMN a; -ALTER TABLE partitioned ALTER COLUMN a TYPE char(5); -ALTER TABLE partitioned DROP COLUMN b; -ALTER TABLE partitioned ALTER COLUMN b TYPE char(5); - --- partitioned table cannot participate in regular inheritance -CREATE TABLE nonpartitioned ( - a int, - b int -); -ALTER TABLE partitioned INHERIT nonpartitioned; -ALTER TABLE nonpartitioned INHERIT partitioned; - --- cannot add NO INHERIT constraint to partitioned tables -ALTER TABLE partitioned ADD CONSTRAINT chk_a CHECK (a > 0) NO INHERIT; - -DROP TABLE partitioned, nonpartitioned; - --- --- ATTACH PARTITION --- - --- check that target table is partitioned -CREATE TABLE unparted ( - a int -); -CREATE TABLE fail_part (like unparted); -ALTER TABLE unparted ATTACH PARTITION fail_part FOR VALUES IN ('a'); -DROP TABLE unparted, fail_part; - --- check that partition bound is compatible -CREATE TABLE list_parted ( - a int NOT NULL, - b char(2) COLLATE "C", - CONSTRAINT check_a CHECK (a > 0) -) PARTITION BY LIST (a); -CREATE TABLE fail_part (LIKE list_parted); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES FROM (1) TO (10); -DROP TABLE fail_part; - --- check that the table being attached exists -ALTER TABLE list_parted ATTACH PARTITION nonexistent FOR VALUES IN (1); - --- check ownership of the source table -CREATE ROLE regress_test_me; -CREATE ROLE regress_test_not_me; -CREATE TABLE not_owned_by_me (LIKE list_parted); -ALTER TABLE not_owned_by_me OWNER TO regress_test_not_me; -SET SESSION AUTHORIZATION regress_test_me; -CREATE TABLE owned_by_me ( - a int -) PARTITION BY LIST (a); -ALTER TABLE owned_by_me ATTACH PARTITION not_owned_by_me FOR VALUES IN (1); -RESET SESSION AUTHORIZATION; -DROP TABLE owned_by_me, not_owned_by_me; -DROP ROLE regress_test_not_me; -DROP ROLE regress_test_me; - --- check that the table being attached is not part of regular inheritance -CREATE TABLE parent (LIKE list_parted); -CREATE TABLE child () INHERITS (parent); -ALTER TABLE list_parted ATTACH PARTITION child FOR VALUES IN (1); -ALTER TABLE list_parted ATTACH PARTITION parent FOR VALUES IN (1); -DROP TABLE parent CASCADE; - --- check any TEMP-ness -CREATE TEMP TABLE temp_parted (a int) PARTITION BY LIST (a); -CREATE TABLE perm_part (a int); -ALTER TABLE temp_parted ATTACH PARTITION perm_part FOR VALUES IN (1); -DROP TABLE temp_parted, perm_part; - --- check that the table being attached is not a typed table -CREATE TYPE mytype AS (a int); -CREATE TABLE fail_part OF mytype; -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -DROP TYPE mytype CASCADE; - --- check that the table being attached has only columns present in the parent -CREATE TABLE fail_part (like list_parted, c int); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -DROP TABLE fail_part; - --- check that the table being attached has every column of the parent -CREATE TABLE fail_part (a int NOT NULL); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -DROP TABLE fail_part; - --- check that columns match in type, collation and NOT NULL status -CREATE TABLE fail_part ( - b char(3), - a int NOT NULL -); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -ALTER TABLE fail_part ALTER b TYPE char (2) COLLATE "POSIX"; -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -DROP TABLE fail_part; - --- check that the table being attached has all constraints of the parent -CREATE TABLE fail_part ( - b char(2) COLLATE "C", - a int NOT NULL -); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); - --- check that the constraint matches in definition with parent's constraint -ALTER TABLE fail_part ADD CONSTRAINT check_a CHECK (a >= 0); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -DROP TABLE fail_part; - --- check the attributes and constraints after partition is attached -CREATE TABLE part_1 ( - a int NOT NULL, - b char(2) COLLATE "C", - CONSTRAINT check_a CHECK (a > 0) -); -ALTER TABLE list_parted ATTACH PARTITION part_1 FOR VALUES IN (1); --- attislocal and conislocal are always false for merged attributes and constraints respectively. -SELECT attislocal, attinhcount FROM pg_attribute WHERE attrelid = 'part_1'::regclass AND attnum > 0; -SELECT conislocal, coninhcount FROM pg_constraint WHERE conrelid = 'part_1'::regclass AND conname = 'check_a'; - --- check that the new partition won't overlap with an existing partition -CREATE TABLE fail_part (LIKE part_1 INCLUDING CONSTRAINTS); -ALTER TABLE list_parted ATTACH PARTITION fail_part FOR VALUES IN (1); -DROP TABLE fail_part; --- check that an existing table can be attached as a default partition -CREATE TABLE def_part (LIKE list_parted INCLUDING CONSTRAINTS); -ALTER TABLE list_parted ATTACH PARTITION def_part DEFAULT; --- check attaching default partition fails if a default partition already --- exists -CREATE TABLE fail_def_part (LIKE part_1 INCLUDING CONSTRAINTS); -ALTER TABLE list_parted ATTACH PARTITION fail_def_part DEFAULT; - --- check validation when attaching list partitions -CREATE TABLE list_parted2 ( - a int, - b char -) PARTITION BY LIST (a); - --- check that violating rows are correctly reported -CREATE TABLE part_2 (LIKE list_parted2); -INSERT INTO part_2 VALUES (3, 'a'); -ALTER TABLE list_parted2 ATTACH PARTITION part_2 FOR VALUES IN (2); - --- should be ok after deleting the bad row -DELETE FROM part_2; -ALTER TABLE list_parted2 ATTACH PARTITION part_2 FOR VALUES IN (2); - --- check partition cannot be attached if default has some row for its values -CREATE TABLE list_parted2_def PARTITION OF list_parted2 DEFAULT; -INSERT INTO list_parted2_def VALUES (11, 'z'); -CREATE TABLE part_3 (LIKE list_parted2); -ALTER TABLE list_parted2 ATTACH PARTITION part_3 FOR VALUES IN (11); --- should be ok after deleting the bad row -DELETE FROM list_parted2_def WHERE a = 11; -ALTER TABLE list_parted2 ATTACH PARTITION part_3 FOR VALUES IN (11); - --- adding constraints that describe the desired partition constraint --- (or more restrictive) will help skip the validation scan -CREATE TABLE part_3_4 ( - LIKE list_parted2, - CONSTRAINT check_a CHECK (a IN (3)) -); - --- however, if a list partition does not accept nulls, there should be --- an explicit NOT NULL constraint on the partition key column for the --- validation scan to be skipped; -ALTER TABLE list_parted2 ATTACH PARTITION part_3_4 FOR VALUES IN (3, 4); - --- adding a NOT NULL constraint will cause the scan to be skipped -ALTER TABLE list_parted2 DETACH PARTITION part_3_4; -ALTER TABLE part_3_4 ALTER a SET NOT NULL; -ALTER TABLE list_parted2 ATTACH PARTITION part_3_4 FOR VALUES IN (3, 4); - --- check if default partition scan skipped -ALTER TABLE list_parted2_def ADD CONSTRAINT check_a CHECK (a IN (5, 6)); -CREATE TABLE part_55_66 PARTITION OF list_parted2 FOR VALUES IN (55, 66); - --- check validation when attaching range partitions -CREATE TABLE range_parted ( - a int, - b int -) PARTITION BY RANGE (a, b); - --- check that violating rows are correctly reported -CREATE TABLE part1 ( - a int NOT NULL CHECK (a = 1), - b int NOT NULL CHECK (b >= 1 AND b <= 10) -); -INSERT INTO part1 VALUES (1, 10); --- Remember the TO bound is exclusive -ALTER TABLE range_parted ATTACH PARTITION part1 FOR VALUES FROM (1, 1) TO (1, 10); - --- should be ok after deleting the bad row -DELETE FROM part1; -ALTER TABLE range_parted ATTACH PARTITION part1 FOR VALUES FROM (1, 1) TO (1, 10); - --- adding constraints that describe the desired partition constraint --- (or more restrictive) will help skip the validation scan -CREATE TABLE part2 ( - a int NOT NULL CHECK (a = 1), - b int NOT NULL CHECK (b >= 10 AND b < 18) -); -ALTER TABLE range_parted ATTACH PARTITION part2 FOR VALUES FROM (1, 10) TO (1, 20); - --- Create default partition -CREATE TABLE partr_def1 PARTITION OF range_parted DEFAULT; - --- Only one default partition is allowed, hence, following should give error -CREATE TABLE partr_def2 (LIKE part1 INCLUDING CONSTRAINTS); -ALTER TABLE range_parted ATTACH PARTITION partr_def2 DEFAULT; - --- Overlapping partitions cannot be attached, hence, following should give error -INSERT INTO partr_def1 VALUES (2, 10); -CREATE TABLE part3 (LIKE range_parted); -ALTER TABLE range_parted ATTACH partition part3 FOR VALUES FROM (2, 10) TO (2, 20); - --- Attaching partitions should be successful when there are no overlapping rows -ALTER TABLE range_parted ATTACH partition part3 FOR VALUES FROM (3, 10) TO (3, 20); - --- check that leaf partitions are scanned when attaching a partitioned --- table -CREATE TABLE part_5 ( - LIKE list_parted2 -) PARTITION BY LIST (b); - --- check that violating rows are correctly reported -CREATE TABLE part_5_a PARTITION OF part_5 FOR VALUES IN ('a'); -INSERT INTO part_5_a (a, b) VALUES (6, 'a'); -ALTER TABLE list_parted2 ATTACH PARTITION part_5 FOR VALUES IN (5); - --- delete the faulting row and also add a constraint to skip the scan -DELETE FROM part_5_a WHERE a NOT IN (3); -ALTER TABLE part_5 ADD CONSTRAINT check_a CHECK (a IS NOT NULL AND a = 5); -ALTER TABLE list_parted2 ATTACH PARTITION part_5 FOR VALUES IN (5); -ALTER TABLE list_parted2 DETACH PARTITION part_5; -ALTER TABLE part_5 DROP CONSTRAINT check_a; - --- scan should again be skipped, even though NOT NULL is now a column property -ALTER TABLE part_5 ADD CONSTRAINT check_a CHECK (a IN (5)), ALTER a SET NOT NULL; -ALTER TABLE list_parted2 ATTACH PARTITION part_5 FOR VALUES IN (5); - --- Check the case where attnos of the partitioning columns in the table being --- attached differs from the parent. It should not affect the constraint- --- checking logic that allows to skip the scan. -CREATE TABLE part_6 ( - c int, - LIKE list_parted2, - CONSTRAINT check_a CHECK (a IS NOT NULL AND a = 6) -); -ALTER TABLE part_6 DROP c; -ALTER TABLE list_parted2 ATTACH PARTITION part_6 FOR VALUES IN (6); - --- Similar to above, but the table being attached is a partitioned table --- whose partition has still different attnos for the root partitioning --- columns. -CREATE TABLE part_7 ( - LIKE list_parted2, - CONSTRAINT check_a CHECK (a IS NOT NULL AND a = 7) -) PARTITION BY LIST (b); -CREATE TABLE part_7_a_null ( - c int, - d int, - e int, - LIKE list_parted2, -- 'a' will have attnum = 4 - CONSTRAINT check_b CHECK (b IS NULL OR b = 'a'), - CONSTRAINT check_a CHECK (a IS NOT NULL AND a = 7) -); -ALTER TABLE part_7_a_null DROP c, DROP d, DROP e; -ALTER TABLE part_7 ATTACH PARTITION part_7_a_null FOR VALUES IN ('a', null); -ALTER TABLE list_parted2 ATTACH PARTITION part_7 FOR VALUES IN (7); - --- Same example, but check this time that the constraint correctly detects --- violating rows -ALTER TABLE list_parted2 DETACH PARTITION part_7; -ALTER TABLE part_7 DROP CONSTRAINT check_a; -- thusly, scan won't be skipped -INSERT INTO part_7 (a, b) VALUES (8, null), (9, 'a'); -SELECT tableoid::regclass, a, b FROM part_7 order by a; -ALTER TABLE list_parted2 ATTACH PARTITION part_7 FOR VALUES IN (7); - --- check that leaf partitions of default partition are scanned when --- attaching a partitioned table. -ALTER TABLE part_5 DROP CONSTRAINT check_a; -CREATE TABLE part5_def PARTITION OF part_5 DEFAULT PARTITION BY LIST(a); -CREATE TABLE part5_def_p1 PARTITION OF part5_def FOR VALUES IN (5); -INSERT INTO part5_def_p1 VALUES (5, 'y'); -CREATE TABLE part5_p1 (LIKE part_5); -ALTER TABLE part_5 ATTACH PARTITION part5_p1 FOR VALUES IN ('y'); --- should be ok after deleting the bad row -DELETE FROM part5_def_p1 WHERE b = 'y'; -ALTER TABLE part_5 ATTACH PARTITION part5_p1 FOR VALUES IN ('y'); - --- check that the table being attached is not already a partition -ALTER TABLE list_parted2 ATTACH PARTITION part_2 FOR VALUES IN (2); - --- check that circular inheritance is not allowed -ALTER TABLE part_5 ATTACH PARTITION list_parted2 FOR VALUES IN ('b'); -ALTER TABLE list_parted2 ATTACH PARTITION list_parted2 FOR VALUES IN (0); - --- If a partitioned table being created or an existing table being attached --- as a partition does not have a constraint that would allow validation scan --- to be skipped, but an individual partition does, then the partition's --- validation scan is skipped. -CREATE TABLE quuux (a int, b text) PARTITION BY LIST (a); -CREATE TABLE quuux_default PARTITION OF quuux DEFAULT PARTITION BY LIST (b); -CREATE TABLE quuux_default1 PARTITION OF quuux_default ( - CONSTRAINT check_1 CHECK (a IS NOT NULL AND a = 1) -) FOR VALUES IN ('b'); -CREATE TABLE quuux1 (a int, b text); -ALTER TABLE quuux ATTACH PARTITION quuux1 FOR VALUES IN (1); -- validate! -CREATE TABLE quuux2 (a int, b text); -ALTER TABLE quuux ATTACH PARTITION quuux2 FOR VALUES IN (2); -- skip validation -DROP TABLE quuux1, quuux2; --- should validate for quuux1, but not for quuux2 -CREATE TABLE quuux1 PARTITION OF quuux FOR VALUES IN (1); -CREATE TABLE quuux2 PARTITION OF quuux FOR VALUES IN (2); -DROP TABLE quuux; - --- check validation when attaching hash partitions - --- Use hand-rolled hash functions and operator class to get predictable result --- on different machines. part_test_int4_ops is defined in insert.sql. - --- check that the new partition won't overlap with an existing partition -CREATE TABLE hash_parted ( - a int, - b int -) PARTITION BY HASH (a part_test_int4_ops); -CREATE TABLE hpart_1 PARTITION OF hash_parted FOR VALUES WITH (MODULUS 4, REMAINDER 0); -CREATE TABLE fail_part (LIKE hpart_1); -ALTER TABLE hash_parted ATTACH PARTITION fail_part FOR VALUES WITH (MODULUS 8, REMAINDER 4); -ALTER TABLE hash_parted ATTACH PARTITION fail_part FOR VALUES WITH (MODULUS 8, REMAINDER 0); -DROP TABLE fail_part; - --- check validation when attaching hash partitions - --- check that violating rows are correctly reported -CREATE TABLE hpart_2 (LIKE hash_parted); -INSERT INTO hpart_2 VALUES (3, 0); -ALTER TABLE hash_parted ATTACH PARTITION hpart_2 FOR VALUES WITH (MODULUS 4, REMAINDER 1); - --- should be ok after deleting the bad row -DELETE FROM hpart_2; -ALTER TABLE hash_parted ATTACH PARTITION hpart_2 FOR VALUES WITH (MODULUS 4, REMAINDER 1); - --- check that leaf partitions are scanned when attaching a partitioned --- table -CREATE TABLE hpart_5 ( - LIKE hash_parted -) PARTITION BY LIST (b); - --- check that violating rows are correctly reported -CREATE TABLE hpart_5_a PARTITION OF hpart_5 FOR VALUES IN ('1', '2', '3'); -INSERT INTO hpart_5_a (a, b) VALUES (7, 1); -ALTER TABLE hash_parted ATTACH PARTITION hpart_5 FOR VALUES WITH (MODULUS 4, REMAINDER 2); - --- should be ok after deleting the bad row -DELETE FROM hpart_5_a; -ALTER TABLE hash_parted ATTACH PARTITION hpart_5 FOR VALUES WITH (MODULUS 4, REMAINDER 2); - --- check that the table being attach is with valid modulus and remainder value -CREATE TABLE fail_part(LIKE hash_parted); -ALTER TABLE hash_parted ATTACH PARTITION fail_part FOR VALUES WITH (MODULUS 0, REMAINDER 1); -ALTER TABLE hash_parted ATTACH PARTITION fail_part FOR VALUES WITH (MODULUS 8, REMAINDER 8); -ALTER TABLE hash_parted ATTACH PARTITION fail_part FOR VALUES WITH (MODULUS 3, REMAINDER 2); -DROP TABLE fail_part; - --- --- DETACH PARTITION --- - --- check that the table is partitioned at all -CREATE TABLE regular_table (a int); -ALTER TABLE regular_table DETACH PARTITION any_name; -DROP TABLE regular_table; - --- check that the partition being detached exists at all -ALTER TABLE list_parted2 DETACH PARTITION part_4; -ALTER TABLE hash_parted DETACH PARTITION hpart_4; - --- check that the partition being detached is actually a partition of the parent -CREATE TABLE not_a_part (a int); -ALTER TABLE list_parted2 DETACH PARTITION not_a_part; -ALTER TABLE list_parted2 DETACH PARTITION part_1; - -ALTER TABLE hash_parted DETACH PARTITION not_a_part; -DROP TABLE not_a_part; - --- check that, after being detached, attinhcount/coninhcount is dropped to 0 and --- attislocal/conislocal is set to true -ALTER TABLE list_parted2 DETACH PARTITION part_3_4; -SELECT attinhcount, attislocal FROM pg_attribute WHERE attrelid = 'part_3_4'::regclass AND attnum > 0; -SELECT coninhcount, conislocal FROM pg_constraint WHERE conrelid = 'part_3_4'::regclass AND conname = 'check_a'; -DROP TABLE part_3_4; - --- check that a detached partition is not dropped on dropping a partitioned table -CREATE TABLE range_parted2 ( - a int -) PARTITION BY RANGE(a); -CREATE TABLE part_rp PARTITION OF range_parted2 FOR VALUES FROM (0) to (100); -ALTER TABLE range_parted2 DETACH PARTITION part_rp; -DROP TABLE range_parted2; -SELECT * from part_rp; -DROP TABLE part_rp; - --- concurrent detach -CREATE TABLE range_parted2 ( - a int -) PARTITION BY RANGE(a); -CREATE TABLE part_rp PARTITION OF range_parted2 FOR VALUES FROM (0) to (100); -BEGIN; --- doesn't work in a partition block -ALTER TABLE range_parted2 DETACH PARTITION part_rp CONCURRENTLY; -COMMIT; -CREATE TABLE part_rpd PARTITION OF range_parted2 DEFAULT; --- doesn't work if there's a default partition -ALTER TABLE range_parted2 DETACH PARTITION part_rp CONCURRENTLY; --- doesn't work for the default partition -ALTER TABLE range_parted2 DETACH PARTITION part_rpd CONCURRENTLY; -DROP TABLE part_rpd; --- works fine -ALTER TABLE range_parted2 DETACH PARTITION part_rp CONCURRENTLY; -\d+ range_parted2 --- constraint should be created -\d part_rp -CREATE TABLE part_rp100 PARTITION OF range_parted2 (CHECK (a>=123 AND a<133 AND a IS NOT NULL)) FOR VALUES FROM (100) to (200); -ALTER TABLE range_parted2 DETACH PARTITION part_rp100 CONCURRENTLY; --- redundant constraint should not be created -\d part_rp100 -DROP TABLE range_parted2; - --- Check ALTER TABLE commands for partitioned tables and partitions - --- cannot add/drop column to/from *only* the parent -ALTER TABLE ONLY list_parted2 ADD COLUMN c int; -ALTER TABLE ONLY list_parted2 DROP COLUMN b; - --- cannot add a column to partition or drop an inherited one -ALTER TABLE part_2 ADD COLUMN c text; -ALTER TABLE part_2 DROP COLUMN b; - --- Nor rename, alter type -ALTER TABLE part_2 RENAME COLUMN b to c; -ALTER TABLE part_2 ALTER COLUMN b TYPE text; - --- cannot add/drop NOT NULL or check constraints to *only* the parent, when --- partitions exist -ALTER TABLE ONLY list_parted2 ALTER b SET NOT NULL; -ALTER TABLE ONLY list_parted2 ADD CONSTRAINT check_b CHECK (b <> 'zz'); - -ALTER TABLE list_parted2 ALTER b SET NOT NULL; -ALTER TABLE ONLY list_parted2 ALTER b DROP NOT NULL; -ALTER TABLE list_parted2 ADD CONSTRAINT check_b CHECK (b <> 'zz'); -ALTER TABLE ONLY list_parted2 DROP CONSTRAINT check_b; - --- It's alright though, if no partitions are yet created -CREATE TABLE parted_no_parts (a int) PARTITION BY LIST (a); -ALTER TABLE ONLY parted_no_parts ALTER a SET NOT NULL; -ALTER TABLE ONLY parted_no_parts ADD CONSTRAINT check_a CHECK (a > 0); -ALTER TABLE ONLY parted_no_parts ALTER a DROP NOT NULL; -ALTER TABLE ONLY parted_no_parts DROP CONSTRAINT check_a; -DROP TABLE parted_no_parts; - --- cannot drop inherited NOT NULL or check constraints from partition -ALTER TABLE list_parted2 ALTER b SET NOT NULL, ADD CONSTRAINT check_a2 CHECK (a > 0); -ALTER TABLE part_2 ALTER b DROP NOT NULL; -ALTER TABLE part_2 DROP CONSTRAINT check_a2; - --- Doesn't make sense to add NO INHERIT constraints on partitioned tables -ALTER TABLE list_parted2 add constraint check_b2 check (b <> 'zz') NO INHERIT; - --- check that a partition cannot participate in regular inheritance -CREATE TABLE inh_test () INHERITS (part_2); -CREATE TABLE inh_test (LIKE part_2); -ALTER TABLE inh_test INHERIT part_2; -ALTER TABLE part_2 INHERIT inh_test; - --- cannot drop or alter type of partition key columns of lower level --- partitioned tables; for example, part_5, which is list_parted2's --- partition, is partitioned on b; -ALTER TABLE list_parted2 DROP COLUMN b; -ALTER TABLE list_parted2 ALTER COLUMN b TYPE text; - --- dropping non-partition key columns should be allowed on the parent table. -ALTER TABLE list_parted DROP COLUMN b; -SELECT * FROM list_parted; - --- cleanup -DROP TABLE list_parted, list_parted2, range_parted; -DROP TABLE fail_def_part; -DROP TABLE hash_parted; - --- more tests for certain multi-level partitioning scenarios -create table p (a int, b int) partition by range (a, b); -create table p1 (b int, a int not null) partition by range (b); -create table p11 (like p1); -alter table p11 drop a; -alter table p11 add a int; -alter table p11 drop a; -alter table p11 add a int not null; --- attnum for key attribute 'a' is different in p, p1, and p11 -select attrelid::regclass, attname, attnum -from pg_attribute -where attname = 'a' - and (attrelid = 'p'::regclass - or attrelid = 'p1'::regclass - or attrelid = 'p11'::regclass) -order by attrelid::regclass::text; - -alter table p1 attach partition p11 for values from (2) to (5); - -insert into p1 (a, b) values (2, 3); --- check that partition validation scan correctly detects violating rows -alter table p attach partition p1 for values from (1, 2) to (1, 10); - --- cleanup -drop table p; -drop table p1; - --- validate constraint on partitioned tables should only scan leaf partitions -create table parted_validate_test (a int) partition by list (a); -create table parted_validate_test_1 partition of parted_validate_test for values in (0, 1); -alter table parted_validate_test add constraint parted_validate_test_chka check (a > 0) not valid; -alter table parted_validate_test validate constraint parted_validate_test_chka; -drop table parted_validate_test; --- test alter column options -CREATE TABLE attmp(i integer); -INSERT INTO attmp VALUES (1); -ALTER TABLE attmp ALTER COLUMN i SET (n_distinct = 1, n_distinct_inherited = 2); -ALTER TABLE attmp ALTER COLUMN i RESET (n_distinct_inherited); -ANALYZE attmp; -DROP TABLE attmp; - -DROP USER regress_alter_table_user1; - --- check that violating rows are correctly reported when attaching as the --- default partition -create table defpart_attach_test (a int) partition by list (a); -create table defpart_attach_test1 partition of defpart_attach_test for values in (1); -create table defpart_attach_test_d (b int, a int); -alter table defpart_attach_test_d drop b; -insert into defpart_attach_test_d values (1), (2); - --- error because its constraint as the default partition would be violated --- by the row containing 1 -alter table defpart_attach_test attach partition defpart_attach_test_d default; -delete from defpart_attach_test_d where a = 1; -alter table defpart_attach_test_d add check (a > 1); - --- should be attached successfully and without needing to be scanned -alter table defpart_attach_test attach partition defpart_attach_test_d default; - --- check that attaching a partition correctly reports any rows in the default --- partition that should not be there for the new partition to be attached --- successfully -create table defpart_attach_test_2 (like defpart_attach_test_d); -alter table defpart_attach_test attach partition defpart_attach_test_2 for values in (2); - -drop table defpart_attach_test; - --- check combinations of temporary and permanent relations when attaching --- partitions. -create table perm_part_parent (a int) partition by list (a); -create temp table temp_part_parent (a int) partition by list (a); -create table perm_part_child (a int); -create temp table temp_part_child (a int); -alter table temp_part_parent attach partition perm_part_child default; -- error -alter table perm_part_parent attach partition temp_part_child default; -- error -alter table temp_part_parent attach partition temp_part_child default; -- ok -drop table perm_part_parent cascade; -drop table temp_part_parent cascade; - --- check that attaching partitions to a table while it is being used is --- prevented -create table tab_part_attach (a int) partition by list (a); -create or replace function func_part_attach() returns trigger - language plpgsql as $$ - begin - execute 'create table tab_part_attach_1 (a int)'; - execute 'alter table tab_part_attach attach partition tab_part_attach_1 for values in (1)'; - return null; - end $$; -create trigger trig_part_attach before insert on tab_part_attach - for each statement execute procedure func_part_attach(); -insert into tab_part_attach values (1); -drop table tab_part_attach; -drop function func_part_attach(); - --- test case where the partitioning operator is a SQL function whose --- evaluation results in the table's relcache being rebuilt partway through --- the execution of an ATTACH PARTITION command -create function at_test_sql_partop (int4, int4) returns int language sql -as $$ select case when $1 = $2 then 0 when $1 > $2 then 1 else -1 end; $$; -create operator class at_test_sql_partop for type int4 using btree as - operator 1 < (int4, int4), operator 2 <= (int4, int4), - operator 3 = (int4, int4), operator 4 >= (int4, int4), - operator 5 > (int4, int4), function 1 at_test_sql_partop(int4, int4); -create table at_test_sql_partop (a int) partition by range (a at_test_sql_partop); -create table at_test_sql_partop_1 (a int); -alter table at_test_sql_partop attach partition at_test_sql_partop_1 for values from (0) to (10); -drop table at_test_sql_partop; -drop operator class at_test_sql_partop using btree; -drop function at_test_sql_partop; - - -/* Test case for bug #16242 */ - --- We create a parent and child where the child has missing --- non-null attribute values, and arrange to pass them through --- tuple conversion from the child to the parent tupdesc -create table bar1 (a integer, b integer not null default 1) - partition by range (a); -create table bar2 (a integer); -insert into bar2 values (1); -alter table bar2 add column b integer not null default 1; --- (at this point bar2 contains tuple with natts=1) -alter table bar1 attach partition bar2 default; - --- this works: -select * from bar1; - --- this exercises tuple conversion: -create function xtrig() - returns trigger language plpgsql -as $$ - declare - r record; - begin - for r in select * from old loop - raise info 'a=%, b=%', r.a, r.b; - end loop; - return NULL; - end; -$$; -create trigger xtrig - after update on bar1 - referencing old table as old - for each statement execute procedure xtrig(); - -update bar1 set a = a + 1; - -/* End test case for bug #16242 */ - -/* Test case for bug #17409 */ - -create table attbl (p1 int constraint pk_attbl primary key); -create table atref (c1 int references attbl(p1)); -cluster attbl using pk_attbl; -alter table attbl alter column p1 set data type bigint; -alter table atref alter column c1 set data type bigint; -drop table attbl, atref; - -create table attbl (p1 int constraint pk_attbl primary key); -alter table attbl replica identity using index pk_attbl; -create table atref (c1 int references attbl(p1)); -alter table attbl alter column p1 set data type bigint; -alter table atref alter column c1 set data type bigint; -drop table attbl, atref; - -/* End test case for bug #17409 */ - --- Test that ALTER TABLE rewrite preserves a clustered index --- for normal indexes and indexes on constraints. -create table alttype_cluster (a int); -alter table alttype_cluster add primary key (a); -create index alttype_cluster_ind on alttype_cluster (a); -alter table alttype_cluster cluster on alttype_cluster_ind; --- Normal index remains clustered. -select indexrelid::regclass, indisclustered from pg_index - where indrelid = 'alttype_cluster'::regclass - order by indexrelid::regclass::text; -alter table alttype_cluster alter a type bigint; -select indexrelid::regclass, indisclustered from pg_index - where indrelid = 'alttype_cluster'::regclass - order by indexrelid::regclass::text; --- Constraint index remains clustered. -alter table alttype_cluster cluster on alttype_cluster_pkey; -select indexrelid::regclass, indisclustered from pg_index - where indrelid = 'alttype_cluster'::regclass - order by indexrelid::regclass::text; -alter table alttype_cluster alter a type int; -select indexrelid::regclass, indisclustered from pg_index - where indrelid = 'alttype_cluster'::regclass - order by indexrelid::regclass::text; -drop table alttype_cluster; - --- --- Check that attaching or detaching a partitioned partition correctly leads --- to its partitions' constraint being updated to reflect the parent's --- newly added/removed constraint -create table target_parted (a int, b int) partition by list (a); -create table attach_parted (a int, b int) partition by list (b); -create table attach_parted_part1 partition of attach_parted for values in (1); --- insert a row directly into the leaf partition so that its partition --- constraint is built and stored in the relcache -insert into attach_parted_part1 values (1, 1); --- the following better invalidate the partition constraint of the leaf --- partition too... -alter table target_parted attach partition attach_parted for values in (1); --- ...such that the following insert fails -insert into attach_parted_part1 values (2, 1); --- ...and doesn't when the partition is detached along with its own partition -alter table target_parted detach partition attach_parted; -insert into attach_parted_part1 values (2, 1); - --- Test altering table having publication -create schema alter1; -create schema alter2; -create table alter1.t1 (a int); -set client_min_messages = 'ERROR'; -create publication pub1 for table alter1.t1, all tables in schema alter2; -reset client_min_messages; -alter table alter1.t1 set schema alter2; -- should fail -drop publication pub1; -drop schema alter1 cascade; -drop schema alter2 cascade; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Farrays.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Farrays.sql deleted file mode 100644 index f774faf856..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Farrays.sql +++ /dev/null @@ -1,756 +0,0 @@ --- --- ARRAYS --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - -CREATE TABLE arrtest ( - a int2[], - b int4[][][], - c name[], - d text[][], - e float8[], - f char(5)[], - g varchar(5)[] -); - -CREATE TABLE array_op_test ( - seqno int4, - i int4[], - t text[] -); - -\set filename :abs_srcdir '/data/array.data' -COPY array_op_test FROM :'filename'; -ANALYZE array_op_test; - --- --- only the 'e' array is 0-based, the others are 1-based. --- - -INSERT INTO arrtest (a[1:5], b[1:1][1:2][1:2], c, d, f, g) - VALUES ('{1,2,3,4,5}', '{{{0,0},{1,2}}}', '{}', '{}', '{}', '{}'); - -UPDATE arrtest SET e[0] = '1.1'; - -UPDATE arrtest SET e[1] = '2.2'; - -INSERT INTO arrtest (f) - VALUES ('{"too long"}'); - -INSERT INTO arrtest (a, b[1:2][1:2], c, d, e, f, g) - VALUES ('{11,12,23}', '{{3,4},{4,5}}', '{"foobar"}', - '{{"elt1", "elt2"}}', '{"3.4", "6.7"}', - '{"abc","abcde"}', '{"abc","abcde"}'); - -INSERT INTO arrtest (a, b[1:2], c, d[1:2]) - VALUES ('{}', '{3,4}', '{foo,bar}', '{bar,foo}'); - -INSERT INTO arrtest (b[2]) VALUES(now()); -- error, type mismatch - -INSERT INTO arrtest (b[1:2]) VALUES(now()); -- error, type mismatch - -SELECT * FROM arrtest; - -SELECT arrtest.a[1], - arrtest.b[1][1][1], - arrtest.c[1], - arrtest.d[1][1], - arrtest.e[0] - FROM arrtest; - -SELECT a[1], b[1][1][1], c[1], d[1][1], e[0] - FROM arrtest; - -SELECT a[1:3], - b[1:1][1:2][1:2], - c[1:2], - d[1:1][1:2] - FROM arrtest; - -SELECT array_ndims(a) AS a,array_ndims(b) AS b,array_ndims(c) AS c - FROM arrtest; - -SELECT array_dims(a) AS a,array_dims(b) AS b,array_dims(c) AS c - FROM arrtest; - --- returns nothing -SELECT * - FROM arrtest - WHERE a[1] < 5 and - c = '{"foobar"}'::_name; - -UPDATE arrtest - SET a[1:2] = '{16,25}' - WHERE NOT a = '{}'::_int2; - -UPDATE arrtest - SET b[1:1][1:1][1:2] = '{113, 117}', - b[1:1][1:2][2:2] = '{142, 147}' - WHERE array_dims(b) = '[1:1][1:2][1:2]'; - -UPDATE arrtest - SET c[2:2] = '{"new_word"}' - WHERE array_dims(c) is not null; - -SELECT a,b,c FROM arrtest; - -SELECT a[1:3], - b[1:1][1:2][1:2], - c[1:2], - d[1:1][2:2] - FROM arrtest; - -SELECT b[1:1][2][2], - d[1:1][2] - FROM arrtest; - -INSERT INTO arrtest(a) VALUES('{1,null,3}'); -SELECT a FROM arrtest; -UPDATE arrtest SET a[4] = NULL WHERE a[2] IS NULL; -SELECT a FROM arrtest WHERE a[2] IS NULL; -DELETE FROM arrtest WHERE a[2] IS NULL AND b IS NULL; -SELECT a,b,c FROM arrtest; - --- test mixed slice/scalar subscripting -select '{{1,2,3},{4,5,6},{7,8,9}}'::int[]; -select ('{{1,2,3},{4,5,6},{7,8,9}}'::int[])[1:2][2]; -select '[0:2][0:2]={{1,2,3},{4,5,6},{7,8,9}}'::int[]; -select ('[0:2][0:2]={{1,2,3},{4,5,6},{7,8,9}}'::int[])[1:2][2]; - --- --- check subscription corner cases --- --- More subscripts than MAXDIM (6) -SELECT ('{}'::int[])[1][2][3][4][5][6][7]; --- NULL index yields NULL when selecting -SELECT ('{{{1},{2},{3}},{{4},{5},{6}}}'::int[])[1][NULL][1]; -SELECT ('{{{1},{2},{3}},{{4},{5},{6}}}'::int[])[1][NULL:1][1]; -SELECT ('{{{1},{2},{3}},{{4},{5},{6}}}'::int[])[1][1:NULL][1]; --- NULL index in assignment is an error -UPDATE arrtest - SET c[NULL] = '{"can''t assign"}' - WHERE array_dims(c) is not null; -UPDATE arrtest - SET c[NULL:1] = '{"can''t assign"}' - WHERE array_dims(c) is not null; -UPDATE arrtest - SET c[1:NULL] = '{"can''t assign"}' - WHERE array_dims(c) is not null; --- Un-subscriptable type -SELECT (now())[1]; - --- test slices with empty lower and/or upper index -CREATE TEMP TABLE arrtest_s ( - a int2[], - b int2[][] -); -INSERT INTO arrtest_s VALUES ('{1,2,3,4,5}', '{{1,2,3}, {4,5,6}, {7,8,9}}'); -INSERT INTO arrtest_s VALUES ('[0:4]={1,2,3,4,5}', '[0:2][0:2]={{1,2,3}, {4,5,6}, {7,8,9}}'); - -SELECT * FROM arrtest_s; -SELECT a[:3], b[:2][:2] FROM arrtest_s; -SELECT a[2:], b[2:][2:] FROM arrtest_s; -SELECT a[:], b[:] FROM arrtest_s; - --- updates -UPDATE arrtest_s SET a[:3] = '{11, 12, 13}', b[:2][:2] = '{{11,12}, {14,15}}' - WHERE array_lower(a,1) = 1; -SELECT * FROM arrtest_s; -UPDATE arrtest_s SET a[3:] = '{23, 24, 25}', b[2:][2:] = '{{25,26}, {28,29}}'; -SELECT * FROM arrtest_s; -UPDATE arrtest_s SET a[:] = '{11, 12, 13, 14, 15}'; -SELECT * FROM arrtest_s; -UPDATE arrtest_s SET a[:] = '{23, 24, 25}'; -- fail, too small -INSERT INTO arrtest_s VALUES(NULL, NULL); -UPDATE arrtest_s SET a[:] = '{11, 12, 13, 14, 15}'; -- fail, no good with null - --- we want to work with a point_tbl that includes a null -CREATE TEMP TABLE point_tbl AS SELECT * FROM public.point_tbl; -INSERT INTO POINT_TBL(f1) VALUES (NULL); - --- check with fixed-length-array type, such as point -SELECT f1[0:1] FROM POINT_TBL; -SELECT f1[0:] FROM POINT_TBL; -SELECT f1[:1] FROM POINT_TBL; -SELECT f1[:] FROM POINT_TBL; - --- subscript assignments to fixed-width result in NULL if previous value is NULL -UPDATE point_tbl SET f1[0] = 10 WHERE f1 IS NULL RETURNING *; -INSERT INTO point_tbl(f1[0]) VALUES(0) RETURNING *; --- NULL assignments get ignored -UPDATE point_tbl SET f1[0] = NULL WHERE f1::text = '(10,10)'::point::text RETURNING *; --- but non-NULL subscript assignments work -UPDATE point_tbl SET f1[0] = -10, f1[1] = -10 WHERE f1::text = '(10,10)'::point::text RETURNING *; --- but not to expand the range -UPDATE point_tbl SET f1[3] = 10 WHERE f1::text = '(-10,-10)'::point::text RETURNING *; - --- --- test array extension --- -CREATE TEMP TABLE arrtest1 (i int[], t text[]); -insert into arrtest1 values(array[1,2,null,4], array['one','two',null,'four']); -select * from arrtest1; -update arrtest1 set i[2] = 22, t[2] = 'twenty-two'; -select * from arrtest1; -update arrtest1 set i[5] = 5, t[5] = 'five'; -select * from arrtest1; -update arrtest1 set i[8] = 8, t[8] = 'eight'; -select * from arrtest1; -update arrtest1 set i[0] = 0, t[0] = 'zero'; -select * from arrtest1; -update arrtest1 set i[-3] = -3, t[-3] = 'minus-three'; -select * from arrtest1; -update arrtest1 set i[0:2] = array[10,11,12], t[0:2] = array['ten','eleven','twelve']; -select * from arrtest1; -update arrtest1 set i[8:10] = array[18,null,20], t[8:10] = array['p18',null,'p20']; -select * from arrtest1; -update arrtest1 set i[11:12] = array[null,22], t[11:12] = array[null,'p22']; -select * from arrtest1; -update arrtest1 set i[15:16] = array[null,26], t[15:16] = array[null,'p26']; -select * from arrtest1; -update arrtest1 set i[-5:-3] = array[-15,-14,-13], t[-5:-3] = array['m15','m14','m13']; -select * from arrtest1; -update arrtest1 set i[-7:-6] = array[-17,null], t[-7:-6] = array['m17',null]; -select * from arrtest1; -update arrtest1 set i[-12:-10] = array[-22,null,-20], t[-12:-10] = array['m22',null,'m20']; -select * from arrtest1; -delete from arrtest1; -insert into arrtest1 values(array[1,2,null,4], array['one','two',null,'four']); -select * from arrtest1; -update arrtest1 set i[0:5] = array[0,1,2,null,4,5], t[0:5] = array['z','p1','p2',null,'p4','p5']; -select * from arrtest1; - --- --- array expressions and operators --- - --- table creation and INSERTs -CREATE TEMP TABLE arrtest2 (i integer ARRAY[4], f float8[], n numeric[], t text[], d timestamp[]); -INSERT INTO arrtest2 VALUES( - ARRAY[[[113,142],[1,147]]], - ARRAY[1.1,1.2,1.3]::float8[], - ARRAY[1.1,1.2,1.3], - ARRAY[[['aaa','aab'],['aba','abb'],['aca','acb']],[['baa','bab'],['bba','bbb'],['bca','bcb']]], - ARRAY['19620326','19931223','19970117']::timestamp[] -); - --- some more test data -CREATE TEMP TABLE arrtest_f (f0 int, f1 text, f2 float8); -insert into arrtest_f values(1,'cat1',1.21); -insert into arrtest_f values(2,'cat1',1.24); -insert into arrtest_f values(3,'cat1',1.18); -insert into arrtest_f values(4,'cat1',1.26); -insert into arrtest_f values(5,'cat1',1.15); -insert into arrtest_f values(6,'cat2',1.15); -insert into arrtest_f values(7,'cat2',1.26); -insert into arrtest_f values(8,'cat2',1.32); -insert into arrtest_f values(9,'cat2',1.30); - -CREATE TEMP TABLE arrtest_i (f0 int, f1 text, f2 int); -insert into arrtest_i values(1,'cat1',21); -insert into arrtest_i values(2,'cat1',24); -insert into arrtest_i values(3,'cat1',18); -insert into arrtest_i values(4,'cat1',26); -insert into arrtest_i values(5,'cat1',15); -insert into arrtest_i values(6,'cat2',15); -insert into arrtest_i values(7,'cat2',26); -insert into arrtest_i values(8,'cat2',32); -insert into arrtest_i values(9,'cat2',30); - --- expressions -SELECT t.f[1][3][1] AS "131", t.f[2][2][1] AS "221" FROM ( - SELECT ARRAY[[[111,112],[121,122],[131,132]],[[211,212],[221,122],[231,232]]] AS f -) AS t; -SELECT ARRAY[[[[[['hello'],['world']]]]]]; -SELECT ARRAY[ARRAY['hello'],ARRAY['world']]; -SELECT ARRAY(select f2 from arrtest_f order by f2) AS "ARRAY"; - --- with nulls -SELECT '{1,null,3}'::int[]; -SELECT ARRAY[1,NULL,3]; - --- functions -SELECT array_append(array[42], 6) AS "{42,6}"; -SELECT array_prepend(6, array[42]) AS "{6,42}"; -SELECT array_cat(ARRAY[1,2], ARRAY[3,4]) AS "{1,2,3,4}"; -SELECT array_cat(ARRAY[1,2], ARRAY[[3,4],[5,6]]) AS "{{1,2},{3,4},{5,6}}"; -SELECT array_cat(ARRAY[[3,4],[5,6]], ARRAY[1,2]) AS "{{3,4},{5,6},{1,2}}"; - -SELECT array_position(ARRAY[1,2,3,4,5], 4); -SELECT array_position(ARRAY[5,3,4,2,1], 4); -SELECT array_position(ARRAY[[1,2],[3,4]], 3); -SELECT array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], 'mon'); -SELECT array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], 'sat'); -SELECT array_position(ARRAY['sun','mon','tue','wed','thu','fri','sat'], NULL); -SELECT array_position(ARRAY['sun','mon','tue','wed','thu',NULL,'fri','sat'], NULL); -SELECT array_position(ARRAY['sun','mon','tue','wed','thu',NULL,'fri','sat'], 'sat'); - -SELECT array_positions(NULL, 10); -SELECT array_positions(NULL, NULL::int); -SELECT array_positions(ARRAY[1,2,3,4,5,6,1,2,3,4,5,6], 4); -SELECT array_positions(ARRAY[[1,2],[3,4]], 4); -SELECT array_positions(ARRAY[1,2,3,4,5,6,1,2,3,4,5,6], NULL); -SELECT array_positions(ARRAY[1,2,3,NULL,5,6,1,2,3,NULL,5,6], NULL); -SELECT array_length(array_positions(ARRAY(SELECT 'AAAAAAAAAAAAAAAAAAAAAAAAA'::text || i % 10 - FROM generate_series(1,100) g(i)), - 'AAAAAAAAAAAAAAAAAAAAAAAAA5'), 1); - -DO $$ -DECLARE - o int; - a int[] := ARRAY[1,2,3,2,3,1,2]; -BEGIN - o := array_position(a, 2); - WHILE o IS NOT NULL - LOOP - RAISE NOTICE '%', o; - o := array_position(a, 2, o + 1); - END LOOP; -END -$$ LANGUAGE plpgsql; - -SELECT array_position('[2:4]={1,2,3}'::int[], 1); -SELECT array_positions('[2:4]={1,2,3}'::int[], 1); - -SELECT - array_position(ids, (1, 1)), - array_positions(ids, (1, 1)) - FROM -(VALUES - (ARRAY[(0, 0), (1, 1)]), - (ARRAY[(1, 1)]) -) AS f (ids); - --- operators -SELECT a FROM arrtest WHERE b = ARRAY[[[113,142],[1,147]]]; -SELECT NOT ARRAY[1.1,1.2,1.3] = ARRAY[1.1,1.2,1.3] AS "FALSE"; -SELECT ARRAY[1,2] || 3 AS "{1,2,3}"; -SELECT 0 || ARRAY[1,2] AS "{0,1,2}"; -SELECT ARRAY[1,2] || ARRAY[3,4] AS "{1,2,3,4}"; -SELECT ARRAY[[['hello','world']]] || ARRAY[[['happy','birthday']]] AS "ARRAY"; -SELECT ARRAY[[1,2],[3,4]] || ARRAY[5,6] AS "{{1,2},{3,4},{5,6}}"; -SELECT ARRAY[0,0] || ARRAY[1,1] || ARRAY[2,2] AS "{0,0,1,1,2,2}"; -SELECT 0 || ARRAY[1,2] || 3 AS "{0,1,2,3}"; -SELECT ARRAY[1.1] || ARRAY[2,3,4]; -SELECT array_agg(x) || array_agg(x) FROM (VALUES (ROW(1,2)), (ROW(3,4))) v(x); -SELECT ROW(1,2) || array_agg(x) FROM (VALUES (ROW(3,4)), (ROW(5,6))) v(x); - -SELECT * FROM array_op_test WHERE i @> '{32}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i && '{32}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i @> '{17}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i && '{17}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i @> '{32,17}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i && '{32,17}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i <@ '{38,34,32,89}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i = '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i @> '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i && '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i <@ '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i = '{NULL}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i @> '{NULL}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i && '{NULL}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE i <@ '{NULL}' ORDER BY seqno; - -SELECT * FROM array_op_test WHERE t @> '{AAAAAAAA72908}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t && '{AAAAAAAA72908}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t @> '{AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t && '{AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t @> '{AAAAAAAA72908,AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t && '{AAAAAAAA72908,AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t <@ '{AAAAAAAA72908,AAAAAAAAAAAAAAAAAAA17075,AA88409,AAAAAAAAAAAAAAAAAA36842,AAAAAAA48038,AAAAAAAAAAAAAA10611}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t = '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t @> '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t && '{}' ORDER BY seqno; -SELECT * FROM array_op_test WHERE t <@ '{}' ORDER BY seqno; - --- array casts -SELECT ARRAY[1,2,3]::text[]::int[]::float8[] AS "{1,2,3}"; -SELECT pg_typeof(ARRAY[1,2,3]::text[]::int[]::float8[]) AS "double precision[]"; -SELECT ARRAY[['a','bc'],['def','hijk']]::text[]::varchar[] AS "{{a,bc},{def,hijk}}"; -SELECT pg_typeof(ARRAY[['a','bc'],['def','hijk']]::text[]::varchar[]) AS "character varying[]"; -SELECT CAST(ARRAY[[[[[['a','bb','ccc']]]]]] as text[]) as "{{{{{{a,bb,ccc}}}}}}"; -SELECT NULL::text[]::int[] AS "NULL"; - --- scalar op any/all (array) -select 33 = any ('{1,2,3}'); -select 33 = any ('{1,2,33}'); -select 33 = all ('{1,2,33}'); -select 33 >= all ('{1,2,33}'); --- boundary cases -select null::int >= all ('{1,2,33}'); -select null::int >= all ('{}'); -select null::int >= any ('{}'); --- cross-datatype -select 33.4 = any (array[1,2,3]); -select 33.4 > all (array[1,2,3]); --- errors -select 33 * any ('{1,2,3}'); -select 33 * any (44); --- nulls -select 33 = any (null::int[]); -select null::int = any ('{1,2,3}'); -select 33 = any ('{1,null,3}'); -select 33 = any ('{1,null,33}'); -select 33 = all (null::int[]); -select null::int = all ('{1,2,3}'); -select 33 = all ('{1,null,3}'); -select 33 = all ('{33,null,33}'); --- nulls later in the bitmap -SELECT -1 != ALL(ARRAY(SELECT NULLIF(g.i, 900) FROM generate_series(1,1000) g(i))); - --- test indexes on arrays -create temp table arr_tbl (f1 int[] unique); -insert into arr_tbl values ('{1,2,3}'); -insert into arr_tbl values ('{1,2}'); --- failure expected: -insert into arr_tbl values ('{1,2,3}'); -insert into arr_tbl values ('{2,3,4}'); -insert into arr_tbl values ('{1,5,3}'); -insert into arr_tbl values ('{1,2,10}'); - -set enable_seqscan to off; -set enable_bitmapscan to off; -select * from arr_tbl where f1 > '{1,2,3}' and f1 <= '{1,5,3}'; -select * from arr_tbl where f1 >= '{1,2,3}' and f1 < '{1,5,3}'; - --- test ON CONFLICT DO UPDATE with arrays -create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); -insert into arr_pk_tbl values (1, '{1,2,3}'); -insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) - do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; -insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) - do update set f1[1] = excluded.f1[1], - f1[2] = excluded.f1[2], - f1[3] = excluded.f1[3] - returning pk, f1; - --- note: if above selects don't produce the expected tuple order, --- then you didn't get an indexscan plan, and something is busted. -reset enable_seqscan; -reset enable_bitmapscan; - --- test [not] (like|ilike) (any|all) (...) -select 'foo' like any (array['%a', '%o']); -- t -select 'foo' like any (array['%a', '%b']); -- f -select 'foo' like all (array['f%', '%o']); -- t -select 'foo' like all (array['f%', '%b']); -- f -select 'foo' not like any (array['%a', '%b']); -- t -select 'foo' not like all (array['%a', '%o']); -- f -select 'foo' ilike any (array['%A', '%O']); -- t -select 'foo' ilike all (array['F%', '%O']); -- t - --- --- General array parser tests --- - --- none of the following should be accepted -select '{{1,{2}},{2,3}}'::text[]; -select '{{},{}}'::text[]; -select E'{{1,2},\\{2,3}}'::text[]; -select '{{"1 2" x},{3}}'::text[]; -select '{}}'::text[]; -select '{ }}'::text[]; -select array[]; --- none of the above should be accepted - --- all of the following should be accepted -select '{}'::text[]; -select '{{{1,2,3,4},{2,3,4,5}},{{3,4,5,6},{4,5,6,7}}}'::text[]; -select '{0 second ,0 second}'::interval[]; -select '{ { "," } , { 3 } }'::text[]; -select ' { { " 0 second " , 0 second } }'::text[]; -select '{ - 0 second, - @ 1 hour @ 42 minutes @ 20 seconds - }'::interval[]; -select array[]::text[]; -select '[0:1]={1.1,2.2}'::float8[]; --- all of the above should be accepted - --- tests for array aggregates -CREATE TEMP TABLE arraggtest ( f1 INT[], f2 TEXT[][], f3 FLOAT[]); - -INSERT INTO arraggtest (f1, f2, f3) VALUES -('{1,2,3,4}','{{grey,red},{blue,blue}}','{1.6, 0.0}'); -INSERT INTO arraggtest (f1, f2, f3) VALUES -('{1,2,3}','{{grey,red},{grey,blue}}','{1.6}'); -SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest; - -INSERT INTO arraggtest (f1, f2, f3) VALUES -('{3,3,2,4,5,6}','{{white,yellow},{pink,orange}}','{2.1,3.3,1.8,1.7,1.6}'); -SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest; - -INSERT INTO arraggtest (f1, f2, f3) VALUES -('{2}','{{black,red},{green,orange}}','{1.6,2.2,2.6,0.4}'); -SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest; - -INSERT INTO arraggtest (f1, f2, f3) VALUES -('{4,2,6,7,8,1}','{{red},{black},{purple},{blue},{blue}}',NULL); -SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest; - -INSERT INTO arraggtest (f1, f2, f3) VALUES -('{}','{{pink,white,blue,red,grey,orange}}','{2.1,1.87,1.4,2.2}'); -SELECT max(f1), min(f1), max(f2), min(f2), max(f3), min(f3) FROM arraggtest; - --- A few simple tests for arrays of composite types - -create type comptype as (f1 int, f2 text); - -create table comptable (c1 comptype, c2 comptype[]); - --- XXX would like to not have to specify row() construct types here ... -insert into comptable - values (row(1,'foo'), array[row(2,'bar')::comptype, row(3,'baz')::comptype]); - --- check that implicitly named array type _comptype isn't a problem -create type _comptype as enum('fooey'); - -select * from comptable; -select c2[2].f2 from comptable; - -drop type _comptype; -drop table comptable; -drop type comptype; - -create or replace function unnest1(anyarray) -returns setof anyelement as $$ -select $1[s] from generate_subscripts($1,1) g(s); -$$ language sql immutable; - -create or replace function unnest2(anyarray) -returns setof anyelement as $$ -select $1[s1][s2] from generate_subscripts($1,1) g1(s1), - generate_subscripts($1,2) g2(s2); -$$ language sql immutable; - -select * from unnest1(array[1,2,3]); -select * from unnest2(array[[1,2,3],[4,5,6]]); - -drop function unnest1(anyarray); -drop function unnest2(anyarray); - -select array_fill(null::integer, array[3,3],array[2,2]); -select array_fill(null::integer, array[3,3]); -select array_fill(null::text, array[3,3],array[2,2]); -select array_fill(null::text, array[3,3]); -select array_fill(7, array[3,3],array[2,2]); -select array_fill(7, array[3,3]); -select array_fill('juhu'::text, array[3,3],array[2,2]); -select array_fill('juhu'::text, array[3,3]); -select a, a = '{}' as is_eq, array_dims(a) - from (select array_fill(42, array[0]) as a) ss; -select a, a = '{}' as is_eq, array_dims(a) - from (select array_fill(42, '{}') as a) ss; -select a, a = '{}' as is_eq, array_dims(a) - from (select array_fill(42, '{}', '{}') as a) ss; --- raise exception -select array_fill(1, null, array[2,2]); -select array_fill(1, array[2,2], null); -select array_fill(1, array[2,2], '{}'); -select array_fill(1, array[3,3], array[1,1,1]); -select array_fill(1, array[1,2,null]); -select array_fill(1, array[[1,2],[3,4]]); - -select string_to_array('1|2|3', '|'); -select string_to_array('1|2|3|', '|'); -select string_to_array('1||2|3||', '||'); -select string_to_array('1|2|3', ''); -select string_to_array('', '|'); -select string_to_array('1|2|3', NULL); -select string_to_array(NULL, '|') IS NULL; -select string_to_array('abc', ''); -select string_to_array('abc', '', 'abc'); -select string_to_array('abc', ','); -select string_to_array('abc', ',', 'abc'); -select string_to_array('1,2,3,4,,6', ','); -select string_to_array('1,2,3,4,,6', ',', ''); -select string_to_array('1,2,3,4,*,6', ',', '*'); - -select v, v is null as "is null" from string_to_table('1|2|3', '|') g(v); -select v, v is null as "is null" from string_to_table('1|2|3|', '|') g(v); -select v, v is null as "is null" from string_to_table('1||2|3||', '||') g(v); -select v, v is null as "is null" from string_to_table('1|2|3', '') g(v); -select v, v is null as "is null" from string_to_table('', '|') g(v); -select v, v is null as "is null" from string_to_table('1|2|3', NULL) g(v); -select v, v is null as "is null" from string_to_table(NULL, '|') g(v); -select v, v is null as "is null" from string_to_table('abc', '') g(v); -select v, v is null as "is null" from string_to_table('abc', '', 'abc') g(v); -select v, v is null as "is null" from string_to_table('abc', ',') g(v); -select v, v is null as "is null" from string_to_table('abc', ',', 'abc') g(v); -select v, v is null as "is null" from string_to_table('1,2,3,4,,6', ',') g(v); -select v, v is null as "is null" from string_to_table('1,2,3,4,,6', ',', '') g(v); -select v, v is null as "is null" from string_to_table('1,2,3,4,*,6', ',', '*') g(v); - -select array_to_string(NULL::int4[], ',') IS NULL; -select array_to_string('{}'::int4[], ','); -select array_to_string(array[1,2,3,4,NULL,6], ','); -select array_to_string(array[1,2,3,4,NULL,6], ',', '*'); -select array_to_string(array[1,2,3,4,NULL,6], NULL); -select array_to_string(array[1,2,3,4,NULL,6], ',', NULL); - -select array_to_string(string_to_array('1|2|3', '|'), '|'); - -select array_length(array[1,2,3], 1); -select array_length(array[[1,2,3], [4,5,6]], 0); -select array_length(array[[1,2,3], [4,5,6]], 1); -select array_length(array[[1,2,3], [4,5,6]], 2); -select array_length(array[[1,2,3], [4,5,6]], 3); - -select cardinality(NULL::int[]); -select cardinality('{}'::int[]); -select cardinality(array[1,2,3]); -select cardinality('[2:4]={5,6,7}'::int[]); -select cardinality('{{1,2}}'::int[]); -select cardinality('{{1,2},{3,4},{5,6}}'::int[]); -select cardinality('{{{1,9},{5,6}},{{2,3},{3,4}}}'::int[]); - --- array_agg(anynonarray) -select array_agg(unique1) from (select unique1 from tenk1 where unique1 < 15 order by unique1) ss; -select array_agg(ten) from (select ten from tenk1 where unique1 < 15 order by unique1) ss; -select array_agg(nullif(ten, 4)) from (select ten from tenk1 where unique1 < 15 order by unique1) ss; -select array_agg(unique1) from tenk1 where unique1 < -15; - --- array_agg(anyarray) -select array_agg(ar) - from (values ('{1,2}'::int[]), ('{3,4}'::int[])) v(ar); -select array_agg(distinct ar order by ar desc) - from (select array[i / 2] from generate_series(1,10) a(i)) b(ar); -select array_agg(ar) - from (select array_agg(array[i, i+1, i-1]) - from generate_series(1,2) a(i)) b(ar); -select array_agg(array[i+1.2, i+1.3, i+1.4]) from generate_series(1,3) g(i); -select array_agg(array['Hello', i::text]) from generate_series(9,11) g(i); -select array_agg(array[i, nullif(i, 3), i+1]) from generate_series(1,4) g(i); --- errors -select array_agg('{}'::int[]) from generate_series(1,2); -select array_agg(null::int[]) from generate_series(1,2); -select array_agg(ar) - from (values ('{1,2}'::int[]), ('{3}'::int[])) v(ar); - -select unnest(array[1,2,3]); -select * from unnest(array[1,2,3]); -select unnest(array[1,2,3,4.5]::float8[]); -select unnest(array[1,2,3,4.5]::numeric[]); -select unnest(array[1,2,3,null,4,null,null,5,6]); -select unnest(array[1,2,3,null,4,null,null,5,6]::text[]); -select abs(unnest(array[1,2,null,-3])); -select array_remove(array[1,2,2,3], 2); -select array_remove(array[1,2,2,3], 5); -select array_remove(array[1,NULL,NULL,3], NULL); -select array_remove(array['A','CC','D','C','RR'], 'RR'); -select array_remove(array[1.0, 2.1, 3.3], 1); -select array_remove('{{1,2,2},{1,4,3}}', 2); -- not allowed -select array_remove(array['X','X','X'], 'X') = '{}'; -select array_replace(array[1,2,5,4],5,3); -select array_replace(array[1,2,5,4],5,NULL); -select array_replace(array[1,2,NULL,4,NULL],NULL,5); -select array_replace(array['A','B','DD','B'],'B','CC'); -select array_replace(array[1,NULL,3],NULL,NULL); -select array_replace(array['AB',NULL,'CDE'],NULL,'12'); - --- array(select array-value ...) -select array(select array[i,i/2] from generate_series(1,5) i); -select array(select array['Hello', i::text] from generate_series(9,11) i); - --- Insert/update on a column that is array of composite - -create temp table t1 (f1 int8_tbl[]); -insert into t1 (f1[5].q1) values(42); -select * from t1; -update t1 set f1[5].q2 = 43; -select * from t1; - --- Check that arrays of composites are safely detoasted when needed - -create temp table src (f1 text); -insert into src - select string_agg(random()::text,'') from generate_series(1,10000); -create type textandtext as (c1 text, c2 text); -create temp table dest (f1 textandtext[]); -insert into dest select array[row(f1,f1)::textandtext] from src; -select length(md5((f1[1]).c2)) from dest; -delete from src; -select length(md5((f1[1]).c2)) from dest; -truncate table src; -drop table src; -select length(md5((f1[1]).c2)) from dest; -drop table dest; -drop type textandtext; - --- Tests for polymorphic-array form of width_bucket() - --- this exercises the varwidth and float8 code paths -SELECT - op, - width_bucket(op::numeric, ARRAY[1, 3, 5, 10.0]::numeric[]) AS wb_n1, - width_bucket(op::numeric, ARRAY[0, 5.5, 9.99]::numeric[]) AS wb_n2, - width_bucket(op::numeric, ARRAY[-6, -5, 2.0]::numeric[]) AS wb_n3, - width_bucket(op::float8, ARRAY[1, 3, 5, 10.0]::float8[]) AS wb_f1, - width_bucket(op::float8, ARRAY[0, 5.5, 9.99]::float8[]) AS wb_f2, - width_bucket(op::float8, ARRAY[-6, -5, 2.0]::float8[]) AS wb_f3 -FROM (VALUES - (-5.2), - (-0.0000000001), - (0.000000000001), - (1), - (1.99999999999999), - (2), - (2.00000000000001), - (3), - (4), - (4.5), - (5), - (5.5), - (6), - (7), - (8), - (9), - (9.99999999999999), - (10), - (10.0000000000001) -) v(op); - --- ensure float8 path handles NaN properly -SELECT - op, - width_bucket(op, ARRAY[1, 3, 9, 'NaN', 'NaN']::float8[]) AS wb -FROM (VALUES - (-5.2::float8), - (4::float8), - (77::float8), - ('NaN'::float8) -) v(op); - --- these exercise the generic fixed-width code path -SELECT - op, - width_bucket(op, ARRAY[1, 3, 5, 10]) AS wb_1 -FROM generate_series(0,11) as op; - -SELECT width_bucket(now(), - array['yesterday', 'today', 'tomorrow']::timestamptz[]); - --- corner cases -SELECT width_bucket(5, ARRAY[3]); -SELECT width_bucket(5, '{}'); - --- error cases -SELECT width_bucket('5'::text, ARRAY[3, 4]::integer[]); -SELECT width_bucket(5, ARRAY[3, 4, NULL]); -SELECT width_bucket(5, ARRAY[ARRAY[1, 2], ARRAY[3, 4]]); - --- trim_array - -SELECT arr, trim_array(arr, 2) -FROM -(VALUES ('{1,2,3,4,5,6}'::bigint[]), - ('{1,2}'), - ('[10:16]={1,2,3,4,5,6,7}'), - ('[-15:-10]={1,2,3,4,5,6}'), - ('{{1,10},{2,20},{3,30},{4,40}}')) v(arr); - -SELECT trim_array(ARRAY[1, 2, 3], -1); -- fail -SELECT trim_array(ARRAY[1, 2, 3], 10); -- fail diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcase.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcase.sql deleted file mode 100644 index 83fe43be6b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcase.sql +++ /dev/null @@ -1,265 +0,0 @@ --- --- CASE --- Test the case statement --- - -CREATE TABLE CASE_TBL ( - i integer, - f double precision -); - -CREATE TABLE CASE2_TBL ( - i integer, - j integer -); - -INSERT INTO CASE_TBL VALUES (1, 10.1); -INSERT INTO CASE_TBL VALUES (2, 20.2); -INSERT INTO CASE_TBL VALUES (3, -30.3); -INSERT INTO CASE_TBL VALUES (4, NULL); - -INSERT INTO CASE2_TBL VALUES (1, -1); -INSERT INTO CASE2_TBL VALUES (2, -2); -INSERT INTO CASE2_TBL VALUES (3, -3); -INSERT INTO CASE2_TBL VALUES (2, -4); -INSERT INTO CASE2_TBL VALUES (1, NULL); -INSERT INTO CASE2_TBL VALUES (NULL, -6); - --- --- Simplest examples without tables --- - -SELECT '3' AS "One", - CASE - WHEN 1 < 2 THEN 3 - END AS "Simple WHEN"; - -SELECT '' AS "One", - CASE - WHEN 1 > 2 THEN 3 - END AS "Simple default"; - -SELECT '3' AS "One", - CASE - WHEN 1 < 2 THEN 3 - ELSE 4 - END AS "Simple ELSE"; - -SELECT '4' AS "One", - CASE - WHEN 1 > 2 THEN 3 - ELSE 4 - END AS "ELSE default"; - -SELECT '6' AS "One", - CASE - WHEN 1 > 2 THEN 3 - WHEN 4 < 5 THEN 6 - ELSE 7 - END AS "Two WHEN with default"; - - -SELECT '7' AS "None", - CASE WHEN random() < 0 THEN 1 - END AS "NULL on no matches"; - --- Constant-expression folding shouldn't evaluate unreachable subexpressions -SELECT CASE WHEN 1=0 THEN 1/0 WHEN 1=1 THEN 1 ELSE 2/0 END; -SELECT CASE 1 WHEN 0 THEN 1/0 WHEN 1 THEN 1 ELSE 2/0 END; - --- However we do not currently suppress folding of potentially --- reachable subexpressions -SELECT CASE WHEN i > 100 THEN 1/0 ELSE 0 END FROM case_tbl; - --- Test for cases involving untyped literals in test expression -SELECT CASE 'a' WHEN 'a' THEN 1 ELSE 2 END; - --- --- Examples of targets involving tables --- - -SELECT - CASE - WHEN i >= 3 THEN i - END AS ">= 3 or Null" - FROM CASE_TBL; - -SELECT - CASE WHEN i >= 3 THEN (i + i) - ELSE i - END AS "Simplest Math" - FROM CASE_TBL; - -SELECT i AS "Value", - CASE WHEN (i < 0) THEN 'small' - WHEN (i = 0) THEN 'zero' - WHEN (i = 1) THEN 'one' - WHEN (i = 2) THEN 'two' - ELSE 'big' - END AS "Category" - FROM CASE_TBL; - -SELECT - CASE WHEN ((i < 0) or (i < 0)) THEN 'small' - WHEN ((i = 0) or (i = 0)) THEN 'zero' - WHEN ((i = 1) or (i = 1)) THEN 'one' - WHEN ((i = 2) or (i = 2)) THEN 'two' - ELSE 'big' - END AS "Category" - FROM CASE_TBL; - --- --- Examples of qualifications involving tables --- - --- --- NULLIF() and COALESCE() --- Shorthand forms for typical CASE constructs --- defined in the SQL standard. --- - -SELECT * FROM CASE_TBL WHERE COALESCE(f,i) = 4; - -SELECT * FROM CASE_TBL WHERE NULLIF(f,i) = 2; - -SELECT COALESCE(a.f, b.i, b.j) - FROM CASE_TBL a, CASE2_TBL b; - -SELECT * - FROM CASE_TBL a, CASE2_TBL b - WHERE COALESCE(a.f, b.i, b.j) = 2; - -SELECT NULLIF(a.i,b.i) AS "NULLIF(a.i,b.i)", - NULLIF(b.i, 4) AS "NULLIF(b.i,4)" - FROM CASE_TBL a, CASE2_TBL b; - -SELECT * - FROM CASE_TBL a, CASE2_TBL b - WHERE COALESCE(f,b.i) = 2; - --- Tests for constant subexpression simplification - -explain (costs off) -SELECT * FROM CASE_TBL WHERE NULLIF(1, 2) = 2; - -explain (costs off) -SELECT * FROM CASE_TBL WHERE NULLIF(1, 1) IS NOT NULL; - -explain (costs off) -SELECT * FROM CASE_TBL WHERE NULLIF(1, null) = 2; - --- --- Examples of updates involving tables --- - -UPDATE CASE_TBL - SET i = CASE WHEN i >= 3 THEN (- i) - ELSE (2 * i) END; - -SELECT * FROM CASE_TBL; - -UPDATE CASE_TBL - SET i = CASE WHEN i >= 2 THEN (2 * i) - ELSE (3 * i) END; - -SELECT * FROM CASE_TBL; - -UPDATE CASE_TBL - SET i = CASE WHEN b.i >= 2 THEN (2 * j) - ELSE (3 * j) END - FROM CASE2_TBL b - WHERE j = -CASE_TBL.i; - -SELECT * FROM CASE_TBL; - --- --- Nested CASE expressions --- - --- This test exercises a bug caused by aliasing econtext->caseValue_isNull --- with the isNull argument of the inner CASE's CaseExpr evaluation. After --- evaluating the vol(null) expression in the inner CASE's second WHEN-clause, --- the isNull flag for the case test value incorrectly became true, causing --- the third WHEN-clause not to match. The volatile function calls are needed --- to prevent constant-folding in the planner, which would hide the bug. - --- Wrap this in a single transaction so the transient '=' operator doesn't --- cause problems in concurrent sessions -BEGIN; - -CREATE FUNCTION vol(text) returns text as - 'begin return $1; end' language plpgsql volatile; - -SELECT CASE - (CASE vol('bar') - WHEN 'foo' THEN 'it was foo!' - WHEN vol(null) THEN 'null input' - WHEN 'bar' THEN 'it was bar!' END - ) - WHEN 'it was foo!' THEN 'foo recognized' - WHEN 'it was bar!' THEN 'bar recognized' - ELSE 'unrecognized' END; - --- In this case, we can't inline the SQL function without confusing things. -CREATE DOMAIN foodomain AS text; - -CREATE FUNCTION volfoo(text) returns foodomain as - 'begin return $1::foodomain; end' language plpgsql volatile; - -CREATE FUNCTION inline_eq(foodomain, foodomain) returns boolean as - 'SELECT CASE $2::text WHEN $1::text THEN true ELSE false END' language sql; - -CREATE OPERATOR = (procedure = inline_eq, - leftarg = foodomain, rightarg = foodomain); - -SELECT CASE volfoo('bar') WHEN 'foo'::foodomain THEN 'is foo' ELSE 'is not foo' END; - -ROLLBACK; - --- Test multiple evaluation of a CASE arg that is a read/write object (#14472) --- Wrap this in a single transaction so the transient '=' operator doesn't --- cause problems in concurrent sessions -BEGIN; - -CREATE DOMAIN arrdomain AS int[]; - -CREATE FUNCTION make_ad(int,int) returns arrdomain as - 'declare x arrdomain; - begin - x := array[$1,$2]; - return x; - end' language plpgsql volatile; - -CREATE FUNCTION ad_eq(arrdomain, arrdomain) returns boolean as - 'begin return array_eq($1, $2); end' language plpgsql; - -CREATE OPERATOR = (procedure = ad_eq, - leftarg = arrdomain, rightarg = arrdomain); - -SELECT CASE make_ad(1,2) - WHEN array[2,4]::arrdomain THEN 'wrong' - WHEN array[2,5]::arrdomain THEN 'still wrong' - WHEN array[1,2]::arrdomain THEN 'right' - END; - -ROLLBACK; - --- Test interaction of CASE with ArrayCoerceExpr (bug #15471) -BEGIN; - -CREATE TYPE casetestenum AS ENUM ('e', 'f', 'g'); - -SELECT - CASE 'foo'::text - WHEN 'foo' THEN ARRAY['a', 'b', 'c', 'd'] || enum_range(NULL::casetestenum)::text[] - ELSE ARRAY['x', 'y'] - END; - -ROLLBACK; - --- --- Clean up --- - -DROP TABLE CASE_TBL; -DROP TABLE CASE2_TBL; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcluster.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcluster.sql deleted file mode 100644 index 6cb9c926c0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcluster.sql +++ /dev/null @@ -1,319 +0,0 @@ --- --- CLUSTER --- - -CREATE TABLE clstr_tst_s (rf_a SERIAL PRIMARY KEY, - b INT); - -CREATE TABLE clstr_tst (a SERIAL PRIMARY KEY, - b INT, - c TEXT, - d TEXT, - CONSTRAINT clstr_tst_con FOREIGN KEY (b) REFERENCES clstr_tst_s); - -CREATE INDEX clstr_tst_b ON clstr_tst (b); -CREATE INDEX clstr_tst_c ON clstr_tst (c); -CREATE INDEX clstr_tst_c_b ON clstr_tst (c,b); -CREATE INDEX clstr_tst_b_c ON clstr_tst (b,c); - -INSERT INTO clstr_tst_s (b) VALUES (0); -INSERT INTO clstr_tst_s (b) SELECT b FROM clstr_tst_s; -INSERT INTO clstr_tst_s (b) SELECT b FROM clstr_tst_s; -INSERT INTO clstr_tst_s (b) SELECT b FROM clstr_tst_s; -INSERT INTO clstr_tst_s (b) SELECT b FROM clstr_tst_s; -INSERT INTO clstr_tst_s (b) SELECT b FROM clstr_tst_s; - -CREATE TABLE clstr_tst_inh () INHERITS (clstr_tst); - -INSERT INTO clstr_tst (b, c) VALUES (11, 'once'); -INSERT INTO clstr_tst (b, c) VALUES (10, 'diez'); -INSERT INTO clstr_tst (b, c) VALUES (31, 'treinta y uno'); -INSERT INTO clstr_tst (b, c) VALUES (22, 'veintidos'); -INSERT INTO clstr_tst (b, c) VALUES (3, 'tres'); -INSERT INTO clstr_tst (b, c) VALUES (20, 'veinte'); -INSERT INTO clstr_tst (b, c) VALUES (23, 'veintitres'); -INSERT INTO clstr_tst (b, c) VALUES (21, 'veintiuno'); -INSERT INTO clstr_tst (b, c) VALUES (4, 'cuatro'); -INSERT INTO clstr_tst (b, c) VALUES (14, 'catorce'); -INSERT INTO clstr_tst (b, c) VALUES (2, 'dos'); -INSERT INTO clstr_tst (b, c) VALUES (18, 'dieciocho'); -INSERT INTO clstr_tst (b, c) VALUES (27, 'veintisiete'); -INSERT INTO clstr_tst (b, c) VALUES (25, 'veinticinco'); -INSERT INTO clstr_tst (b, c) VALUES (13, 'trece'); -INSERT INTO clstr_tst (b, c) VALUES (28, 'veintiocho'); -INSERT INTO clstr_tst (b, c) VALUES (32, 'treinta y dos'); -INSERT INTO clstr_tst (b, c) VALUES (5, 'cinco'); -INSERT INTO clstr_tst (b, c) VALUES (29, 'veintinueve'); -INSERT INTO clstr_tst (b, c) VALUES (1, 'uno'); -INSERT INTO clstr_tst (b, c) VALUES (24, 'veinticuatro'); -INSERT INTO clstr_tst (b, c) VALUES (30, 'treinta'); -INSERT INTO clstr_tst (b, c) VALUES (12, 'doce'); -INSERT INTO clstr_tst (b, c) VALUES (17, 'diecisiete'); -INSERT INTO clstr_tst (b, c) VALUES (9, 'nueve'); -INSERT INTO clstr_tst (b, c) VALUES (19, 'diecinueve'); -INSERT INTO clstr_tst (b, c) VALUES (26, 'veintiseis'); -INSERT INTO clstr_tst (b, c) VALUES (15, 'quince'); -INSERT INTO clstr_tst (b, c) VALUES (7, 'siete'); -INSERT INTO clstr_tst (b, c) VALUES (16, 'dieciseis'); -INSERT INTO clstr_tst (b, c) VALUES (8, 'ocho'); --- This entry is needed to test that TOASTED values are copied correctly. -INSERT INTO clstr_tst (b, c, d) VALUES (6, 'seis', repeat('xyzzy', 100000)); - -CLUSTER clstr_tst_c ON clstr_tst; - -SELECT a,b,c,substring(d for 30), length(d) from clstr_tst; -SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY a; -SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY b; -SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY c; - --- Verify that inheritance link still works -INSERT INTO clstr_tst_inh VALUES (0, 100, 'in child table'); -SELECT a,b,c,substring(d for 30), length(d) from clstr_tst; - --- Verify that foreign key link still works -INSERT INTO clstr_tst (b, c) VALUES (1111, 'this should fail'); - -SELECT conname FROM pg_constraint WHERE conrelid = 'clstr_tst'::regclass -ORDER BY 1; - - -SELECT relname, relkind, - EXISTS(SELECT 1 FROM pg_class WHERE oid = c.reltoastrelid) AS hastoast -FROM pg_class c WHERE relname LIKE 'clstr_tst%' ORDER BY relname; - --- Verify that indisclustered is correctly set -SELECT pg_class.relname FROM pg_index, pg_class, pg_class AS pg_class_2 -WHERE pg_class.oid=indexrelid - AND indrelid=pg_class_2.oid - AND pg_class_2.relname = 'clstr_tst' - AND indisclustered; - --- Try changing indisclustered -ALTER TABLE clstr_tst CLUSTER ON clstr_tst_b_c; -SELECT pg_class.relname FROM pg_index, pg_class, pg_class AS pg_class_2 -WHERE pg_class.oid=indexrelid - AND indrelid=pg_class_2.oid - AND pg_class_2.relname = 'clstr_tst' - AND indisclustered; - --- Try turning off all clustering -ALTER TABLE clstr_tst SET WITHOUT CLUSTER; -SELECT pg_class.relname FROM pg_index, pg_class, pg_class AS pg_class_2 -WHERE pg_class.oid=indexrelid - AND indrelid=pg_class_2.oid - AND pg_class_2.relname = 'clstr_tst' - AND indisclustered; - --- Verify that toast tables are clusterable -CLUSTER pg_toast.pg_toast_826 USING pg_toast_826_index; - --- Verify that clustering all tables does in fact cluster the right ones -CREATE USER regress_clstr_user; -CREATE TABLE clstr_1 (a INT PRIMARY KEY); -CREATE TABLE clstr_2 (a INT PRIMARY KEY); -CREATE TABLE clstr_3 (a INT PRIMARY KEY); -ALTER TABLE clstr_1 OWNER TO regress_clstr_user; -ALTER TABLE clstr_3 OWNER TO regress_clstr_user; -GRANT SELECT ON clstr_2 TO regress_clstr_user; -INSERT INTO clstr_1 VALUES (2); -INSERT INTO clstr_1 VALUES (1); -INSERT INTO clstr_2 VALUES (2); -INSERT INTO clstr_2 VALUES (1); -INSERT INTO clstr_3 VALUES (2); -INSERT INTO clstr_3 VALUES (1); - --- "CLUSTER " on a table that hasn't been clustered -CLUSTER clstr_2; - -CLUSTER clstr_1_pkey ON clstr_1; -CLUSTER clstr_2 USING clstr_2_pkey; -SELECT * FROM clstr_1 UNION ALL - SELECT * FROM clstr_2 UNION ALL - SELECT * FROM clstr_3; - --- revert to the original state -DELETE FROM clstr_1; -DELETE FROM clstr_2; -DELETE FROM clstr_3; -INSERT INTO clstr_1 VALUES (2); -INSERT INTO clstr_1 VALUES (1); -INSERT INTO clstr_2 VALUES (2); -INSERT INTO clstr_2 VALUES (1); -INSERT INTO clstr_3 VALUES (2); -INSERT INTO clstr_3 VALUES (1); - --- this user can only cluster clstr_1 and clstr_3, but the latter --- has not been clustered -SET SESSION AUTHORIZATION regress_clstr_user; -CLUSTER; -SELECT * FROM clstr_1 UNION ALL - SELECT * FROM clstr_2 UNION ALL - SELECT * FROM clstr_3; - --- cluster a single table using the indisclustered bit previously set -DELETE FROM clstr_1; -INSERT INTO clstr_1 VALUES (2); -INSERT INTO clstr_1 VALUES (1); -CLUSTER clstr_1; -SELECT * FROM clstr_1; - --- Test MVCC-safety of cluster. There isn't much we can do to verify the --- results with a single backend... - -CREATE TABLE clustertest (key int PRIMARY KEY); - -INSERT INTO clustertest VALUES (10); -INSERT INTO clustertest VALUES (20); -INSERT INTO clustertest VALUES (30); -INSERT INTO clustertest VALUES (40); -INSERT INTO clustertest VALUES (50); - --- Use a transaction so that updates are not committed when CLUSTER sees 'em -BEGIN; - --- Test update where the old row version is found first in the scan -UPDATE clustertest SET key = 100 WHERE key = 10; - --- Test update where the new row version is found first in the scan -UPDATE clustertest SET key = 35 WHERE key = 40; - --- Test longer update chain -UPDATE clustertest SET key = 60 WHERE key = 50; -UPDATE clustertest SET key = 70 WHERE key = 60; -UPDATE clustertest SET key = 80 WHERE key = 70; - -SELECT * FROM clustertest; -CLUSTER clustertest_pkey ON clustertest; -SELECT * FROM clustertest; - -COMMIT; - -SELECT * FROM clustertest; - --- check that temp tables can be clustered -create temp table clstr_temp (col1 int primary key, col2 text); -insert into clstr_temp values (2, 'two'), (1, 'one'); -cluster clstr_temp using clstr_temp_pkey; -select * from clstr_temp; -drop table clstr_temp; - -RESET SESSION AUTHORIZATION; - --- check clustering an empty table -DROP TABLE clustertest; -CREATE TABLE clustertest (f1 int PRIMARY KEY); -CLUSTER clustertest USING clustertest_pkey; -CLUSTER clustertest; - --- Check that partitioned tables can be clustered -CREATE TABLE clstrpart (a int) PARTITION BY RANGE (a); -CREATE TABLE clstrpart1 PARTITION OF clstrpart FOR VALUES FROM (1) TO (10) PARTITION BY RANGE (a); -CREATE TABLE clstrpart11 PARTITION OF clstrpart1 FOR VALUES FROM (1) TO (5); -CREATE TABLE clstrpart12 PARTITION OF clstrpart1 FOR VALUES FROM (5) TO (10) PARTITION BY RANGE (a); -CREATE TABLE clstrpart2 PARTITION OF clstrpart FOR VALUES FROM (10) TO (20); -CREATE TABLE clstrpart3 PARTITION OF clstrpart DEFAULT PARTITION BY RANGE (a); -CREATE TABLE clstrpart33 PARTITION OF clstrpart3 DEFAULT; -CREATE INDEX clstrpart_only_idx ON ONLY clstrpart (a); -CLUSTER clstrpart USING clstrpart_only_idx; -- fails -DROP INDEX clstrpart_only_idx; -CREATE INDEX clstrpart_idx ON clstrpart (a); --- Check that clustering sets new relfilenodes: -CREATE TEMP TABLE old_cluster_info AS SELECT relname, level, relfilenode, relkind FROM pg_partition_tree('clstrpart'::regclass) AS tree JOIN pg_class c ON c.oid=tree.relid ; -CLUSTER clstrpart USING clstrpart_idx; -CREATE TEMP TABLE new_cluster_info AS SELECT relname, level, relfilenode, relkind FROM pg_partition_tree('clstrpart'::regclass) AS tree JOIN pg_class c ON c.oid=tree.relid ; -SELECT relname, old.level, old.relkind, old.relfilenode = new.relfilenode FROM old_cluster_info AS old JOIN new_cluster_info AS new USING (relname) ORDER BY relname COLLATE "C"; --- Partitioned indexes aren't and can't be marked un/clustered: -\d clstrpart -CLUSTER clstrpart; -ALTER TABLE clstrpart SET WITHOUT CLUSTER; -ALTER TABLE clstrpart CLUSTER ON clstrpart_idx; -DROP TABLE clstrpart; - --- Ownership of partitions is checked -CREATE TABLE ptnowner(i int unique) PARTITION BY LIST (i); -CREATE INDEX ptnowner_i_idx ON ptnowner(i); -CREATE TABLE ptnowner1 PARTITION OF ptnowner FOR VALUES IN (1); -CREATE ROLE regress_ptnowner; -CREATE TABLE ptnowner2 PARTITION OF ptnowner FOR VALUES IN (2); -ALTER TABLE ptnowner1 OWNER TO regress_ptnowner; -ALTER TABLE ptnowner OWNER TO regress_ptnowner; -CREATE TEMP TABLE ptnowner_oldnodes AS - SELECT oid, relname, relfilenode FROM pg_partition_tree('ptnowner') AS tree - JOIN pg_class AS c ON c.oid=tree.relid; -SET SESSION AUTHORIZATION regress_ptnowner; -CLUSTER ptnowner USING ptnowner_i_idx; -RESET SESSION AUTHORIZATION; -SELECT a.relname, a.relfilenode=b.relfilenode FROM pg_class a - JOIN ptnowner_oldnodes b USING (oid) ORDER BY a.relname COLLATE "C"; -DROP TABLE ptnowner; -DROP ROLE regress_ptnowner; - --- Test CLUSTER with external tuplesorting - -create table clstr_4 as select * from tenk1; -create index cluster_sort on clstr_4 (hundred, thousand, tenthous); --- ensure we don't use the index in CLUSTER nor the checking SELECTs -set enable_indexscan = off; - --- Use external sort: -set maintenance_work_mem = '1MB'; -cluster clstr_4 using cluster_sort; -select * from -(select hundred, lag(hundred) over () as lhundred, - thousand, lag(thousand) over () as lthousand, - tenthous, lag(tenthous) over () as ltenthous from clstr_4) ss -where row(hundred, thousand, tenthous) <= row(lhundred, lthousand, ltenthous); - -reset enable_indexscan; -reset maintenance_work_mem; - --- test CLUSTER on expression index -CREATE TABLE clstr_expression(id serial primary key, a int, b text COLLATE "C"); -INSERT INTO clstr_expression(a, b) SELECT g.i % 42, 'prefix'||g.i FROM generate_series(1, 133) g(i); -CREATE INDEX clstr_expression_minus_a ON clstr_expression ((-a), b); -CREATE INDEX clstr_expression_upper_b ON clstr_expression ((upper(b))); - --- verify indexes work before cluster -BEGIN; -SET LOCAL enable_seqscan = false; -EXPLAIN (COSTS OFF) SELECT * FROM clstr_expression WHERE upper(b) = 'PREFIX3'; -SELECT * FROM clstr_expression WHERE upper(b) = 'PREFIX3'; -EXPLAIN (COSTS OFF) SELECT * FROM clstr_expression WHERE -a = -3 ORDER BY -a, b; -SELECT * FROM clstr_expression WHERE -a = -3 ORDER BY -a, b; -COMMIT; - --- and after clustering on clstr_expression_minus_a -CLUSTER clstr_expression USING clstr_expression_minus_a; -WITH rows AS - (SELECT ctid, lag(a) OVER (ORDER BY ctid) AS la, a FROM clstr_expression) -SELECT * FROM rows WHERE la < a; -BEGIN; -SET LOCAL enable_seqscan = false; -EXPLAIN (COSTS OFF) SELECT * FROM clstr_expression WHERE upper(b) = 'PREFIX3'; -SELECT * FROM clstr_expression WHERE upper(b) = 'PREFIX3'; -EXPLAIN (COSTS OFF) SELECT * FROM clstr_expression WHERE -a = -3 ORDER BY -a, b; -SELECT * FROM clstr_expression WHERE -a = -3 ORDER BY -a, b; -COMMIT; - --- and after clustering on clstr_expression_upper_b -CLUSTER clstr_expression USING clstr_expression_upper_b; -WITH rows AS - (SELECT ctid, lag(b) OVER (ORDER BY ctid) AS lb, b FROM clstr_expression) -SELECT * FROM rows WHERE upper(lb) > upper(b); -BEGIN; -SET LOCAL enable_seqscan = false; -EXPLAIN (COSTS OFF) SELECT * FROM clstr_expression WHERE upper(b) = 'PREFIX3'; -SELECT * FROM clstr_expression WHERE upper(b) = 'PREFIX3'; -EXPLAIN (COSTS OFF) SELECT * FROM clstr_expression WHERE -a = -3 ORDER BY -a, b; -SELECT * FROM clstr_expression WHERE -a = -3 ORDER BY -a, b; -COMMIT; - --- clean up -DROP TABLE clustertest; -DROP TABLE clstr_1; -DROP TABLE clstr_2; -DROP TABLE clstr_3; -DROP TABLE clstr_4; -DROP TABLE clstr_expression; - -DROP USER regress_clstr_user; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcollate.icu.utf8.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcollate.icu.utf8.sql deleted file mode 100644 index b0ddc7db44..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcollate.icu.utf8.sql +++ /dev/null @@ -1,760 +0,0 @@ -/* - * This test is for ICU collations. - */ - -/* skip test if not UTF8 server encoding or no ICU collations installed */ -SELECT getdatabaseencoding() <> 'UTF8' OR - (SELECT count(*) FROM pg_collation WHERE collprovider = 'i') = 0 - AS skip_test \gset -\if :skip_test -\quit -\endif - -SET client_encoding TO UTF8; - -CREATE SCHEMA collate_tests; -SET search_path = collate_tests; - - -CREATE TABLE collate_test1 ( - a int, - b text COLLATE "en-x-icu" NOT NULL -); - -\d collate_test1 - -CREATE TABLE collate_test_fail ( - a int, - b text COLLATE "ja_JP.eucjp-x-icu" -); - -CREATE TABLE collate_test_fail ( - a int, - b text COLLATE "foo-x-icu" -); - -CREATE TABLE collate_test_fail ( - a int COLLATE "en-x-icu", - b text -); - -CREATE TABLE collate_test_like ( - LIKE collate_test1 -); - -\d collate_test_like - -CREATE TABLE collate_test2 ( - a int, - b text COLLATE "sv-x-icu" -); - -CREATE TABLE collate_test3 ( - a int, - b text COLLATE "C" -); - -INSERT INTO collate_test1 VALUES (1, 'abc'), (2, 'äbc'), (3, 'bbc'), (4, 'ABC'); -INSERT INTO collate_test2 SELECT * FROM collate_test1; -INSERT INTO collate_test3 SELECT * FROM collate_test1; - -SELECT * FROM collate_test1 WHERE b >= 'bbc'; -SELECT * FROM collate_test2 WHERE b >= 'bbc'; -SELECT * FROM collate_test3 WHERE b >= 'bbc'; -SELECT * FROM collate_test3 WHERE b >= 'BBC'; - -SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc'; -SELECT * FROM collate_test1 WHERE b >= 'bbc' COLLATE "C"; -SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc' COLLATE "C"; -SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc' COLLATE "en-x-icu"; - - -CREATE DOMAIN testdomain_sv AS text COLLATE "sv-x-icu"; -CREATE DOMAIN testdomain_i AS int COLLATE "sv-x-icu"; -- fails -CREATE TABLE collate_test4 ( - a int, - b testdomain_sv -); -INSERT INTO collate_test4 SELECT * FROM collate_test1; -SELECT a, b FROM collate_test4 ORDER BY b; - -CREATE TABLE collate_test5 ( - a int, - b testdomain_sv COLLATE "en-x-icu" -); -INSERT INTO collate_test5 SELECT * FROM collate_test1; -SELECT a, b FROM collate_test5 ORDER BY b; - - -SELECT a, b FROM collate_test1 ORDER BY b; -SELECT a, b FROM collate_test2 ORDER BY b; -SELECT a, b FROM collate_test3 ORDER BY b; - -SELECT a, b FROM collate_test1 ORDER BY b COLLATE "C"; - --- star expansion -SELECT * FROM collate_test1 ORDER BY b; -SELECT * FROM collate_test2 ORDER BY b; -SELECT * FROM collate_test3 ORDER BY b; - --- constant expression folding -SELECT 'bbc' COLLATE "en-x-icu" > 'äbc' COLLATE "en-x-icu" AS "true"; -SELECT 'bbc' COLLATE "sv-x-icu" > 'äbc' COLLATE "sv-x-icu" AS "false"; - --- upper/lower - -CREATE TABLE collate_test10 ( - a int, - x text COLLATE "en-x-icu", - y text COLLATE "tr-x-icu" -); - -INSERT INTO collate_test10 VALUES (1, 'hij', 'hij'), (2, 'HIJ', 'HIJ'); - -SELECT a, lower(x), lower(y), upper(x), upper(y), initcap(x), initcap(y) FROM collate_test10; -SELECT a, lower(x COLLATE "C"), lower(y COLLATE "C") FROM collate_test10; - -SELECT a, x, y FROM collate_test10 ORDER BY lower(y), a; - --- LIKE/ILIKE - -SELECT * FROM collate_test1 WHERE b LIKE 'abc'; -SELECT * FROM collate_test1 WHERE b LIKE 'abc%'; -SELECT * FROM collate_test1 WHERE b LIKE '%bc%'; -SELECT * FROM collate_test1 WHERE b ILIKE 'abc'; -SELECT * FROM collate_test1 WHERE b ILIKE 'abc%'; -SELECT * FROM collate_test1 WHERE b ILIKE '%bc%'; - -SELECT 'Türkiye' COLLATE "en-x-icu" ILIKE '%KI%' AS "true"; -SELECT 'Türkiye' COLLATE "tr-x-icu" ILIKE '%KI%' AS "false"; - -SELECT 'bıt' ILIKE 'BIT' COLLATE "en-x-icu" AS "false"; -SELECT 'bıt' ILIKE 'BIT' COLLATE "tr-x-icu" AS "true"; - --- The following actually exercises the selectivity estimation for ILIKE. -SELECT relname FROM pg_class WHERE relname ILIKE 'abc%'; - --- regular expressions - -SELECT * FROM collate_test1 WHERE b ~ '^abc$'; -SELECT * FROM collate_test1 WHERE b ~ '^abc'; -SELECT * FROM collate_test1 WHERE b ~ 'bc'; -SELECT * FROM collate_test1 WHERE b ~* '^abc$'; -SELECT * FROM collate_test1 WHERE b ~* '^abc'; -SELECT * FROM collate_test1 WHERE b ~* 'bc'; - -CREATE TABLE collate_test6 ( - a int, - b text COLLATE "en-x-icu" -); -INSERT INTO collate_test6 VALUES (1, 'abc'), (2, 'ABC'), (3, '123'), (4, 'ab1'), - (5, 'a1!'), (6, 'a c'), (7, '!.;'), (8, ' '), - (9, 'äbç'), (10, 'ÄBÇ'); -SELECT b, - b ~ '^[[:alpha:]]+$' AS is_alpha, - b ~ '^[[:upper:]]+$' AS is_upper, - b ~ '^[[:lower:]]+$' AS is_lower, - b ~ '^[[:digit:]]+$' AS is_digit, - b ~ '^[[:alnum:]]+$' AS is_alnum, - b ~ '^[[:graph:]]+$' AS is_graph, - b ~ '^[[:print:]]+$' AS is_print, - b ~ '^[[:punct:]]+$' AS is_punct, - b ~ '^[[:space:]]+$' AS is_space -FROM collate_test6; - -SELECT 'Türkiye' COLLATE "en-x-icu" ~* 'KI' AS "true"; -SELECT 'Türkiye' COLLATE "tr-x-icu" ~* 'KI' AS "true"; -- true with ICU - -SELECT 'bıt' ~* 'BIT' COLLATE "en-x-icu" AS "false"; -SELECT 'bıt' ~* 'BIT' COLLATE "tr-x-icu" AS "false"; -- false with ICU - --- The following actually exercises the selectivity estimation for ~*. -SELECT relname FROM pg_class WHERE relname ~* '^abc'; - - -/* not run by default because it requires tr_TR system locale --- to_char - -SET lc_time TO 'tr_TR'; -SELECT to_char(date '2010-04-01', 'DD TMMON YYYY'); -SELECT to_char(date '2010-04-01', 'DD TMMON YYYY' COLLATE "tr-x-icu"); -*/ - - --- backwards parsing - -CREATE VIEW collview1 AS SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc'; -CREATE VIEW collview2 AS SELECT a, b FROM collate_test1 ORDER BY b COLLATE "C"; -CREATE VIEW collview3 AS SELECT a, lower((x || x) COLLATE "C") FROM collate_test10; - -SELECT table_name, view_definition FROM information_schema.views - WHERE table_name LIKE 'collview%' ORDER BY 1; - - --- collation propagation in various expression types - -SELECT a, coalesce(b, 'foo') FROM collate_test1 ORDER BY 2; -SELECT a, coalesce(b, 'foo') FROM collate_test2 ORDER BY 2; -SELECT a, coalesce(b, 'foo') FROM collate_test3 ORDER BY 2; -SELECT a, lower(coalesce(x, 'foo')), lower(coalesce(y, 'foo')) FROM collate_test10; - -SELECT a, b, greatest(b, 'CCC') FROM collate_test1 ORDER BY 3; -SELECT a, b, greatest(b, 'CCC') FROM collate_test2 ORDER BY 3; -SELECT a, b, greatest(b, 'CCC') FROM collate_test3 ORDER BY 3; -SELECT a, x, y, lower(greatest(x, 'foo')), lower(greatest(y, 'foo')) FROM collate_test10; - -SELECT a, nullif(b, 'abc') FROM collate_test1 ORDER BY 2; -SELECT a, nullif(b, 'abc') FROM collate_test2 ORDER BY 2; -SELECT a, nullif(b, 'abc') FROM collate_test3 ORDER BY 2; -SELECT a, lower(nullif(x, 'foo')), lower(nullif(y, 'foo')) FROM collate_test10; - -SELECT a, CASE b WHEN 'abc' THEN 'abcd' ELSE b END FROM collate_test1 ORDER BY 2; -SELECT a, CASE b WHEN 'abc' THEN 'abcd' ELSE b END FROM collate_test2 ORDER BY 2; -SELECT a, CASE b WHEN 'abc' THEN 'abcd' ELSE b END FROM collate_test3 ORDER BY 2; - -CREATE DOMAIN testdomain AS text; -SELECT a, b::testdomain FROM collate_test1 ORDER BY 2; -SELECT a, b::testdomain FROM collate_test2 ORDER BY 2; -SELECT a, b::testdomain FROM collate_test3 ORDER BY 2; -SELECT a, b::testdomain_sv FROM collate_test3 ORDER BY 2; -SELECT a, lower(x::testdomain), lower(y::testdomain) FROM collate_test10; - -SELECT min(b), max(b) FROM collate_test1; -SELECT min(b), max(b) FROM collate_test2; -SELECT min(b), max(b) FROM collate_test3; - -SELECT array_agg(b ORDER BY b) FROM collate_test1; -SELECT array_agg(b ORDER BY b) FROM collate_test2; -SELECT array_agg(b ORDER BY b) FROM collate_test3; - -SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test1 ORDER BY 2; -SELECT a, b FROM collate_test2 UNION SELECT a, b FROM collate_test2 ORDER BY 2; -SELECT a, b FROM collate_test3 WHERE a < 4 INTERSECT SELECT a, b FROM collate_test3 WHERE a > 1 ORDER BY 2; -SELECT a, b FROM collate_test3 EXCEPT SELECT a, b FROM collate_test3 WHERE a < 2 ORDER BY 2; - -SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test3 ORDER BY 2; -- fail -SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test3; -- ok -SELECT a, b FROM collate_test1 UNION SELECT a, b FROM collate_test3 ORDER BY 2; -- fail -SELECT a, b COLLATE "C" FROM collate_test1 UNION SELECT a, b FROM collate_test3 ORDER BY 2; -- ok -SELECT a, b FROM collate_test1 INTERSECT SELECT a, b FROM collate_test3 ORDER BY 2; -- fail -SELECT a, b FROM collate_test1 EXCEPT SELECT a, b FROM collate_test3 ORDER BY 2; -- fail - -CREATE TABLE test_u AS SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test3; -- fail - --- ideally this would be a parse-time error, but for now it must be run-time: -select x < y from collate_test10; -- fail -select x || y from collate_test10; -- ok, because || is not collation aware -select x, y from collate_test10 order by x || y; -- not so ok - --- collation mismatch between recursive and non-recursive term -WITH RECURSIVE foo(x) AS - (SELECT x FROM (VALUES('a' COLLATE "en-x-icu"),('b')) t(x) - UNION ALL - SELECT (x || 'c') COLLATE "de-x-icu" FROM foo WHERE length(x) < 10) -SELECT * FROM foo; - - --- casting - -SELECT CAST('42' AS text COLLATE "C"); - -SELECT a, CAST(b AS varchar) FROM collate_test1 ORDER BY 2; -SELECT a, CAST(b AS varchar) FROM collate_test2 ORDER BY 2; -SELECT a, CAST(b AS varchar) FROM collate_test3 ORDER BY 2; - - --- propagation of collation in SQL functions (inlined and non-inlined cases) --- and plpgsql functions too - -CREATE FUNCTION mylt (text, text) RETURNS boolean LANGUAGE sql - AS $$ select $1 < $2 $$; - -CREATE FUNCTION mylt_noninline (text, text) RETURNS boolean LANGUAGE sql - AS $$ select $1 < $2 limit 1 $$; - -CREATE FUNCTION mylt_plpgsql (text, text) RETURNS boolean LANGUAGE plpgsql - AS $$ begin return $1 < $2; end $$; - -SELECT a.b AS a, b.b AS b, a.b < b.b AS lt, - mylt(a.b, b.b), mylt_noninline(a.b, b.b), mylt_plpgsql(a.b, b.b) -FROM collate_test1 a, collate_test1 b -ORDER BY a.b, b.b; - -SELECT a.b AS a, b.b AS b, a.b < b.b COLLATE "C" AS lt, - mylt(a.b, b.b COLLATE "C"), mylt_noninline(a.b, b.b COLLATE "C"), - mylt_plpgsql(a.b, b.b COLLATE "C") -FROM collate_test1 a, collate_test1 b -ORDER BY a.b, b.b; - - --- collation override in plpgsql - -CREATE FUNCTION mylt2 (x text, y text) RETURNS boolean LANGUAGE plpgsql AS $$ -declare - xx text := x; - yy text := y; -begin - return xx < yy; -end -$$; - -SELECT mylt2('a', 'B' collate "en-x-icu") as t, mylt2('a', 'B' collate "C") as f; - -CREATE OR REPLACE FUNCTION - mylt2 (x text, y text) RETURNS boolean LANGUAGE plpgsql AS $$ -declare - xx text COLLATE "POSIX" := x; - yy text := y; -begin - return xx < yy; -end -$$; - -SELECT mylt2('a', 'B') as f; -SELECT mylt2('a', 'B' collate "C") as fail; -- conflicting collations -SELECT mylt2('a', 'B' collate "POSIX") as f; - - --- polymorphism - -SELECT * FROM unnest((SELECT array_agg(b ORDER BY b) FROM collate_test1)) ORDER BY 1; -SELECT * FROM unnest((SELECT array_agg(b ORDER BY b) FROM collate_test2)) ORDER BY 1; -SELECT * FROM unnest((SELECT array_agg(b ORDER BY b) FROM collate_test3)) ORDER BY 1; - -CREATE FUNCTION dup (anyelement) RETURNS anyelement - AS 'select $1' LANGUAGE sql; - -SELECT a, dup(b) FROM collate_test1 ORDER BY 2; -SELECT a, dup(b) FROM collate_test2 ORDER BY 2; -SELECT a, dup(b) FROM collate_test3 ORDER BY 2; - - --- indexes - -CREATE INDEX collate_test1_idx1 ON collate_test1 (b); -CREATE INDEX collate_test1_idx2 ON collate_test1 (b COLLATE "C"); -CREATE INDEX collate_test1_idx3 ON collate_test1 ((b COLLATE "C")); -- this is different grammatically -CREATE INDEX collate_test1_idx4 ON collate_test1 (((b||'foo') COLLATE "POSIX")); - -CREATE INDEX collate_test1_idx5 ON collate_test1 (a COLLATE "C"); -- fail -CREATE INDEX collate_test1_idx6 ON collate_test1 ((a COLLATE "C")); -- fail - -SELECT relname, pg_get_indexdef(oid) FROM pg_class WHERE relname LIKE 'collate_test%_idx%' ORDER BY 1; - -set enable_seqscan = off; -explain (costs off) -select * from collate_test1 where b ilike 'abc'; -select * from collate_test1 where b ilike 'abc'; -explain (costs off) -select * from collate_test1 where b ilike 'ABC'; -select * from collate_test1 where b ilike 'ABC'; -reset enable_seqscan; - - --- schema manipulation commands - -CREATE ROLE regress_test_role; -CREATE SCHEMA test_schema; - --- We need to do this this way to cope with varying names for encodings: -do $$ -BEGIN - EXECUTE 'CREATE COLLATION test0 (provider = icu, locale = ' || - quote_literal(current_setting('lc_collate')) || ');'; -END -$$; -CREATE COLLATION test0 FROM "C"; -- fail, duplicate name -do $$ -BEGIN - EXECUTE 'CREATE COLLATION test1 (provider = icu, locale = ' || - quote_literal(current_setting('lc_collate')) || ');'; -END -$$; -CREATE COLLATION test3 (provider = icu, lc_collate = 'en_US.utf8'); -- fail, needs "locale" -CREATE COLLATION testx (provider = icu, locale = 'nonsense'); /* never fails with ICU */ DROP COLLATION testx; - -CREATE COLLATION test4 FROM nonsense; -CREATE COLLATION test5 FROM test0; - -SELECT collname FROM pg_collation WHERE collname LIKE 'test%' ORDER BY 1; - -ALTER COLLATION test1 RENAME TO test11; -ALTER COLLATION test0 RENAME TO test11; -- fail -ALTER COLLATION test1 RENAME TO test22; -- fail - -ALTER COLLATION test11 OWNER TO regress_test_role; -ALTER COLLATION test11 OWNER TO nonsense; -ALTER COLLATION test11 SET SCHEMA test_schema; - -COMMENT ON COLLATION test0 IS 'US English'; - -SELECT collname, nspname, obj_description(pg_collation.oid, 'pg_collation') - FROM pg_collation JOIN pg_namespace ON (collnamespace = pg_namespace.oid) - WHERE collname LIKE 'test%' - ORDER BY 1; - -DROP COLLATION test0, test_schema.test11, test5; -DROP COLLATION test0; -- fail -DROP COLLATION IF EXISTS test0; - -SELECT collname FROM pg_collation WHERE collname LIKE 'test%'; - -DROP SCHEMA test_schema; -DROP ROLE regress_test_role; - - --- ALTER - -ALTER COLLATION "en-x-icu" REFRESH VERSION; - --- also test for database while we are here -SELECT current_database() AS datname \gset -ALTER DATABASE :"datname" REFRESH COLLATION VERSION; - - --- dependencies - -CREATE COLLATION test0 FROM "C"; - -CREATE TABLE collate_dep_test1 (a int, b text COLLATE test0); -CREATE DOMAIN collate_dep_dom1 AS text COLLATE test0; -CREATE TYPE collate_dep_test2 AS (x int, y text COLLATE test0); -CREATE VIEW collate_dep_test3 AS SELECT text 'foo' COLLATE test0 AS foo; -CREATE TABLE collate_dep_test4t (a int, b text); -CREATE INDEX collate_dep_test4i ON collate_dep_test4t (b COLLATE test0); - -DROP COLLATION test0 RESTRICT; -- fail -DROP COLLATION test0 CASCADE; - -\d collate_dep_test1 -\d collate_dep_test2 - -DROP TABLE collate_dep_test1, collate_dep_test4t; -DROP TYPE collate_dep_test2; - --- test range types and collations - -create type textrange_c as range(subtype=text, collation="C"); -create type textrange_en_us as range(subtype=text, collation="en-x-icu"); - -select textrange_c('A','Z') @> 'b'::text; -select textrange_en_us('A','Z') @> 'b'::text; - -drop type textrange_c; -drop type textrange_en_us; - - --- test ICU collation customization - --- test the attributes handled by icu_set_collation_attributes() - -CREATE COLLATION testcoll_ignore_accents (provider = icu, locale = '@colStrength=primary;colCaseLevel=yes'); -SELECT 'aaá' > 'AAA' COLLATE "und-x-icu", 'aaá' < 'AAA' COLLATE testcoll_ignore_accents; - -CREATE COLLATION testcoll_backwards (provider = icu, locale = '@colBackwards=yes'); -SELECT 'coté' < 'côte' COLLATE "und-x-icu", 'coté' > 'côte' COLLATE testcoll_backwards; - -CREATE COLLATION testcoll_lower_first (provider = icu, locale = '@colCaseFirst=lower'); -CREATE COLLATION testcoll_upper_first (provider = icu, locale = '@colCaseFirst=upper'); -SELECT 'aaa' < 'AAA' COLLATE testcoll_lower_first, 'aaa' > 'AAA' COLLATE testcoll_upper_first; - -CREATE COLLATION testcoll_shifted (provider = icu, locale = '@colAlternate=shifted'); -SELECT 'de-luge' < 'deanza' COLLATE "und-x-icu", 'de-luge' > 'deanza' COLLATE testcoll_shifted; - -CREATE COLLATION testcoll_numeric (provider = icu, locale = '@colNumeric=yes'); -SELECT 'A-21' > 'A-123' COLLATE "und-x-icu", 'A-21' < 'A-123' COLLATE testcoll_numeric; - -CREATE COLLATION testcoll_error1 (provider = icu, locale = '@colNumeric=lower'); - --- test that attributes not handled by icu_set_collation_attributes() --- (handled by ucol_open() directly) also work -CREATE COLLATION testcoll_de_phonebook (provider = icu, locale = 'de@collation=phonebook'); -SELECT 'Goldmann' < 'Götz' COLLATE "de-x-icu", 'Goldmann' > 'Götz' COLLATE testcoll_de_phonebook; - - --- nondeterministic collations - -CREATE COLLATION ctest_det (provider = icu, locale = '', deterministic = true); -CREATE COLLATION ctest_nondet (provider = icu, locale = '', deterministic = false); - -CREATE TABLE test6 (a int, b text); --- same string in different normal forms -INSERT INTO test6 VALUES (1, U&'\00E4bc'); -INSERT INTO test6 VALUES (2, U&'\0061\0308bc'); -SELECT * FROM test6; -SELECT * FROM test6 WHERE b = 'äbc' COLLATE ctest_det; -SELECT * FROM test6 WHERE b = 'äbc' COLLATE ctest_nondet; - --- same with arrays -CREATE TABLE test6a (a int, b text[]); -INSERT INTO test6a VALUES (1, ARRAY[U&'\00E4bc']); -INSERT INTO test6a VALUES (2, ARRAY[U&'\0061\0308bc']); -SELECT * FROM test6a; -SELECT * FROM test6a WHERE b = ARRAY['äbc'] COLLATE ctest_det; -SELECT * FROM test6a WHERE b = ARRAY['äbc'] COLLATE ctest_nondet; - -CREATE COLLATION case_sensitive (provider = icu, locale = ''); -CREATE COLLATION case_insensitive (provider = icu, locale = '@colStrength=secondary', deterministic = false); - -SELECT 'abc' <= 'ABC' COLLATE case_sensitive, 'abc' >= 'ABC' COLLATE case_sensitive; -SELECT 'abc' <= 'ABC' COLLATE case_insensitive, 'abc' >= 'ABC' COLLATE case_insensitive; - -CREATE TABLE test1cs (x text COLLATE case_sensitive); -CREATE TABLE test2cs (x text COLLATE case_sensitive); -CREATE TABLE test3cs (x text COLLATE case_sensitive); -INSERT INTO test1cs VALUES ('abc'), ('def'), ('ghi'); -INSERT INTO test2cs VALUES ('ABC'), ('ghi'); -INSERT INTO test3cs VALUES ('abc'), ('ABC'), ('def'), ('ghi'); - -SELECT x FROM test3cs WHERE x = 'abc'; -SELECT x FROM test3cs WHERE x <> 'abc'; -SELECT x FROM test3cs WHERE x LIKE 'a%'; -SELECT x FROM test3cs WHERE x ILIKE 'a%'; -SELECT x FROM test3cs WHERE x SIMILAR TO 'a%'; -SELECT x FROM test3cs WHERE x ~ 'a'; -SELECT x FROM test1cs UNION SELECT x FROM test2cs ORDER BY x; -SELECT x FROM test2cs UNION SELECT x FROM test1cs ORDER BY x; -SELECT x FROM test1cs INTERSECT SELECT x FROM test2cs; -SELECT x FROM test2cs INTERSECT SELECT x FROM test1cs; -SELECT x FROM test1cs EXCEPT SELECT x FROM test2cs; -SELECT x FROM test2cs EXCEPT SELECT x FROM test1cs; -SELECT DISTINCT x FROM test3cs ORDER BY x; -SELECT count(DISTINCT x) FROM test3cs; -SELECT x, count(*) FROM test3cs GROUP BY x ORDER BY x; -SELECT x, row_number() OVER (ORDER BY x), rank() OVER (ORDER BY x) FROM test3cs ORDER BY x; -CREATE UNIQUE INDEX ON test1cs (x); -- ok -INSERT INTO test1cs VALUES ('ABC'); -- ok -CREATE UNIQUE INDEX ON test3cs (x); -- ok -SELECT string_to_array('ABC,DEF,GHI' COLLATE case_sensitive, ',', 'abc'); -SELECT string_to_array('ABCDEFGHI' COLLATE case_sensitive, NULL, 'b'); - -CREATE TABLE test1ci (x text COLLATE case_insensitive); -CREATE TABLE test2ci (x text COLLATE case_insensitive); -CREATE TABLE test3ci (x text COLLATE case_insensitive); -CREATE INDEX ON test3ci (x text_pattern_ops); -- error -INSERT INTO test1ci VALUES ('abc'), ('def'), ('ghi'); -INSERT INTO test2ci VALUES ('ABC'), ('ghi'); -INSERT INTO test3ci VALUES ('abc'), ('ABC'), ('def'), ('ghi'); - -SELECT x FROM test3ci WHERE x = 'abc'; -SELECT x FROM test3ci WHERE x <> 'abc'; -SELECT x FROM test3ci WHERE x LIKE 'a%'; -SELECT x FROM test3ci WHERE x ILIKE 'a%'; -SELECT x FROM test3ci WHERE x SIMILAR TO 'a%'; -SELECT x FROM test3ci WHERE x ~ 'a'; -SELECT x FROM test1ci UNION SELECT x FROM test2ci ORDER BY x; -SELECT x FROM test2ci UNION SELECT x FROM test1ci ORDER BY x; -SELECT x FROM test1ci INTERSECT SELECT x FROM test2ci ORDER BY x; -SELECT x FROM test2ci INTERSECT SELECT x FROM test1ci ORDER BY x; -SELECT x FROM test1ci EXCEPT SELECT x FROM test2ci; -SELECT x FROM test2ci EXCEPT SELECT x FROM test1ci; -SELECT DISTINCT x FROM test3ci ORDER BY x; -SELECT count(DISTINCT x) FROM test3ci; -SELECT x, count(*) FROM test3ci GROUP BY x ORDER BY x; -SELECT x, row_number() OVER (ORDER BY x), rank() OVER (ORDER BY x) FROM test3ci ORDER BY x; -CREATE UNIQUE INDEX ON test1ci (x); -- ok -INSERT INTO test1ci VALUES ('ABC'); -- error -CREATE UNIQUE INDEX ON test3ci (x); -- error -SELECT string_to_array('ABC,DEF,GHI' COLLATE case_insensitive, ',', 'abc'); -SELECT string_to_array('ABCDEFGHI' COLLATE case_insensitive, NULL, 'b'); - --- bpchar -CREATE TABLE test1bpci (x char(3) COLLATE case_insensitive); -CREATE TABLE test2bpci (x char(3) COLLATE case_insensitive); -CREATE TABLE test3bpci (x char(3) COLLATE case_insensitive); -CREATE INDEX ON test3bpci (x bpchar_pattern_ops); -- error -INSERT INTO test1bpci VALUES ('abc'), ('def'), ('ghi'); -INSERT INTO test2bpci VALUES ('ABC'), ('ghi'); -INSERT INTO test3bpci VALUES ('abc'), ('ABC'), ('def'), ('ghi'); - -SELECT x FROM test3bpci WHERE x = 'abc'; -SELECT x FROM test3bpci WHERE x <> 'abc'; -SELECT x FROM test3bpci WHERE x LIKE 'a%'; -SELECT x FROM test3bpci WHERE x ILIKE 'a%'; -SELECT x FROM test3bpci WHERE x SIMILAR TO 'a%'; -SELECT x FROM test3bpci WHERE x ~ 'a'; -SELECT x FROM test1bpci UNION SELECT x FROM test2bpci ORDER BY x; -SELECT x FROM test2bpci UNION SELECT x FROM test1bpci ORDER BY x; -SELECT x FROM test1bpci INTERSECT SELECT x FROM test2bpci ORDER BY x; -SELECT x FROM test2bpci INTERSECT SELECT x FROM test1bpci ORDER BY x; -SELECT x FROM test1bpci EXCEPT SELECT x FROM test2bpci; -SELECT x FROM test2bpci EXCEPT SELECT x FROM test1bpci; -SELECT DISTINCT x FROM test3bpci ORDER BY x; -SELECT count(DISTINCT x) FROM test3bpci; -SELECT x, count(*) FROM test3bpci GROUP BY x ORDER BY x; -SELECT x, row_number() OVER (ORDER BY x), rank() OVER (ORDER BY x) FROM test3bpci ORDER BY x; -CREATE UNIQUE INDEX ON test1bpci (x); -- ok -INSERT INTO test1bpci VALUES ('ABC'); -- error -CREATE UNIQUE INDEX ON test3bpci (x); -- error -SELECT string_to_array('ABC,DEF,GHI'::char(11) COLLATE case_insensitive, ',', 'abc'); -SELECT string_to_array('ABCDEFGHI'::char(9) COLLATE case_insensitive, NULL, 'b'); - --- This tests the issue described in match_pattern_prefix(). In the --- absence of that check, the case_insensitive tests below would --- return no rows where they should logically return one. -CREATE TABLE test4c (x text COLLATE "C"); -INSERT INTO test4c VALUES ('abc'); -CREATE INDEX ON test4c (x); -SET enable_seqscan = off; -SELECT x FROM test4c WHERE x LIKE 'ABC' COLLATE case_sensitive; -- ok, no rows -SELECT x FROM test4c WHERE x LIKE 'ABC%' COLLATE case_sensitive; -- ok, no rows -SELECT x FROM test4c WHERE x LIKE 'ABC' COLLATE case_insensitive; -- error -SELECT x FROM test4c WHERE x LIKE 'ABC%' COLLATE case_insensitive; -- error -RESET enable_seqscan; - --- Unicode special case: different variants of Greek lower case sigma. --- A naive implementation like citext that just does lower(x) = --- lower(y) will do the wrong thing here, because lower('Σ') is 'σ' --- but upper('ς') is 'Σ'. -SELECT 'ὀδυσσεύς' = 'ὈΔΥΣΣΕΎΣ' COLLATE case_sensitive; -SELECT 'ὀδυσσεύς' = 'ὈΔΥΣΣΕΎΣ' COLLATE case_insensitive; - --- name vs. text comparison operators -SELECT relname FROM pg_class WHERE relname = 'PG_CLASS'::text COLLATE case_insensitive; -SELECT relname FROM pg_class WHERE 'PG_CLASS'::text = relname COLLATE case_insensitive; - -SELECT typname FROM pg_type WHERE typname LIKE 'int_' AND typname <> 'INT2'::text - COLLATE case_insensitive ORDER BY typname; -SELECT typname FROM pg_type WHERE typname LIKE 'int_' AND 'INT2'::text <> typname - COLLATE case_insensitive ORDER BY typname; - --- test case adapted from subselect.sql -CREATE TEMP TABLE outer_text (f1 text COLLATE case_insensitive, f2 text); -INSERT INTO outer_text VALUES ('a', 'a'); -INSERT INTO outer_text VALUES ('b', 'a'); -INSERT INTO outer_text VALUES ('A', NULL); -INSERT INTO outer_text VALUES ('B', NULL); - -CREATE TEMP TABLE inner_text (c1 text COLLATE case_insensitive, c2 text); -INSERT INTO inner_text VALUES ('a', NULL); - -SELECT * FROM outer_text WHERE (f1, f2) NOT IN (SELECT * FROM inner_text); - --- accents -CREATE COLLATION ignore_accents (provider = icu, locale = '@colStrength=primary;colCaseLevel=yes', deterministic = false); - -CREATE TABLE test4 (a int, b text); -INSERT INTO test4 VALUES (1, 'cote'), (2, 'côte'), (3, 'coté'), (4, 'côté'); -SELECT * FROM test4 WHERE b = 'cote'; -SELECT * FROM test4 WHERE b = 'cote' COLLATE ignore_accents; -SELECT * FROM test4 WHERE b = 'Cote' COLLATE ignore_accents; -- still case-sensitive -SELECT * FROM test4 WHERE b = 'Cote' COLLATE case_insensitive; - --- foreign keys (should use collation of primary key) - --- PK is case-sensitive, FK is case-insensitive -CREATE TABLE test10pk (x text COLLATE case_sensitive PRIMARY KEY); -INSERT INTO test10pk VALUES ('abc'), ('def'), ('ghi'); -CREATE TABLE test10fk (x text COLLATE case_insensitive REFERENCES test10pk (x) ON UPDATE CASCADE ON DELETE CASCADE); -INSERT INTO test10fk VALUES ('abc'); -- ok -INSERT INTO test10fk VALUES ('ABC'); -- error -INSERT INTO test10fk VALUES ('xyz'); -- error -SELECT * FROM test10pk; -SELECT * FROM test10fk; --- restrict update even though the values are "equal" in the FK table -UPDATE test10fk SET x = 'ABC' WHERE x = 'abc'; -- error -SELECT * FROM test10fk; -DELETE FROM test10pk WHERE x = 'abc'; -SELECT * FROM test10pk; -SELECT * FROM test10fk; - --- PK is case-insensitive, FK is case-sensitive -CREATE TABLE test11pk (x text COLLATE case_insensitive PRIMARY KEY); -INSERT INTO test11pk VALUES ('abc'), ('def'), ('ghi'); -CREATE TABLE test11fk (x text COLLATE case_sensitive REFERENCES test11pk (x) ON UPDATE CASCADE ON DELETE CASCADE); -INSERT INTO test11fk VALUES ('abc'); -- ok -INSERT INTO test11fk VALUES ('ABC'); -- ok -INSERT INTO test11fk VALUES ('xyz'); -- error -SELECT * FROM test11pk; -SELECT * FROM test11fk; --- cascade update even though the values are "equal" in the PK table -UPDATE test11pk SET x = 'ABC' WHERE x = 'abc'; -SELECT * FROM test11fk; -DELETE FROM test11pk WHERE x = 'abc'; -SELECT * FROM test11pk; -SELECT * FROM test11fk; - --- partitioning -CREATE TABLE test20 (a int, b text COLLATE case_insensitive) PARTITION BY LIST (b); -CREATE TABLE test20_1 PARTITION OF test20 FOR VALUES IN ('abc'); -INSERT INTO test20 VALUES (1, 'abc'); -INSERT INTO test20 VALUES (2, 'ABC'); -SELECT * FROM test20_1; - -CREATE TABLE test21 (a int, b text COLLATE case_insensitive) PARTITION BY RANGE (b); -CREATE TABLE test21_1 PARTITION OF test21 FOR VALUES FROM ('ABC') TO ('DEF'); -INSERT INTO test21 VALUES (1, 'abc'); -INSERT INTO test21 VALUES (2, 'ABC'); -SELECT * FROM test21_1; - -CREATE TABLE test22 (a int, b text COLLATE case_sensitive) PARTITION BY HASH (b); -CREATE TABLE test22_0 PARTITION OF test22 FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE test22_1 PARTITION OF test22 FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO test22 VALUES (1, 'def'); -INSERT INTO test22 VALUES (2, 'DEF'); --- they end up in different partitions -SELECT (SELECT count(*) FROM test22_0) = (SELECT count(*) FROM test22_1); - --- same with arrays -CREATE TABLE test22a (a int, b text[] COLLATE case_sensitive) PARTITION BY HASH (b); -CREATE TABLE test22a_0 PARTITION OF test22a FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE test22a_1 PARTITION OF test22a FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO test22a VALUES (1, ARRAY['def']); -INSERT INTO test22a VALUES (2, ARRAY['DEF']); --- they end up in different partitions -SELECT (SELECT count(*) FROM test22a_0) = (SELECT count(*) FROM test22a_1); - -CREATE TABLE test23 (a int, b text COLLATE case_insensitive) PARTITION BY HASH (b); -CREATE TABLE test23_0 PARTITION OF test23 FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE test23_1 PARTITION OF test23 FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO test23 VALUES (1, 'def'); -INSERT INTO test23 VALUES (2, 'DEF'); --- they end up in the same partition (but it's platform-dependent which one) -SELECT (SELECT count(*) FROM test23_0) <> (SELECT count(*) FROM test23_1); - --- same with arrays -CREATE TABLE test23a (a int, b text[] COLLATE case_insensitive) PARTITION BY HASH (b); -CREATE TABLE test23a_0 PARTITION OF test23a FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE test23a_1 PARTITION OF test23a FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO test23a VALUES (1, ARRAY['def']); -INSERT INTO test23a VALUES (2, ARRAY['DEF']); --- they end up in the same partition (but it's platform-dependent which one) -SELECT (SELECT count(*) FROM test23a_0) <> (SELECT count(*) FROM test23a_1); - -CREATE TABLE test30 (a int, b char(3) COLLATE case_insensitive) PARTITION BY LIST (b); -CREATE TABLE test30_1 PARTITION OF test30 FOR VALUES IN ('abc'); -INSERT INTO test30 VALUES (1, 'abc'); -INSERT INTO test30 VALUES (2, 'ABC'); -SELECT * FROM test30_1; - -CREATE TABLE test31 (a int, b char(3) COLLATE case_insensitive) PARTITION BY RANGE (b); -CREATE TABLE test31_1 PARTITION OF test31 FOR VALUES FROM ('ABC') TO ('DEF'); -INSERT INTO test31 VALUES (1, 'abc'); -INSERT INTO test31 VALUES (2, 'ABC'); -SELECT * FROM test31_1; - -CREATE TABLE test32 (a int, b char(3) COLLATE case_sensitive) PARTITION BY HASH (b); -CREATE TABLE test32_0 PARTITION OF test32 FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE test32_1 PARTITION OF test32 FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO test32 VALUES (1, 'def'); -INSERT INTO test32 VALUES (2, 'DEF'); --- they end up in different partitions -SELECT (SELECT count(*) FROM test32_0) = (SELECT count(*) FROM test32_1); - -CREATE TABLE test33 (a int, b char(3) COLLATE case_insensitive) PARTITION BY HASH (b); -CREATE TABLE test33_0 PARTITION OF test33 FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE test33_1 PARTITION OF test33 FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO test33 VALUES (1, 'def'); -INSERT INTO test33 VALUES (2, 'DEF'); --- they end up in the same partition (but it's platform-dependent which one) -SELECT (SELECT count(*) FROM test33_0) <> (SELECT count(*) FROM test33_1); - - --- cleanup -RESET search_path; -SET client_min_messages TO warning; -DROP SCHEMA collate_tests CASCADE; -RESET client_min_messages; - --- leave a collation for pg_upgrade test -CREATE COLLATION coll_icu_upgrade FROM "und-x-icu"; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcollate.linux.utf8.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcollate.linux.utf8.sql deleted file mode 100644 index 0f6dd1b02e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcollate.linux.utf8.sql +++ /dev/null @@ -1,459 +0,0 @@ -/* - * This test is for Linux/glibc systems and assumes that a full set of - * locales is installed. It must be run in a database with UTF-8 encoding, - * because other encodings don't support all the characters used. - */ - -SELECT getdatabaseencoding() <> 'UTF8' OR - (SELECT count(*) FROM pg_collation WHERE collname IN ('de_DE', 'en_US', 'sv_SE', 'tr_TR') AND collencoding = pg_char_to_encoding('UTF8')) <> 4 OR - version() !~ 'linux-gnu' - AS skip_test \gset -\if :skip_test -\quit -\endif - -SET client_encoding TO UTF8; - -CREATE SCHEMA collate_tests; -SET search_path = collate_tests; - - -CREATE TABLE collate_test1 ( - a int, - b text COLLATE "en_US" NOT NULL -); - -\d collate_test1 - -CREATE TABLE collate_test_fail ( - a int, - b text COLLATE "ja_JP.eucjp" -); - -CREATE TABLE collate_test_fail ( - a int, - b text COLLATE "foo" -); - -CREATE TABLE collate_test_fail ( - a int COLLATE "en_US", - b text -); - -CREATE TABLE collate_test_like ( - LIKE collate_test1 -); - -\d collate_test_like - -CREATE TABLE collate_test2 ( - a int, - b text COLLATE "sv_SE" -); - -CREATE TABLE collate_test3 ( - a int, - b text COLLATE "C" -); - -INSERT INTO collate_test1 VALUES (1, 'abc'), (2, 'äbc'), (3, 'bbc'), (4, 'ABC'); -INSERT INTO collate_test2 SELECT * FROM collate_test1; -INSERT INTO collate_test3 SELECT * FROM collate_test1; - -SELECT * FROM collate_test1 WHERE b >= 'bbc'; -SELECT * FROM collate_test2 WHERE b >= 'bbc'; -SELECT * FROM collate_test3 WHERE b >= 'bbc'; -SELECT * FROM collate_test3 WHERE b >= 'BBC'; - -SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc'; -SELECT * FROM collate_test1 WHERE b >= 'bbc' COLLATE "C"; -SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc' COLLATE "C"; -SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc' COLLATE "en_US"; - - -CREATE DOMAIN testdomain_sv AS text COLLATE "sv_SE"; -CREATE DOMAIN testdomain_i AS int COLLATE "sv_SE"; -- fails -CREATE TABLE collate_test4 ( - a int, - b testdomain_sv -); -INSERT INTO collate_test4 SELECT * FROM collate_test1; -SELECT a, b FROM collate_test4 ORDER BY b; - -CREATE TABLE collate_test5 ( - a int, - b testdomain_sv COLLATE "en_US" -); -INSERT INTO collate_test5 SELECT * FROM collate_test1; -SELECT a, b FROM collate_test5 ORDER BY b; - - -SELECT a, b FROM collate_test1 ORDER BY b; -SELECT a, b FROM collate_test2 ORDER BY b; -SELECT a, b FROM collate_test3 ORDER BY b; - -SELECT a, b FROM collate_test1 ORDER BY b COLLATE "C"; - --- star expansion -SELECT * FROM collate_test1 ORDER BY b; -SELECT * FROM collate_test2 ORDER BY b; -SELECT * FROM collate_test3 ORDER BY b; - --- constant expression folding -SELECT 'bbc' COLLATE "en_US" > 'äbc' COLLATE "en_US" AS "true"; -SELECT 'bbc' COLLATE "sv_SE" > 'äbc' COLLATE "sv_SE" AS "false"; - --- upper/lower - -CREATE TABLE collate_test10 ( - a int, - x text COLLATE "en_US", - y text COLLATE "tr_TR" -); - -INSERT INTO collate_test10 VALUES (1, 'hij', 'hij'), (2, 'HIJ', 'HIJ'); - -SELECT a, lower(x), lower(y), upper(x), upper(y), initcap(x), initcap(y) FROM collate_test10; -SELECT a, lower(x COLLATE "C"), lower(y COLLATE "C") FROM collate_test10; - -SELECT a, x, y FROM collate_test10 ORDER BY lower(y), a; - --- LIKE/ILIKE - -SELECT * FROM collate_test1 WHERE b LIKE 'abc'; -SELECT * FROM collate_test1 WHERE b LIKE 'abc%'; -SELECT * FROM collate_test1 WHERE b LIKE '%bc%'; -SELECT * FROM collate_test1 WHERE b ILIKE 'abc'; -SELECT * FROM collate_test1 WHERE b ILIKE 'abc%'; -SELECT * FROM collate_test1 WHERE b ILIKE '%bc%'; - -SELECT 'Türkiye' COLLATE "en_US" ILIKE '%KI%' AS "true"; -SELECT 'Türkiye' COLLATE "tr_TR" ILIKE '%KI%' AS "false"; - -SELECT 'bıt' ILIKE 'BIT' COLLATE "en_US" AS "false"; -SELECT 'bıt' ILIKE 'BIT' COLLATE "tr_TR" AS "true"; - --- The following actually exercises the selectivity estimation for ILIKE. -SELECT relname FROM pg_class WHERE relname ILIKE 'abc%'; - --- regular expressions - -SELECT * FROM collate_test1 WHERE b ~ '^abc$'; -SELECT * FROM collate_test1 WHERE b ~ '^abc'; -SELECT * FROM collate_test1 WHERE b ~ 'bc'; -SELECT * FROM collate_test1 WHERE b ~* '^abc$'; -SELECT * FROM collate_test1 WHERE b ~* '^abc'; -SELECT * FROM collate_test1 WHERE b ~* 'bc'; - -CREATE TABLE collate_test6 ( - a int, - b text COLLATE "en_US" -); -INSERT INTO collate_test6 VALUES (1, 'abc'), (2, 'ABC'), (3, '123'), (4, 'ab1'), - (5, 'a1!'), (6, 'a c'), (7, '!.;'), (8, ' '), - (9, 'äbç'), (10, 'ÄBÇ'); -SELECT b, - b ~ '^[[:alpha:]]+$' AS is_alpha, - b ~ '^[[:upper:]]+$' AS is_upper, - b ~ '^[[:lower:]]+$' AS is_lower, - b ~ '^[[:digit:]]+$' AS is_digit, - b ~ '^[[:alnum:]]+$' AS is_alnum, - b ~ '^[[:graph:]]+$' AS is_graph, - b ~ '^[[:print:]]+$' AS is_print, - b ~ '^[[:punct:]]+$' AS is_punct, - b ~ '^[[:space:]]+$' AS is_space -FROM collate_test6; - -SELECT 'Türkiye' COLLATE "en_US" ~* 'KI' AS "true"; -SELECT 'Türkiye' COLLATE "tr_TR" ~* 'KI' AS "false"; - -SELECT 'bıt' ~* 'BIT' COLLATE "en_US" AS "false"; -SELECT 'bıt' ~* 'BIT' COLLATE "tr_TR" AS "true"; - --- The following actually exercises the selectivity estimation for ~*. -SELECT relname FROM pg_class WHERE relname ~* '^abc'; - - --- to_char - -SET lc_time TO 'tr_TR'; -SELECT to_char(date '2010-02-01', 'DD TMMON YYYY'); -SELECT to_char(date '2010-02-01', 'DD TMMON YYYY' COLLATE "tr_TR"); -SELECT to_char(date '2010-04-01', 'DD TMMON YYYY'); -SELECT to_char(date '2010-04-01', 'DD TMMON YYYY' COLLATE "tr_TR"); - --- to_date - -SELECT to_date('01 ŞUB 2010', 'DD TMMON YYYY'); -SELECT to_date('01 Şub 2010', 'DD TMMON YYYY'); -SELECT to_date('1234567890ab 2010', 'TMMONTH YYYY'); -- fail - - --- backwards parsing - -CREATE VIEW collview1 AS SELECT * FROM collate_test1 WHERE b COLLATE "C" >= 'bbc'; -CREATE VIEW collview2 AS SELECT a, b FROM collate_test1 ORDER BY b COLLATE "C"; -CREATE VIEW collview3 AS SELECT a, lower((x || x) COLLATE "C") FROM collate_test10; - -SELECT table_name, view_definition FROM information_schema.views - WHERE table_name LIKE 'collview%' ORDER BY 1; - - --- collation propagation in various expression types - -SELECT a, coalesce(b, 'foo') FROM collate_test1 ORDER BY 2; -SELECT a, coalesce(b, 'foo') FROM collate_test2 ORDER BY 2; -SELECT a, coalesce(b, 'foo') FROM collate_test3 ORDER BY 2; -SELECT a, lower(coalesce(x, 'foo')), lower(coalesce(y, 'foo')) FROM collate_test10; - -SELECT a, b, greatest(b, 'CCC') FROM collate_test1 ORDER BY 3; -SELECT a, b, greatest(b, 'CCC') FROM collate_test2 ORDER BY 3; -SELECT a, b, greatest(b, 'CCC') FROM collate_test3 ORDER BY 3; -SELECT a, x, y, lower(greatest(x, 'foo')), lower(greatest(y, 'foo')) FROM collate_test10; - -SELECT a, nullif(b, 'abc') FROM collate_test1 ORDER BY 2; -SELECT a, nullif(b, 'abc') FROM collate_test2 ORDER BY 2; -SELECT a, nullif(b, 'abc') FROM collate_test3 ORDER BY 2; -SELECT a, lower(nullif(x, 'foo')), lower(nullif(y, 'foo')) FROM collate_test10; - -SELECT a, CASE b WHEN 'abc' THEN 'abcd' ELSE b END FROM collate_test1 ORDER BY 2; -SELECT a, CASE b WHEN 'abc' THEN 'abcd' ELSE b END FROM collate_test2 ORDER BY 2; -SELECT a, CASE b WHEN 'abc' THEN 'abcd' ELSE b END FROM collate_test3 ORDER BY 2; - -CREATE DOMAIN testdomain AS text; -SELECT a, b::testdomain FROM collate_test1 ORDER BY 2; -SELECT a, b::testdomain FROM collate_test2 ORDER BY 2; -SELECT a, b::testdomain FROM collate_test3 ORDER BY 2; -SELECT a, b::testdomain_sv FROM collate_test3 ORDER BY 2; -SELECT a, lower(x::testdomain), lower(y::testdomain) FROM collate_test10; - -SELECT min(b), max(b) FROM collate_test1; -SELECT min(b), max(b) FROM collate_test2; -SELECT min(b), max(b) FROM collate_test3; - -SELECT array_agg(b ORDER BY b) FROM collate_test1; -SELECT array_agg(b ORDER BY b) FROM collate_test2; -SELECT array_agg(b ORDER BY b) FROM collate_test3; - -SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test1 ORDER BY 2; -SELECT a, b FROM collate_test2 UNION SELECT a, b FROM collate_test2 ORDER BY 2; -SELECT a, b FROM collate_test3 WHERE a < 4 INTERSECT SELECT a, b FROM collate_test3 WHERE a > 1 ORDER BY 2; -SELECT a, b FROM collate_test3 EXCEPT SELECT a, b FROM collate_test3 WHERE a < 2 ORDER BY 2; - -SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test3 ORDER BY 2; -- fail -SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test3; -- ok -SELECT a, b FROM collate_test1 UNION SELECT a, b FROM collate_test3 ORDER BY 2; -- fail -SELECT a, b COLLATE "C" FROM collate_test1 UNION SELECT a, b FROM collate_test3 ORDER BY 2; -- ok -SELECT a, b FROM collate_test1 INTERSECT SELECT a, b FROM collate_test3 ORDER BY 2; -- fail -SELECT a, b FROM collate_test1 EXCEPT SELECT a, b FROM collate_test3 ORDER BY 2; -- fail - -CREATE TABLE test_u AS SELECT a, b FROM collate_test1 UNION ALL SELECT a, b FROM collate_test3; -- fail - --- ideally this would be a parse-time error, but for now it must be run-time: -select x < y from collate_test10; -- fail -select x || y from collate_test10; -- ok, because || is not collation aware -select x, y from collate_test10 order by x || y; -- not so ok - --- collation mismatch between recursive and non-recursive term -WITH RECURSIVE foo(x) AS - (SELECT x FROM (VALUES('a' COLLATE "en_US"),('b')) t(x) - UNION ALL - SELECT (x || 'c') COLLATE "de_DE" FROM foo WHERE length(x) < 10) -SELECT * FROM foo; - - --- casting - -SELECT CAST('42' AS text COLLATE "C"); - -SELECT a, CAST(b AS varchar) FROM collate_test1 ORDER BY 2; -SELECT a, CAST(b AS varchar) FROM collate_test2 ORDER BY 2; -SELECT a, CAST(b AS varchar) FROM collate_test3 ORDER BY 2; - - --- propagation of collation in SQL functions (inlined and non-inlined cases) --- and plpgsql functions too - -CREATE FUNCTION mylt (text, text) RETURNS boolean LANGUAGE sql - AS $$ select $1 < $2 $$; - -CREATE FUNCTION mylt_noninline (text, text) RETURNS boolean LANGUAGE sql - AS $$ select $1 < $2 limit 1 $$; - -CREATE FUNCTION mylt_plpgsql (text, text) RETURNS boolean LANGUAGE plpgsql - AS $$ begin return $1 < $2; end $$; - -SELECT a.b AS a, b.b AS b, a.b < b.b AS lt, - mylt(a.b, b.b), mylt_noninline(a.b, b.b), mylt_plpgsql(a.b, b.b) -FROM collate_test1 a, collate_test1 b -ORDER BY a.b, b.b; - -SELECT a.b AS a, b.b AS b, a.b < b.b COLLATE "C" AS lt, - mylt(a.b, b.b COLLATE "C"), mylt_noninline(a.b, b.b COLLATE "C"), - mylt_plpgsql(a.b, b.b COLLATE "C") -FROM collate_test1 a, collate_test1 b -ORDER BY a.b, b.b; - - --- collation override in plpgsql - -CREATE FUNCTION mylt2 (x text, y text) RETURNS boolean LANGUAGE plpgsql AS $$ -declare - xx text := x; - yy text := y; -begin - return xx < yy; -end -$$; - -SELECT mylt2('a', 'B' collate "en_US") as t, mylt2('a', 'B' collate "C") as f; - -CREATE OR REPLACE FUNCTION - mylt2 (x text, y text) RETURNS boolean LANGUAGE plpgsql AS $$ -declare - xx text COLLATE "POSIX" := x; - yy text := y; -begin - return xx < yy; -end -$$; - -SELECT mylt2('a', 'B') as f; -SELECT mylt2('a', 'B' collate "C") as fail; -- conflicting collations -SELECT mylt2('a', 'B' collate "POSIX") as f; - - --- polymorphism - -SELECT * FROM unnest((SELECT array_agg(b ORDER BY b) FROM collate_test1)) ORDER BY 1; -SELECT * FROM unnest((SELECT array_agg(b ORDER BY b) FROM collate_test2)) ORDER BY 1; -SELECT * FROM unnest((SELECT array_agg(b ORDER BY b) FROM collate_test3)) ORDER BY 1; - -CREATE FUNCTION dup (anyelement) RETURNS anyelement - AS 'select $1' LANGUAGE sql; - -SELECT a, dup(b) FROM collate_test1 ORDER BY 2; -SELECT a, dup(b) FROM collate_test2 ORDER BY 2; -SELECT a, dup(b) FROM collate_test3 ORDER BY 2; - - --- indexes - -CREATE INDEX collate_test1_idx1 ON collate_test1 (b); -CREATE INDEX collate_test1_idx2 ON collate_test1 (b COLLATE "C"); -CREATE INDEX collate_test1_idx3 ON collate_test1 ((b COLLATE "C")); -- this is different grammatically -CREATE INDEX collate_test1_idx4 ON collate_test1 (((b||'foo') COLLATE "POSIX")); - -CREATE INDEX collate_test1_idx5 ON collate_test1 (a COLLATE "C"); -- fail -CREATE INDEX collate_test1_idx6 ON collate_test1 ((a COLLATE "C")); -- fail - -SELECT relname, pg_get_indexdef(oid) FROM pg_class WHERE relname LIKE 'collate_test%_idx%' ORDER BY 1; - - --- schema manipulation commands - -CREATE ROLE regress_test_role; -CREATE SCHEMA test_schema; - --- We need to do this this way to cope with varying names for encodings: -do $$ -BEGIN - EXECUTE 'CREATE COLLATION test0 (locale = ' || - quote_literal(current_setting('lc_collate')) || ');'; -END -$$; -CREATE COLLATION test0 FROM "C"; -- fail, duplicate name -CREATE COLLATION IF NOT EXISTS test0 FROM "C"; -- ok, skipped -CREATE COLLATION IF NOT EXISTS test0 (locale = 'foo'); -- ok, skipped -do $$ -BEGIN - EXECUTE 'CREATE COLLATION test1 (lc_collate = ' || - quote_literal(current_setting('lc_collate')) || - ', lc_ctype = ' || - quote_literal(current_setting('lc_ctype')) || ');'; -END -$$; -CREATE COLLATION test3 (lc_collate = 'en_US.utf8'); -- fail, need lc_ctype -CREATE COLLATION testx (locale = 'nonsense'); -- fail - -CREATE COLLATION test4 FROM nonsense; -CREATE COLLATION test5 FROM test0; - -SELECT collname FROM pg_collation WHERE collname LIKE 'test%' ORDER BY 1; - -ALTER COLLATION test1 RENAME TO test11; -ALTER COLLATION test0 RENAME TO test11; -- fail -ALTER COLLATION test1 RENAME TO test22; -- fail - -ALTER COLLATION test11 OWNER TO regress_test_role; -ALTER COLLATION test11 OWNER TO nonsense; -ALTER COLLATION test11 SET SCHEMA test_schema; - -COMMENT ON COLLATION test0 IS 'US English'; - -SELECT collname, nspname, obj_description(pg_collation.oid, 'pg_collation') - FROM pg_collation JOIN pg_namespace ON (collnamespace = pg_namespace.oid) - WHERE collname LIKE 'test%' - ORDER BY 1; - -DROP COLLATION test0, test_schema.test11, test5; -DROP COLLATION test0; -- fail -DROP COLLATION IF EXISTS test0; - -SELECT collname FROM pg_collation WHERE collname LIKE 'test%'; - -DROP SCHEMA test_schema; -DROP ROLE regress_test_role; - - --- ALTER - -ALTER COLLATION "en_US" REFRESH VERSION; - --- also test for database while we are here -SELECT current_database() AS datname \gset -ALTER DATABASE :"datname" REFRESH COLLATION VERSION; - - --- dependencies - -CREATE COLLATION test0 FROM "C"; - -CREATE TABLE collate_dep_test1 (a int, b text COLLATE test0); -CREATE DOMAIN collate_dep_dom1 AS text COLLATE test0; -CREATE TYPE collate_dep_test2 AS (x int, y text COLLATE test0); -CREATE VIEW collate_dep_test3 AS SELECT text 'foo' COLLATE test0 AS foo; -CREATE TABLE collate_dep_test4t (a int, b text); -CREATE INDEX collate_dep_test4i ON collate_dep_test4t (b COLLATE test0); - -DROP COLLATION test0 RESTRICT; -- fail -DROP COLLATION test0 CASCADE; - -\d collate_dep_test1 -\d collate_dep_test2 - -DROP TABLE collate_dep_test1, collate_dep_test4t; -DROP TYPE collate_dep_test2; - --- test range types and collations - -create type textrange_c as range(subtype=text, collation="C"); -create type textrange_en_us as range(subtype=text, collation="en_US"); - -select textrange_c('A','Z') @> 'b'::text; -select textrange_en_us('A','Z') @> 'b'::text; - -drop type textrange_c; -drop type textrange_en_us; - - --- nondeterministic collations --- (not supported with libc provider) - -CREATE COLLATION ctest_det (locale = 'en_US.utf8', deterministic = true); -CREATE COLLATION ctest_nondet (locale = 'en_US.utf8', deterministic = false); - - --- cleanup -SET client_min_messages TO warning; -DROP SCHEMA collate_tests CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcombocid.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcombocid.sql deleted file mode 100644 index a5cdf6dba2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcombocid.sql +++ /dev/null @@ -1,111 +0,0 @@ --- --- Tests for some likely failure cases with combo cmin/cmax mechanism --- -CREATE TEMP TABLE combocidtest (foobar int); - -BEGIN; - --- a few dummy ops to push up the CommandId counter -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; - -INSERT INTO combocidtest VALUES (1); -INSERT INTO combocidtest VALUES (2); - -SELECT ctid,cmin,* FROM combocidtest; - -SAVEPOINT s1; - -UPDATE combocidtest SET foobar = foobar + 10; - --- here we should see only updated tuples -SELECT ctid,cmin,* FROM combocidtest; - -ROLLBACK TO s1; - --- now we should see old tuples, but with combo CIDs starting at 0 -SELECT ctid,cmin,* FROM combocidtest; - -COMMIT; - --- combo data is not there anymore, but should still see tuples -SELECT ctid,cmin,* FROM combocidtest; - --- Test combo CIDs with portals -BEGIN; - -INSERT INTO combocidtest VALUES (333); - -DECLARE c CURSOR FOR SELECT ctid,cmin,* FROM combocidtest; - -DELETE FROM combocidtest; - -FETCH ALL FROM c; - -ROLLBACK; - -SELECT ctid,cmin,* FROM combocidtest; - --- check behavior with locked tuples -BEGIN; - --- a few dummy ops to push up the CommandId counter -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; -INSERT INTO combocidtest SELECT 1 LIMIT 0; - -INSERT INTO combocidtest VALUES (444); - -SELECT ctid,cmin,* FROM combocidtest; - -SAVEPOINT s1; - --- this doesn't affect cmin -SELECT ctid,cmin,* FROM combocidtest FOR UPDATE; -SELECT ctid,cmin,* FROM combocidtest; - --- but this does -UPDATE combocidtest SET foobar = foobar + 10; - -SELECT ctid,cmin,* FROM combocidtest; - -ROLLBACK TO s1; - -SELECT ctid,cmin,* FROM combocidtest; - -COMMIT; - -SELECT ctid,cmin,* FROM combocidtest; - --- test for bug reported in --- CABRT9RC81YUf1=jsmWopcKJEro=VoeG2ou6sPwyOUTx_qteRsg@mail.gmail.com -CREATE TABLE IF NOT EXISTS testcase( - id int PRIMARY KEY, - balance numeric -); -INSERT INTO testcase VALUES (1, 0); -BEGIN; -SELECT * FROM testcase WHERE testcase.id = 1 FOR UPDATE; -UPDATE testcase SET balance = balance + 400 WHERE id=1; -SAVEPOINT subxact; -UPDATE testcase SET balance = balance - 100 WHERE id=1; -ROLLBACK TO SAVEPOINT subxact; --- should return one tuple -SELECT * FROM testcase WHERE id = 1 FOR UPDATE; -ROLLBACK; -DROP TABLE testcase; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fconstraints.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fconstraints.sql deleted file mode 100644 index 34de0c969a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fconstraints.sql +++ /dev/null @@ -1,573 +0,0 @@ --- --- CONSTRAINTS --- Constraints can be specified with: --- - DEFAULT clause --- - CHECK clauses --- - PRIMARY KEY clauses --- - UNIQUE clauses --- - EXCLUDE clauses --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - --- --- DEFAULT syntax --- - -CREATE TABLE DEFAULT_TBL (i int DEFAULT 100, - x text DEFAULT 'vadim', f float8 DEFAULT 123.456); - -INSERT INTO DEFAULT_TBL VALUES (1, 'thomas', 57.0613); -INSERT INTO DEFAULT_TBL VALUES (1, 'bruce'); -INSERT INTO DEFAULT_TBL (i, f) VALUES (2, 987.654); -INSERT INTO DEFAULT_TBL (x) VALUES ('marc'); -INSERT INTO DEFAULT_TBL VALUES (3, null, 1.0); - -SELECT * FROM DEFAULT_TBL; - -CREATE SEQUENCE DEFAULT_SEQ; - -CREATE TABLE DEFAULTEXPR_TBL (i1 int DEFAULT 100 + (200-199) * 2, - i2 int DEFAULT nextval('default_seq')); - -INSERT INTO DEFAULTEXPR_TBL VALUES (-1, -2); -INSERT INTO DEFAULTEXPR_TBL (i1) VALUES (-3); -INSERT INTO DEFAULTEXPR_TBL (i2) VALUES (-4); -INSERT INTO DEFAULTEXPR_TBL (i2) VALUES (NULL); - -SELECT * FROM DEFAULTEXPR_TBL; - --- syntax errors --- test for extraneous comma -CREATE TABLE error_tbl (i int DEFAULT (100, )); --- this will fail because gram.y uses b_expr not a_expr for defaults, --- to avoid a shift/reduce conflict that arises from NOT NULL being --- part of the column definition syntax: -CREATE TABLE error_tbl (b1 bool DEFAULT 1 IN (1, 2)); --- this should work, however: -CREATE TABLE error_tbl (b1 bool DEFAULT (1 IN (1, 2))); - -DROP TABLE error_tbl; - --- --- CHECK syntax --- - -CREATE TABLE CHECK_TBL (x int, - CONSTRAINT CHECK_CON CHECK (x > 3)); - -INSERT INTO CHECK_TBL VALUES (5); -INSERT INTO CHECK_TBL VALUES (4); -INSERT INTO CHECK_TBL VALUES (3); -INSERT INTO CHECK_TBL VALUES (2); -INSERT INTO CHECK_TBL VALUES (6); -INSERT INTO CHECK_TBL VALUES (1); - -SELECT * FROM CHECK_TBL; - -CREATE SEQUENCE CHECK_SEQ; - -CREATE TABLE CHECK2_TBL (x int, y text, z int, - CONSTRAINT SEQUENCE_CON - CHECK (x > 3 and y <> 'check failed' and z < 8)); - -INSERT INTO CHECK2_TBL VALUES (4, 'check ok', -2); -INSERT INTO CHECK2_TBL VALUES (1, 'x check failed', -2); -INSERT INTO CHECK2_TBL VALUES (5, 'z check failed', 10); -INSERT INTO CHECK2_TBL VALUES (0, 'check failed', -2); -INSERT INTO CHECK2_TBL VALUES (6, 'check failed', 11); -INSERT INTO CHECK2_TBL VALUES (7, 'check ok', 7); - -SELECT * from CHECK2_TBL; - --- --- Check constraints on INSERT --- - -CREATE SEQUENCE INSERT_SEQ; - -CREATE TABLE INSERT_TBL (x INT DEFAULT nextval('insert_seq'), - y TEXT DEFAULT '-NULL-', - z INT DEFAULT -1 * currval('insert_seq'), - CONSTRAINT INSERT_TBL_CON CHECK (x >= 3 AND y <> 'check failed' AND x < 8), - CHECK (x + z = 0)); - -INSERT INTO INSERT_TBL(x,z) VALUES (2, -2); - -SELECT * FROM INSERT_TBL; - -SELECT 'one' AS one, nextval('insert_seq'); - -INSERT INTO INSERT_TBL(y) VALUES ('Y'); -INSERT INTO INSERT_TBL(y) VALUES ('Y'); -INSERT INTO INSERT_TBL(x,z) VALUES (1, -2); -INSERT INTO INSERT_TBL(z,x) VALUES (-7, 7); -INSERT INTO INSERT_TBL VALUES (5, 'check failed', -5); -INSERT INTO INSERT_TBL VALUES (7, '!check failed', -7); -INSERT INTO INSERT_TBL(y) VALUES ('-!NULL-'); - -SELECT * FROM INSERT_TBL; - -INSERT INTO INSERT_TBL(y,z) VALUES ('check failed', 4); -INSERT INTO INSERT_TBL(x,y) VALUES (5, 'check failed'); -INSERT INTO INSERT_TBL(x,y) VALUES (5, '!check failed'); -INSERT INTO INSERT_TBL(y) VALUES ('-!NULL-'); - -SELECT * FROM INSERT_TBL; - -SELECT 'seven' AS one, nextval('insert_seq'); - -INSERT INTO INSERT_TBL(y) VALUES ('Y'); - -SELECT 'eight' AS one, currval('insert_seq'); - --- According to SQL, it is OK to insert a record that gives rise to NULL --- constraint-condition results. Postgres used to reject this, but it --- was wrong: -INSERT INTO INSERT_TBL VALUES (null, null, null); - -SELECT * FROM INSERT_TBL; - --- --- Check constraints on system columns --- - -CREATE TABLE SYS_COL_CHECK_TBL (city text, state text, is_capital bool, - altitude int, - CHECK (NOT (is_capital AND tableoid::regclass::text = 'sys_col_check_tbl'))); - -INSERT INTO SYS_COL_CHECK_TBL VALUES ('Seattle', 'Washington', false, 100); -INSERT INTO SYS_COL_CHECK_TBL VALUES ('Olympia', 'Washington', true, 100); - -SELECT *, tableoid::regclass::text FROM SYS_COL_CHECK_TBL; - -DROP TABLE SYS_COL_CHECK_TBL; - --- --- Check constraints on system columns other then TableOid should return error --- -CREATE TABLE SYS_COL_CHECK_TBL (city text, state text, is_capital bool, - altitude int, - CHECK (NOT (is_capital AND ctid::text = 'sys_col_check_tbl'))); - --- --- Check inheritance of defaults and constraints --- - -CREATE TABLE INSERT_CHILD (cx INT default 42, - cy INT CHECK (cy > x)) - INHERITS (INSERT_TBL); - -INSERT INTO INSERT_CHILD(x,z,cy) VALUES (7,-7,11); -INSERT INTO INSERT_CHILD(x,z,cy) VALUES (7,-7,6); -INSERT INTO INSERT_CHILD(x,z,cy) VALUES (6,-7,7); -INSERT INTO INSERT_CHILD(x,y,z,cy) VALUES (6,'check failed',-6,7); - -SELECT * FROM INSERT_CHILD; - -DROP TABLE INSERT_CHILD; - --- --- Check NO INHERIT type of constraints and inheritance --- - -CREATE TABLE ATACC1 (TEST INT - CHECK (TEST > 0) NO INHERIT); - -CREATE TABLE ATACC2 (TEST2 INT) INHERITS (ATACC1); --- check constraint is not there on child -INSERT INTO ATACC2 (TEST) VALUES (-3); --- check constraint is there on parent -INSERT INTO ATACC1 (TEST) VALUES (-3); -DROP TABLE ATACC1 CASCADE; - -CREATE TABLE ATACC1 (TEST INT, TEST2 INT - CHECK (TEST > 0), CHECK (TEST2 > 10) NO INHERIT); - -CREATE TABLE ATACC2 () INHERITS (ATACC1); --- check constraint is there on child -INSERT INTO ATACC2 (TEST) VALUES (-3); --- check constraint is there on parent -INSERT INTO ATACC1 (TEST) VALUES (-3); --- check constraint is not there on child -INSERT INTO ATACC2 (TEST2) VALUES (3); --- check constraint is there on parent -INSERT INTO ATACC1 (TEST2) VALUES (3); -DROP TABLE ATACC1 CASCADE; - --- --- Check constraints on INSERT INTO --- - -DELETE FROM INSERT_TBL; - -ALTER SEQUENCE INSERT_SEQ RESTART WITH 4; - -CREATE TEMP TABLE tmp (xd INT, yd TEXT, zd INT); - -INSERT INTO tmp VALUES (null, 'Y', null); -INSERT INTO tmp VALUES (5, '!check failed', null); -INSERT INTO tmp VALUES (null, 'try again', null); -INSERT INTO INSERT_TBL(y) select yd from tmp; - -SELECT * FROM INSERT_TBL; - -INSERT INTO INSERT_TBL SELECT * FROM tmp WHERE yd = 'try again'; -INSERT INTO INSERT_TBL(y,z) SELECT yd, -7 FROM tmp WHERE yd = 'try again'; -INSERT INTO INSERT_TBL(y,z) SELECT yd, -8 FROM tmp WHERE yd = 'try again'; - -SELECT * FROM INSERT_TBL; - -DROP TABLE tmp; - --- --- Check constraints on UPDATE --- - -UPDATE INSERT_TBL SET x = NULL WHERE x = 5; -UPDATE INSERT_TBL SET x = 6 WHERE x = 6; -UPDATE INSERT_TBL SET x = -z, z = -x; -UPDATE INSERT_TBL SET x = z, z = x; - -SELECT * FROM INSERT_TBL; - --- DROP TABLE INSERT_TBL; - --- --- Check constraints on COPY FROM --- - -CREATE TABLE COPY_TBL (x INT, y TEXT, z INT, - CONSTRAINT COPY_CON - CHECK (x > 3 AND y <> 'check failed' AND x < 7 )); - -\set filename :abs_srcdir '/data/constro.data' -COPY COPY_TBL FROM :'filename'; - -SELECT * FROM COPY_TBL; - -\set filename :abs_srcdir '/data/constrf.data' -COPY COPY_TBL FROM :'filename'; - -SELECT * FROM COPY_TBL; - --- --- Primary keys --- - -CREATE TABLE PRIMARY_TBL (i int PRIMARY KEY, t text); - -INSERT INTO PRIMARY_TBL VALUES (1, 'one'); -INSERT INTO PRIMARY_TBL VALUES (2, 'two'); -INSERT INTO PRIMARY_TBL VALUES (1, 'three'); -INSERT INTO PRIMARY_TBL VALUES (4, 'three'); -INSERT INTO PRIMARY_TBL VALUES (5, 'one'); -INSERT INTO PRIMARY_TBL (t) VALUES ('six'); - -SELECT * FROM PRIMARY_TBL; - -DROP TABLE PRIMARY_TBL; - -CREATE TABLE PRIMARY_TBL (i int, t text, - PRIMARY KEY(i,t)); - -INSERT INTO PRIMARY_TBL VALUES (1, 'one'); -INSERT INTO PRIMARY_TBL VALUES (2, 'two'); -INSERT INTO PRIMARY_TBL VALUES (1, 'three'); -INSERT INTO PRIMARY_TBL VALUES (4, 'three'); -INSERT INTO PRIMARY_TBL VALUES (5, 'one'); -INSERT INTO PRIMARY_TBL (t) VALUES ('six'); - -SELECT * FROM PRIMARY_TBL; - -DROP TABLE PRIMARY_TBL; - --- --- Unique keys --- - -CREATE TABLE UNIQUE_TBL (i int UNIQUE, t text); - -INSERT INTO UNIQUE_TBL VALUES (1, 'one'); -INSERT INTO UNIQUE_TBL VALUES (2, 'two'); -INSERT INTO UNIQUE_TBL VALUES (1, 'three'); -INSERT INTO UNIQUE_TBL VALUES (4, 'four'); -INSERT INTO UNIQUE_TBL VALUES (5, 'one'); -INSERT INTO UNIQUE_TBL (t) VALUES ('six'); -INSERT INTO UNIQUE_TBL (t) VALUES ('seven'); - -INSERT INTO UNIQUE_TBL VALUES (5, 'five-upsert-insert') ON CONFLICT (i) DO UPDATE SET t = 'five-upsert-update'; -INSERT INTO UNIQUE_TBL VALUES (6, 'six-upsert-insert') ON CONFLICT (i) DO UPDATE SET t = 'six-upsert-update'; --- should fail -INSERT INTO UNIQUE_TBL VALUES (1, 'a'), (2, 'b'), (2, 'b') ON CONFLICT (i) DO UPDATE SET t = 'fails'; - -SELECT * FROM UNIQUE_TBL; - -DROP TABLE UNIQUE_TBL; - -CREATE TABLE UNIQUE_TBL (i int UNIQUE NULLS NOT DISTINCT, t text); - -INSERT INTO UNIQUE_TBL VALUES (1, 'one'); -INSERT INTO UNIQUE_TBL VALUES (2, 'two'); -INSERT INTO UNIQUE_TBL VALUES (1, 'three'); -INSERT INTO UNIQUE_TBL VALUES (4, 'four'); -INSERT INTO UNIQUE_TBL VALUES (5, 'one'); -INSERT INTO UNIQUE_TBL (t) VALUES ('six'); -INSERT INTO UNIQUE_TBL (t) VALUES ('seven'); - -SELECT * FROM UNIQUE_TBL; - -DROP TABLE UNIQUE_TBL; - -CREATE TABLE UNIQUE_TBL (i int, t text, - UNIQUE(i,t)); - -INSERT INTO UNIQUE_TBL VALUES (1, 'one'); -INSERT INTO UNIQUE_TBL VALUES (2, 'two'); -INSERT INTO UNIQUE_TBL VALUES (1, 'three'); -INSERT INTO UNIQUE_TBL VALUES (1, 'one'); -INSERT INTO UNIQUE_TBL VALUES (5, 'one'); -INSERT INTO UNIQUE_TBL (t) VALUES ('six'); - -SELECT * FROM UNIQUE_TBL; - -DROP TABLE UNIQUE_TBL; - --- --- Deferrable unique constraints --- - -CREATE TABLE unique_tbl (i int UNIQUE DEFERRABLE, t text); - -INSERT INTO unique_tbl VALUES (0, 'one'); -INSERT INTO unique_tbl VALUES (1, 'two'); -INSERT INTO unique_tbl VALUES (2, 'tree'); -INSERT INTO unique_tbl VALUES (3, 'four'); -INSERT INTO unique_tbl VALUES (4, 'five'); - -BEGIN; - --- default is immediate so this should fail right away -UPDATE unique_tbl SET i = 1 WHERE i = 0; - -ROLLBACK; - --- check is done at end of statement, so this should succeed -UPDATE unique_tbl SET i = i+1; - -SELECT * FROM unique_tbl; - --- explicitly defer the constraint -BEGIN; - -SET CONSTRAINTS unique_tbl_i_key DEFERRED; - -INSERT INTO unique_tbl VALUES (3, 'three'); -DELETE FROM unique_tbl WHERE t = 'tree'; -- makes constraint valid again - -COMMIT; -- should succeed - -SELECT * FROM unique_tbl; - --- try adding an initially deferred constraint -ALTER TABLE unique_tbl DROP CONSTRAINT unique_tbl_i_key; -ALTER TABLE unique_tbl ADD CONSTRAINT unique_tbl_i_key - UNIQUE (i) DEFERRABLE INITIALLY DEFERRED; - -BEGIN; - -INSERT INTO unique_tbl VALUES (1, 'five'); -INSERT INTO unique_tbl VALUES (5, 'one'); -UPDATE unique_tbl SET i = 4 WHERE i = 2; -UPDATE unique_tbl SET i = 2 WHERE i = 4 AND t = 'four'; -DELETE FROM unique_tbl WHERE i = 1 AND t = 'one'; -DELETE FROM unique_tbl WHERE i = 5 AND t = 'five'; - -COMMIT; - -SELECT * FROM unique_tbl; - --- should fail at commit-time -BEGIN; -INSERT INTO unique_tbl VALUES (3, 'Three'); -- should succeed for now -COMMIT; -- should fail - --- make constraint check immediate -BEGIN; - -SET CONSTRAINTS ALL IMMEDIATE; - -INSERT INTO unique_tbl VALUES (3, 'Three'); -- should fail - -COMMIT; - --- forced check when SET CONSTRAINTS is called -BEGIN; - -SET CONSTRAINTS ALL DEFERRED; - -INSERT INTO unique_tbl VALUES (3, 'Three'); -- should succeed for now - -SET CONSTRAINTS ALL IMMEDIATE; -- should fail - -COMMIT; - --- test deferrable UNIQUE with a partitioned table -CREATE TABLE parted_uniq_tbl (i int UNIQUE DEFERRABLE) partition by range (i); -CREATE TABLE parted_uniq_tbl_1 PARTITION OF parted_uniq_tbl FOR VALUES FROM (0) TO (10); -CREATE TABLE parted_uniq_tbl_2 PARTITION OF parted_uniq_tbl FOR VALUES FROM (20) TO (30); -SELECT conname, conrelid::regclass FROM pg_constraint - WHERE conname LIKE 'parted_uniq%' ORDER BY conname; -BEGIN; -INSERT INTO parted_uniq_tbl VALUES (1); -SAVEPOINT f; -INSERT INTO parted_uniq_tbl VALUES (1); -- unique violation -ROLLBACK TO f; -SET CONSTRAINTS parted_uniq_tbl_i_key DEFERRED; -INSERT INTO parted_uniq_tbl VALUES (1); -- OK now, fail at commit -COMMIT; -DROP TABLE parted_uniq_tbl; - --- test a HOT update that invalidates the conflicting tuple. --- the trigger should still fire and catch the violation - -BEGIN; - -INSERT INTO unique_tbl VALUES (3, 'Three'); -- should succeed for now -UPDATE unique_tbl SET t = 'THREE' WHERE i = 3 AND t = 'Three'; - -COMMIT; -- should fail - -SELECT * FROM unique_tbl; - --- test a HOT update that modifies the newly inserted tuple, --- but should succeed because we then remove the other conflicting tuple. - -BEGIN; - -INSERT INTO unique_tbl VALUES(3, 'tree'); -- should succeed for now -UPDATE unique_tbl SET t = 'threex' WHERE t = 'tree'; -DELETE FROM unique_tbl WHERE t = 'three'; - -SELECT * FROM unique_tbl; - -COMMIT; - -SELECT * FROM unique_tbl; - -DROP TABLE unique_tbl; - --- --- EXCLUDE constraints --- - -CREATE TABLE circles ( - c1 CIRCLE, - c2 TEXT, - EXCLUDE USING gist - (c1 WITH &&, (c2::circle) WITH &&) - WHERE (circle_center(c1) <> '(0,0)') -); - --- these should succeed because they don't match the index predicate -INSERT INTO circles VALUES('<(0,0), 5>', '<(0,0), 5>'); -INSERT INTO circles VALUES('<(0,0), 5>', '<(0,0), 4>'); - --- succeed -INSERT INTO circles VALUES('<(10,10), 10>', '<(0,0), 5>'); --- fail, overlaps -INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>'); --- succeed, because violation is ignored -INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>') - ON CONFLICT ON CONSTRAINT circles_c1_c2_excl DO NOTHING; --- fail, because DO UPDATE variant requires unique index -INSERT INTO circles VALUES('<(20,20), 10>', '<(0,0), 4>') - ON CONFLICT ON CONSTRAINT circles_c1_c2_excl DO UPDATE SET c2 = EXCLUDED.c2; --- succeed because c1 doesn't overlap -INSERT INTO circles VALUES('<(20,20), 1>', '<(0,0), 5>'); --- succeed because c2 doesn't overlap -INSERT INTO circles VALUES('<(20,20), 10>', '<(10,10), 5>'); - --- should fail on existing data without the WHERE clause -ALTER TABLE circles ADD EXCLUDE USING gist - (c1 WITH &&, (c2::circle) WITH &&); - --- try reindexing an existing constraint -REINDEX INDEX circles_c1_c2_excl; - -DROP TABLE circles; - --- Check deferred exclusion constraint - -CREATE TABLE deferred_excl ( - f1 int, - f2 int, - CONSTRAINT deferred_excl_con EXCLUDE (f1 WITH =) INITIALLY DEFERRED -); - -INSERT INTO deferred_excl VALUES(1); -INSERT INTO deferred_excl VALUES(2); -INSERT INTO deferred_excl VALUES(1); -- fail -INSERT INTO deferred_excl VALUES(1) ON CONFLICT ON CONSTRAINT deferred_excl_con DO NOTHING; -- fail -BEGIN; -INSERT INTO deferred_excl VALUES(2); -- no fail here -COMMIT; -- should fail here -BEGIN; -INSERT INTO deferred_excl VALUES(3); -INSERT INTO deferred_excl VALUES(3); -- no fail here -COMMIT; -- should fail here - --- bug #13148: deferred constraint versus HOT update -BEGIN; -INSERT INTO deferred_excl VALUES(2, 1); -- no fail here -DELETE FROM deferred_excl WHERE f1 = 2 AND f2 IS NULL; -- remove old row -UPDATE deferred_excl SET f2 = 2 WHERE f1 = 2; -COMMIT; -- should not fail - -SELECT * FROM deferred_excl; - -ALTER TABLE deferred_excl DROP CONSTRAINT deferred_excl_con; - --- This should fail, but worth testing because of HOT updates -UPDATE deferred_excl SET f1 = 3; - -ALTER TABLE deferred_excl ADD EXCLUDE (f1 WITH =); - -DROP TABLE deferred_excl; - --- Comments --- Setup a low-level role to enforce non-superuser checks. -CREATE ROLE regress_constraint_comments; -SET SESSION AUTHORIZATION regress_constraint_comments; - -CREATE TABLE constraint_comments_tbl (a int CONSTRAINT the_constraint CHECK (a > 0)); -CREATE DOMAIN constraint_comments_dom AS int CONSTRAINT the_constraint CHECK (value > 0); - -COMMENT ON CONSTRAINT the_constraint ON constraint_comments_tbl IS 'yes, the comment'; -COMMENT ON CONSTRAINT the_constraint ON DOMAIN constraint_comments_dom IS 'yes, another comment'; - --- no such constraint -COMMENT ON CONSTRAINT no_constraint ON constraint_comments_tbl IS 'yes, the comment'; -COMMENT ON CONSTRAINT no_constraint ON DOMAIN constraint_comments_dom IS 'yes, another comment'; - --- no such table/domain -COMMENT ON CONSTRAINT the_constraint ON no_comments_tbl IS 'bad comment'; -COMMENT ON CONSTRAINT the_constraint ON DOMAIN no_comments_dom IS 'another bad comment'; - -COMMENT ON CONSTRAINT the_constraint ON constraint_comments_tbl IS NULL; -COMMENT ON CONSTRAINT the_constraint ON DOMAIN constraint_comments_dom IS NULL; - --- unauthorized user -RESET SESSION AUTHORIZATION; -CREATE ROLE regress_constraint_comments_noaccess; -SET SESSION AUTHORIZATION regress_constraint_comments_noaccess; -COMMENT ON CONSTRAINT the_constraint ON constraint_comments_tbl IS 'no, the comment'; -COMMENT ON CONSTRAINT the_constraint ON DOMAIN constraint_comments_dom IS 'no, another comment'; -RESET SESSION AUTHORIZATION; - -DROP TABLE constraint_comments_tbl; -DROP DOMAIN constraint_comments_dom; - -DROP ROLE regress_constraint_comments; -DROP ROLE regress_constraint_comments_noaccess; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fconversion.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fconversion.sql deleted file mode 100644 index 9a65fca91f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fconversion.sql +++ /dev/null @@ -1,365 +0,0 @@ --- --- create user defined conversion --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - -CREATE FUNCTION test_enc_conversion(bytea, name, name, bool, validlen OUT int, result OUT bytea) - AS :'regresslib', 'test_enc_conversion' - LANGUAGE C STRICT; - -CREATE USER regress_conversion_user WITH NOCREATEDB NOCREATEROLE; -SET SESSION AUTHORIZATION regress_conversion_user; -CREATE CONVERSION myconv FOR 'LATIN1' TO 'UTF8' FROM iso8859_1_to_utf8; --- --- cannot make same name conversion in same schema --- -CREATE CONVERSION myconv FOR 'LATIN1' TO 'UTF8' FROM iso8859_1_to_utf8; --- --- create default conversion with qualified name --- -CREATE DEFAULT CONVERSION public.mydef FOR 'LATIN1' TO 'UTF8' FROM iso8859_1_to_utf8; --- --- cannot make default conversion with same schema/for_encoding/to_encoding --- -CREATE DEFAULT CONVERSION public.mydef2 FOR 'LATIN1' TO 'UTF8' FROM iso8859_1_to_utf8; --- test comments -COMMENT ON CONVERSION myconv_bad IS 'foo'; -COMMENT ON CONVERSION myconv IS 'bar'; -COMMENT ON CONVERSION myconv IS NULL; --- --- drop user defined conversion --- -DROP CONVERSION myconv; -DROP CONVERSION mydef; --- --- Note: the built-in conversions are exercised in opr_sanity.sql, --- so there's no need to do that here. --- --- --- return to the superuser --- -RESET SESSION AUTHORIZATION; -DROP USER regress_conversion_user; - --- --- Test built-in conversion functions. --- - --- Helper function to test a conversion. Uses the test_enc_conversion function --- that was created in the create_function_0 test. -create or replace function test_conv( - input IN bytea, - src_encoding IN text, - dst_encoding IN text, - - result OUT bytea, - errorat OUT bytea, - error OUT text) -language plpgsql as -$$ -declare - validlen int; -begin - -- First try to perform the conversion with noError = false. If that errors out, - -- capture the error message, and try again with noError = true. The second call - -- should succeed and return the position of the error, return that too. - begin - select * into validlen, result from test_enc_conversion(input, src_encoding, dst_encoding, false); - errorat = NULL; - error := NULL; - exception when others then - error := sqlerrm; - select * into validlen, result from test_enc_conversion(input, src_encoding, dst_encoding, true); - errorat = substr(input, validlen + 1); - end; - return; -end; -$$; - - --- --- UTF-8 --- --- The description column must be unique. -CREATE TABLE utf8_verification_inputs (inbytes bytea, description text PRIMARY KEY); -insert into utf8_verification_inputs values - ('\x66006f', 'NUL byte'), - ('\xaf', 'bare continuation'), - ('\xc5', 'missing second byte in 2-byte char'), - ('\xc080', 'smallest 2-byte overlong'), - ('\xc1bf', 'largest 2-byte overlong'), - ('\xc280', 'next 2-byte after overlongs'), - ('\xdfbf', 'largest 2-byte'), - ('\xe9af', 'missing third byte in 3-byte char'), - ('\xe08080', 'smallest 3-byte overlong'), - ('\xe09fbf', 'largest 3-byte overlong'), - ('\xe0a080', 'next 3-byte after overlong'), - ('\xed9fbf', 'last before surrogates'), - ('\xeda080', 'smallest surrogate'), - ('\xedbfbf', 'largest surrogate'), - ('\xee8080', 'next after surrogates'), - ('\xefbfbf', 'largest 3-byte'), - ('\xf1afbf', 'missing fourth byte in 4-byte char'), - ('\xf0808080', 'smallest 4-byte overlong'), - ('\xf08fbfbf', 'largest 4-byte overlong'), - ('\xf0908080', 'next 4-byte after overlong'), - ('\xf48fbfbf', 'largest 4-byte'), - ('\xf4908080', 'smallest too large'), - ('\xfa9a9a8a8a', '5-byte'); - --- Test UTF-8 verification slow path -select description, (test_conv(inbytes, 'utf8', 'utf8')).* from utf8_verification_inputs; - --- Test UTF-8 verification with ASCII padding appended to provide --- coverage for algorithms that work on multiple bytes at a time. --- The error message for a sequence starting with a 4-byte lead --- will contain all 4 bytes if they are present, so various --- expressions below add 3 ASCII bytes to the end to ensure --- consistent error messages. --- The number 64 below needs to be at least the value of STRIDE_LENGTH in wchar.c. - --- Test multibyte verification in fast path -with test_bytes as ( - select - inbytes, - description, - (test_conv(inbytes || repeat('.', 3)::bytea, 'utf8', 'utf8')).error - from utf8_verification_inputs -), test_padded as ( - select - description, - (test_conv(inbytes || repeat('.', 64)::bytea, 'utf8', 'utf8')).error - from test_bytes -) -select - description, - b.error as orig_error, - p.error as error_after_padding -from test_padded p -join test_bytes b -using (description) -where p.error is distinct from b.error -order by description; - --- Test ASCII verification in fast path where incomplete --- UTF-8 sequences fall at the end of the preceding chunk. -with test_bytes as ( - select - inbytes, - description, - (test_conv(inbytes || repeat('.', 3)::bytea, 'utf8', 'utf8')).error - from utf8_verification_inputs -), test_padded as ( - select - description, - (test_conv(repeat('.', 64 - length(inbytes))::bytea || inbytes || repeat('.', 64)::bytea, 'utf8', 'utf8')).error - from test_bytes -) -select - description, - b.error as orig_error, - p.error as error_after_padding -from test_padded p -join test_bytes b -using (description) -where p.error is distinct from b.error -order by description; - --- Test cases where UTF-8 sequences within short text --- come after the fast path returns. -with test_bytes as ( - select - inbytes, - description, - (test_conv(inbytes || repeat('.', 3)::bytea, 'utf8', 'utf8')).error - from utf8_verification_inputs -), test_padded as ( - select - description, - (test_conv(repeat('.', 64)::bytea || inbytes || repeat('.', 3)::bytea, 'utf8', 'utf8')).error - from test_bytes -) -select - description, - b.error as orig_error, - p.error as error_after_padding -from test_padded p -join test_bytes b -using (description) -where p.error is distinct from b.error -order by description; - --- Test cases where incomplete UTF-8 sequences fall at the --- end of the part checked by the fast path. -with test_bytes as ( - select - inbytes, - description, - (test_conv(inbytes || repeat('.', 3)::bytea, 'utf8', 'utf8')).error - from utf8_verification_inputs -), test_padded as ( - select - description, - (test_conv(repeat('.', 64 - length(inbytes))::bytea || inbytes || repeat('.', 3)::bytea, 'utf8', 'utf8')).error - from test_bytes -) -select - description, - b.error as orig_error, - p.error as error_after_padding -from test_padded p -join test_bytes b -using (description) -where p.error is distinct from b.error -order by description; - -CREATE TABLE utf8_inputs (inbytes bytea, description text); -insert into utf8_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\xc3a4c3b6', 'valid, extra latin chars'), - ('\xd184d0bed0be', 'valid, cyrillic'), - ('\x666f6fe8b1a1', 'valid, kanji/Chinese'), - ('\xe382abe3829a', 'valid, two chars that combine to one in EUC_JIS_2004'), - ('\xe382ab', 'only first half of combined char in EUC_JIS_2004'), - ('\xe382abe382', 'incomplete combination when converted EUC_JIS_2004'), - ('\xecbd94eb81bceba6ac', 'valid, Hangul, Korean'), - ('\x666f6fefa8aa', 'valid, needs mapping function to convert to GB18030'), - ('\x66e8b1ff6f6f', 'invalid byte sequence'), - ('\x66006f', 'invalid, NUL byte'), - ('\x666f6fe8b100', 'invalid, NUL byte'), - ('\x666f6fe8b1', 'incomplete character at end'); - --- Test UTF-8 verification -select description, (test_conv(inbytes, 'utf8', 'utf8')).* from utf8_inputs; --- Test conversions from UTF-8 -select description, inbytes, (test_conv(inbytes, 'utf8', 'euc_jis_2004')).* from utf8_inputs; -select description, inbytes, (test_conv(inbytes, 'utf8', 'latin1')).* from utf8_inputs; -select description, inbytes, (test_conv(inbytes, 'utf8', 'latin2')).* from utf8_inputs; -select description, inbytes, (test_conv(inbytes, 'utf8', 'latin5')).* from utf8_inputs; -select description, inbytes, (test_conv(inbytes, 'utf8', 'koi8r')).* from utf8_inputs; -select description, inbytes, (test_conv(inbytes, 'utf8', 'gb18030')).* from utf8_inputs; - --- --- EUC_JIS_2004 --- -CREATE TABLE euc_jis_2004_inputs (inbytes bytea, description text); -insert into euc_jis_2004_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\x666f6fbedd', 'valid'), - ('\xa5f7', 'valid, translates to two UTF-8 chars '), - ('\xbeddbe', 'incomplete char '), - ('\x666f6f00bedd', 'invalid, NUL byte'), - ('\x666f6fbe00dd', 'invalid, NUL byte'), - ('\x666f6fbedd00', 'invalid, NUL byte'), - ('\xbe04', 'invalid byte sequence'); - --- Test EUC_JIS_2004 verification -select description, inbytes, (test_conv(inbytes, 'euc_jis_2004', 'euc_jis_2004')).* from euc_jis_2004_inputs; --- Test conversions from EUC_JIS_2004 -select description, inbytes, (test_conv(inbytes, 'euc_jis_2004', 'utf8')).* from euc_jis_2004_inputs; - --- --- SHIFT-JIS-2004 --- -CREATE TABLE shiftjis2004_inputs (inbytes bytea, description text); -insert into shiftjis2004_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\x666f6f8fdb', 'valid'), - ('\x666f6f81c0', 'valid, no translation to UTF-8'), - ('\x666f6f82f5', 'valid, translates to two UTF-8 chars '), - ('\x666f6f8fdb8f', 'incomplete char '), - ('\x666f6f820a', 'incomplete char, followed by newline '), - ('\x666f6f008fdb', 'invalid, NUL byte'), - ('\x666f6f8f00db', 'invalid, NUL byte'), - ('\x666f6f8fdb00', 'invalid, NUL byte'); - --- Test SHIFT-JIS-2004 verification -select description, inbytes, (test_conv(inbytes, 'shiftjis2004', 'shiftjis2004')).* from shiftjis2004_inputs; --- Test conversions from SHIFT-JIS-2004 -select description, inbytes, (test_conv(inbytes, 'shiftjis2004', 'utf8')).* from shiftjis2004_inputs; -select description, inbytes, (test_conv(inbytes, 'shiftjis2004', 'euc_jis_2004')).* from shiftjis2004_inputs; - --- --- GB18030 --- -CREATE TABLE gb18030_inputs (inbytes bytea, description text); -insert into gb18030_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\x666f6fcff3', 'valid'), - ('\x666f6f8431a530', 'valid, no translation to UTF-8'), - ('\x666f6f84309c38', 'valid, translates to UTF-8 by mapping function'), - ('\x666f6f84309c', 'incomplete char '), - ('\x666f6f84309c0a', 'incomplete char, followed by newline '), - ('\x666f6f84309c3800', 'invalid, NUL byte'), - ('\x666f6f84309c0038', 'invalid, NUL byte'); - --- Test GB18030 verification -select description, inbytes, (test_conv(inbytes, 'gb18030', 'gb18030')).* from gb18030_inputs; --- Test conversions from GB18030 -select description, inbytes, (test_conv(inbytes, 'gb18030', 'utf8')).* from gb18030_inputs; - - --- --- ISO-8859-5 --- -CREATE TABLE iso8859_5_inputs (inbytes bytea, description text); -insert into iso8859_5_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\xe4dede', 'valid'), - ('\x00', 'invalid, NUL byte'), - ('\xe400dede', 'invalid, NUL byte'), - ('\xe4dede00', 'invalid, NUL byte'); - --- Test ISO-8859-5 verification -select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'iso8859-5')).* from iso8859_5_inputs; --- Test conversions from ISO-8859-5 -select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'utf8')).* from iso8859_5_inputs; -select description, inbytes, (test_conv(inbytes, 'iso8859-5', 'koi8r')).* from iso8859_5_inputs; -select description, inbytes, (test_conv(inbytes, 'iso8859_5', 'mule_internal')).* from iso8859_5_inputs; - --- --- Big5 --- -CREATE TABLE big5_inputs (inbytes bytea, description text); -insert into big5_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\x666f6fb648', 'valid'), - ('\x666f6fa27f', 'valid, no translation to UTF-8'), - ('\x666f6fb60048', 'invalid, NUL byte'), - ('\x666f6fb64800', 'invalid, NUL byte'); - --- Test Big5 verification -select description, inbytes, (test_conv(inbytes, 'big5', 'big5')).* from big5_inputs; --- Test conversions from Big5 -select description, inbytes, (test_conv(inbytes, 'big5', 'utf8')).* from big5_inputs; -select description, inbytes, (test_conv(inbytes, 'big5', 'mule_internal')).* from big5_inputs; - --- --- MULE_INTERNAL --- -CREATE TABLE mic_inputs (inbytes bytea, description text); -insert into mic_inputs values - ('\x666f6f', 'valid, pure ASCII'), - ('\x8bc68bcf8bcf', 'valid (in KOI8R)'), - ('\x8bc68bcf8b', 'invalid,incomplete char'), - ('\x92bedd', 'valid (in SHIFT_JIS)'), - ('\x92be', 'invalid, incomplete char)'), - ('\x666f6f95a3c1', 'valid (in Big5)'), - ('\x666f6f95a3', 'invalid, incomplete char'), - ('\x9200bedd', 'invalid, NUL byte'), - ('\x92bedd00', 'invalid, NUL byte'), - ('\x8b00c68bcf8bcf', 'invalid, NUL byte'); - --- Test MULE_INTERNAL verification -select description, inbytes, (test_conv(inbytes, 'mule_internal', 'mule_internal')).* from mic_inputs; --- Test conversions from MULE_INTERNAL -select description, inbytes, (test_conv(inbytes, 'mule_internal', 'koi8r')).* from mic_inputs; -select description, inbytes, (test_conv(inbytes, 'mule_internal', 'iso8859-5')).* from mic_inputs; -select description, inbytes, (test_conv(inbytes, 'mule_internal', 'sjis')).* from mic_inputs; -select description, inbytes, (test_conv(inbytes, 'mule_internal', 'big5')).* from mic_inputs; -select description, inbytes, (test_conv(inbytes, 'mule_internal', 'euc_jp')).* from mic_inputs; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopy.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopy.sql deleted file mode 100644 index d72d226f34..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopy.sql +++ /dev/null @@ -1,232 +0,0 @@ --- --- COPY --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR -\getenv abs_builddir PG_ABS_BUILDDIR - ---- test copying in CSV mode with various styles ---- of embedded line ending characters - -create temp table copytest ( - style text, - test text, - filler int); - -insert into copytest values('DOS',E'abc\r\ndef',1); -insert into copytest values('Unix',E'abc\ndef',2); -insert into copytest values('Mac',E'abc\rdef',3); -insert into copytest values(E'esc\\ape',E'a\\r\\\r\\\n\\nb',4); - -\set filename :abs_builddir '/results/copytest.csv' -copy copytest to :'filename' csv; - -create temp table copytest2 (like copytest); - -copy copytest2 from :'filename' csv; - -select * from copytest except select * from copytest2; - -truncate copytest2; - ---- same test but with an escape char different from quote char - -copy copytest to :'filename' csv quote '''' escape E'\\'; - -copy copytest2 from :'filename' csv quote '''' escape E'\\'; - -select * from copytest except select * from copytest2; - - --- test header line feature - -create temp table copytest3 ( - c1 int, - "col with , comma" text, - "col with "" quote" int); - -copy copytest3 from stdin csv header; -this is just a line full of junk that would error out if parsed -1,a,1 -2,b,2 -\. - -copy copytest3 to stdout csv header; - -create temp table copytest4 ( - c1 int, - "colname with tab: " text); - -copy copytest4 from stdin (header); -this is just a line full of junk that would error out if parsed -1 a -2 b -\. - -copy copytest4 to stdout (header); - --- test copy from with a partitioned table -create table parted_copytest ( - a int, - b int, - c text -) partition by list (b); - -create table parted_copytest_a1 (c text, b int, a int); -create table parted_copytest_a2 (a int, c text, b int); - -alter table parted_copytest attach partition parted_copytest_a1 for values in(1); -alter table parted_copytest attach partition parted_copytest_a2 for values in(2); - --- We must insert enough rows to trigger multi-inserts. These are only --- enabled adaptively when there are few enough partition changes. -insert into parted_copytest select x,1,'One' from generate_series(1,1000) x; -insert into parted_copytest select x,2,'Two' from generate_series(1001,1010) x; -insert into parted_copytest select x,1,'One' from generate_series(1011,1020) x; - -\set filename :abs_builddir '/results/parted_copytest.csv' -copy (select * from parted_copytest order by a) to :'filename'; - -truncate parted_copytest; - -copy parted_copytest from :'filename'; - --- Ensure COPY FREEZE errors for partitioned tables. -begin; -truncate parted_copytest; -copy parted_copytest from :'filename' (freeze); -rollback; - -select tableoid::regclass,count(*),sum(a) from parted_copytest -group by tableoid order by tableoid::regclass::name; - -truncate parted_copytest; - --- create before insert row trigger on parted_copytest_a2 -create function part_ins_func() returns trigger language plpgsql as $$ -begin - return new; -end; -$$; - -create trigger part_ins_trig - before insert on parted_copytest_a2 - for each row - execute procedure part_ins_func(); - -copy parted_copytest from :'filename'; - -select tableoid::regclass,count(*),sum(a) from parted_copytest -group by tableoid order by tableoid::regclass::name; - -truncate table parted_copytest; -create index on parted_copytest (b); -drop trigger part_ins_trig on parted_copytest_a2; - -copy parted_copytest from stdin; -1 1 str1 -2 2 str2 -\. - --- Ensure index entries were properly added during the copy. -select * from parted_copytest where b = 1; -select * from parted_copytest where b = 2; - -drop table parted_copytest; - --- --- Progress reporting for COPY --- -create table tab_progress_reporting ( - name text, - age int4, - location point, - salary int4, - manager name -); - --- Add a trigger to catch and print the contents of the catalog view --- pg_stat_progress_copy during data insertion. This allows to test --- the validation of some progress reports for COPY FROM where the trigger --- would fire. -create function notice_after_tab_progress_reporting() returns trigger AS -$$ -declare report record; -begin - -- The fields ignored here are the ones that may not remain - -- consistent across multiple runs. The sizes reported may differ - -- across platforms, so just check if these are strictly positive. - with progress_data as ( - select - relid::regclass::text as relname, - command, - type, - bytes_processed > 0 as has_bytes_processed, - bytes_total > 0 as has_bytes_total, - tuples_processed, - tuples_excluded - from pg_stat_progress_copy - where pid = pg_backend_pid()) - select into report (to_jsonb(r)) as value - from progress_data r; - - raise info 'progress: %', report.value::text; - return new; -end; -$$ language plpgsql; - -create trigger check_after_tab_progress_reporting - after insert on tab_progress_reporting - for each statement - execute function notice_after_tab_progress_reporting(); - --- Generate COPY FROM report with PIPE. -copy tab_progress_reporting from stdin; -sharon 25 (15,12) 1000 sam -sam 30 (10,5) 2000 bill -bill 20 (11,10) 1000 sharon -\. - --- Generate COPY FROM report with FILE, with some excluded tuples. -truncate tab_progress_reporting; -\set filename :abs_srcdir '/data/emp.data' -copy tab_progress_reporting from :'filename' - where (salary < 2000); - -drop trigger check_after_tab_progress_reporting on tab_progress_reporting; -drop function notice_after_tab_progress_reporting(); -drop table tab_progress_reporting; - --- Test header matching feature -create table header_copytest ( - a int, - b int, - c text -); -copy header_copytest from stdin with (header wrong_choice); -copy header_copytest from stdin with (header match); -a b c -1 2 foo -\. -copy header_copytest from stdin with (header match); -a b \N -1 2 foo -\. -copy header_copytest from stdin with (header match); -a b -1 2 -\. -copy header_copytest from stdin with (header match); -a b c d -1 2 foo bar -\. -copy header_copytest from stdin with (header match); -a b d -1 2 foo -\. -copy header_copytest from stdin with (header match, format csv); -a,b,c -1,2,foo -\. -drop table header_copytest; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopy2.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopy2.sql deleted file mode 100644 index b3c16af48e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopy2.sql +++ /dev/null @@ -1,470 +0,0 @@ -CREATE TEMP TABLE x ( - a serial, - b int, - c text not null default 'stuff', - d text, - e text -) ; - -CREATE FUNCTION fn_x_before () RETURNS TRIGGER AS ' - BEGIN - NEW.e := ''before trigger fired''::text; - return NEW; - END; -' LANGUAGE plpgsql; - -CREATE FUNCTION fn_x_after () RETURNS TRIGGER AS ' - BEGIN - UPDATE x set e=''after trigger fired'' where c=''stuff''; - return NULL; - END; -' LANGUAGE plpgsql; - -CREATE TRIGGER trg_x_after AFTER INSERT ON x -FOR EACH ROW EXECUTE PROCEDURE fn_x_after(); - -CREATE TRIGGER trg_x_before BEFORE INSERT ON x -FOR EACH ROW EXECUTE PROCEDURE fn_x_before(); - -COPY x (a, b, c, d, e) from stdin; -9999 \N \\N \NN \N -10000 21 31 41 51 -\. - -COPY x (b, d) from stdin; -1 test_1 -\. - -COPY x (b, d) from stdin; -2 test_2 -3 test_3 -4 test_4 -5 test_5 -\. - -COPY x (a, b, c, d, e) from stdin; -10001 22 32 42 52 -10002 23 33 43 53 -10003 24 34 44 54 -10004 25 35 45 55 -10005 26 36 46 56 -\. - --- non-existent column in column list: should fail -COPY x (xyz) from stdin; - --- redundant options -COPY x from stdin (format CSV, FORMAT CSV); -COPY x from stdin (freeze off, freeze on); -COPY x from stdin (delimiter ',', delimiter ','); -COPY x from stdin (null ' ', null ' '); -COPY x from stdin (header off, header on); -COPY x from stdin (quote ':', quote ':'); -COPY x from stdin (escape ':', escape ':'); -COPY x from stdin (force_quote (a), force_quote *); -COPY x from stdin (force_not_null (a), force_not_null (b)); -COPY x from stdin (force_null (a), force_null (b)); -COPY x from stdin (convert_selectively (a), convert_selectively (b)); -COPY x from stdin (encoding 'sql_ascii', encoding 'sql_ascii'); - --- too many columns in column list: should fail -COPY x (a, b, c, d, e, d, c) from stdin; - --- missing data: should fail -COPY x from stdin; - -\. -COPY x from stdin; -2000 230 23 23 -\. -COPY x from stdin; -2001 231 \N \N -\. - --- extra data: should fail -COPY x from stdin; -2002 232 40 50 60 70 80 -\. - --- various COPY options: delimiters, oids, NULL string, encoding -COPY x (b, c, d, e) from stdin delimiter ',' null 'x'; -x,45,80,90 -x,\x,\\x,\\\x -x,\,,\\\,,\\ -\. - -COPY x from stdin WITH DELIMITER AS ';' NULL AS ''; -3000;;c;; -\. - -COPY x from stdin WITH DELIMITER AS ':' NULL AS E'\\X' ENCODING 'sql_ascii'; -4000:\X:C:\X:\X -4001:1:empty:: -4002:2:null:\X:\X -4003:3:Backslash:\\:\\ -4004:4:BackslashX:\\X:\\X -4005:5:N:\N:\N -4006:6:BackslashN:\\N:\\N -4007:7:XX:\XX:\XX -4008:8:Delimiter:\::\: -\. - -COPY x TO stdout WHERE a = 1; -COPY x from stdin WHERE a = 50004; -50003 24 34 44 54 -50004 25 35 45 55 -50005 26 36 46 56 -\. - -COPY x from stdin WHERE a > 60003; -60001 22 32 42 52 -60002 23 33 43 53 -60003 24 34 44 54 -60004 25 35 45 55 -60005 26 36 46 56 -\. - -COPY x from stdin WHERE f > 60003; - -COPY x from stdin WHERE a = max(x.b); - -COPY x from stdin WHERE a IN (SELECT 1 FROM x); - -COPY x from stdin WHERE a IN (generate_series(1,5)); - -COPY x from stdin WHERE a = row_number() over(b); - - --- check results of copy in -SELECT * FROM x; - --- check copy out -COPY x TO stdout; -COPY x (c, e) TO stdout; -COPY x (b, e) TO stdout WITH NULL 'I''m null'; - -CREATE TEMP TABLE y ( - col1 text, - col2 text -); - -INSERT INTO y VALUES ('Jackson, Sam', E'\\h'); -INSERT INTO y VALUES ('It is "perfect".',E'\t'); -INSERT INTO y VALUES ('', NULL); - -COPY y TO stdout WITH CSV; -COPY y TO stdout WITH CSV QUOTE '''' DELIMITER '|'; -COPY y TO stdout WITH CSV FORCE QUOTE col2 ESCAPE E'\\' ENCODING 'sql_ascii'; -COPY y TO stdout WITH CSV FORCE QUOTE *; - --- Repeat above tests with new 9.0 option syntax - -COPY y TO stdout (FORMAT CSV); -COPY y TO stdout (FORMAT CSV, QUOTE '''', DELIMITER '|'); -COPY y TO stdout (FORMAT CSV, FORCE_QUOTE (col2), ESCAPE E'\\'); -COPY y TO stdout (FORMAT CSV, FORCE_QUOTE *); - -\copy y TO stdout (FORMAT CSV) -\copy y TO stdout (FORMAT CSV, QUOTE '''', DELIMITER '|') -\copy y TO stdout (FORMAT CSV, FORCE_QUOTE (col2), ESCAPE E'\\') -\copy y TO stdout (FORMAT CSV, FORCE_QUOTE *) - ---test that we read consecutive LFs properly - -CREATE TEMP TABLE testnl (a int, b text, c int); - -COPY testnl FROM stdin CSV; -1,"a field with two LFs - -inside",2 -\. - --- test end of copy marker -CREATE TEMP TABLE testeoc (a text); - -COPY testeoc FROM stdin CSV; -a\. -\.b -c\.d -"\." -\. - -COPY testeoc TO stdout CSV; - --- test handling of nonstandard null marker that violates escaping rules - -CREATE TEMP TABLE testnull(a int, b text); -INSERT INTO testnull VALUES (1, E'\\0'), (NULL, NULL); - -COPY testnull TO stdout WITH NULL AS E'\\0'; - -COPY testnull FROM stdin WITH NULL AS E'\\0'; -42 \\0 -\0 \0 -\. - -SELECT * FROM testnull; - -BEGIN; -CREATE TABLE vistest (LIKE testeoc); -COPY vistest FROM stdin CSV; -a0 -b -\. -COMMIT; -SELECT * FROM vistest; -BEGIN; -TRUNCATE vistest; -COPY vistest FROM stdin CSV; -a1 -b -\. -SELECT * FROM vistest; -SAVEPOINT s1; -TRUNCATE vistest; -COPY vistest FROM stdin CSV; -d1 -e -\. -SELECT * FROM vistest; -COMMIT; -SELECT * FROM vistest; - -BEGIN; -TRUNCATE vistest; -COPY vistest FROM stdin CSV FREEZE; -a2 -b -\. -SELECT * FROM vistest; -SAVEPOINT s1; -TRUNCATE vistest; -COPY vistest FROM stdin CSV FREEZE; -d2 -e -\. -SELECT * FROM vistest; -COMMIT; -SELECT * FROM vistest; - -BEGIN; -TRUNCATE vistest; -COPY vistest FROM stdin CSV FREEZE; -x -y -\. -SELECT * FROM vistest; -COMMIT; -TRUNCATE vistest; -COPY vistest FROM stdin CSV FREEZE; -p -g -\. -BEGIN; -TRUNCATE vistest; -SAVEPOINT s1; -COPY vistest FROM stdin CSV FREEZE; -m -k -\. -COMMIT; -BEGIN; -INSERT INTO vistest VALUES ('z'); -SAVEPOINT s1; -TRUNCATE vistest; -ROLLBACK TO SAVEPOINT s1; -COPY vistest FROM stdin CSV FREEZE; -d3 -e -\. -COMMIT; -CREATE FUNCTION truncate_in_subxact() RETURNS VOID AS -$$ -BEGIN - TRUNCATE vistest; -EXCEPTION - WHEN OTHERS THEN - INSERT INTO vistest VALUES ('subxact failure'); -END; -$$ language plpgsql; -BEGIN; -INSERT INTO vistest VALUES ('z'); -SELECT truncate_in_subxact(); -COPY vistest FROM stdin CSV FREEZE; -d4 -e -\. -SELECT * FROM vistest; -COMMIT; -SELECT * FROM vistest; --- Test FORCE_NOT_NULL and FORCE_NULL options -CREATE TEMP TABLE forcetest ( - a INT NOT NULL, - b TEXT NOT NULL, - c TEXT, - d TEXT, - e TEXT -); -\pset null NULL --- should succeed with no effect ("b" remains an empty string, "c" remains NULL) -BEGIN; -COPY forcetest (a, b, c) FROM STDIN WITH (FORMAT csv, FORCE_NOT_NULL(b), FORCE_NULL(c)); -1,,"" -\. -COMMIT; -SELECT b, c FROM forcetest WHERE a = 1; --- should succeed, FORCE_NULL and FORCE_NOT_NULL can be both specified -BEGIN; -COPY forcetest (a, b, c, d) FROM STDIN WITH (FORMAT csv, FORCE_NOT_NULL(c,d), FORCE_NULL(c,d)); -2,'a',,"" -\. -COMMIT; -SELECT c, d FROM forcetest WHERE a = 2; --- should fail with not-null constraint violation -BEGIN; -COPY forcetest (a, b, c) FROM STDIN WITH (FORMAT csv, FORCE_NULL(b), FORCE_NOT_NULL(c)); -3,,"" -\. -ROLLBACK; --- should fail with "not referenced by COPY" error -BEGIN; -COPY forcetest (d, e) FROM STDIN WITH (FORMAT csv, FORCE_NOT_NULL(b)); -ROLLBACK; --- should fail with "not referenced by COPY" error -BEGIN; -COPY forcetest (d, e) FROM STDIN WITH (FORMAT csv, FORCE_NULL(b)); -ROLLBACK; -\pset null '' - --- test case with whole-row Var in a check constraint -create table check_con_tbl (f1 int); -create function check_con_function(check_con_tbl) returns bool as $$ -begin - raise notice 'input = %', row_to_json($1); - return $1.f1 > 0; -end $$ language plpgsql immutable; -alter table check_con_tbl add check (check_con_function(check_con_tbl.*)); -\d+ check_con_tbl -copy check_con_tbl from stdin; -1 -\N -\. -copy check_con_tbl from stdin; -0 -\. -select * from check_con_tbl; - --- test with RLS enabled. -CREATE ROLE regress_rls_copy_user; -CREATE ROLE regress_rls_copy_user_colperms; -CREATE TABLE rls_t1 (a int, b int, c int); - -COPY rls_t1 (a, b, c) from stdin; -1 4 1 -2 3 2 -3 2 3 -4 1 4 -\. - -CREATE POLICY p1 ON rls_t1 FOR SELECT USING (a % 2 = 0); -ALTER TABLE rls_t1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE rls_t1 FORCE ROW LEVEL SECURITY; - -GRANT SELECT ON TABLE rls_t1 TO regress_rls_copy_user; -GRANT SELECT (a, b) ON TABLE rls_t1 TO regress_rls_copy_user_colperms; - --- all columns -COPY rls_t1 TO stdout; -COPY rls_t1 (a, b, c) TO stdout; - --- subset of columns -COPY rls_t1 (a) TO stdout; -COPY rls_t1 (a, b) TO stdout; - --- column reordering -COPY rls_t1 (b, a) TO stdout; - -SET SESSION AUTHORIZATION regress_rls_copy_user; - --- all columns -COPY rls_t1 TO stdout; -COPY rls_t1 (a, b, c) TO stdout; - --- subset of columns -COPY rls_t1 (a) TO stdout; -COPY rls_t1 (a, b) TO stdout; - --- column reordering -COPY rls_t1 (b, a) TO stdout; - -RESET SESSION AUTHORIZATION; - -SET SESSION AUTHORIZATION regress_rls_copy_user_colperms; - --- attempt all columns (should fail) -COPY rls_t1 TO stdout; -COPY rls_t1 (a, b, c) TO stdout; - --- try to copy column with no privileges (should fail) -COPY rls_t1 (c) TO stdout; - --- subset of columns (should succeed) -COPY rls_t1 (a) TO stdout; -COPY rls_t1 (a, b) TO stdout; - -RESET SESSION AUTHORIZATION; - --- test with INSTEAD OF INSERT trigger on a view -CREATE TABLE instead_of_insert_tbl(id serial, name text); -CREATE VIEW instead_of_insert_tbl_view AS SELECT ''::text AS str; - -COPY instead_of_insert_tbl_view FROM stdin; -- fail -test1 -\. - -CREATE FUNCTION fun_instead_of_insert_tbl() RETURNS trigger AS $$ -BEGIN - INSERT INTO instead_of_insert_tbl (name) VALUES (NEW.str); - RETURN NULL; -END; -$$ LANGUAGE plpgsql; -CREATE TRIGGER trig_instead_of_insert_tbl_view - INSTEAD OF INSERT ON instead_of_insert_tbl_view - FOR EACH ROW EXECUTE PROCEDURE fun_instead_of_insert_tbl(); - -COPY instead_of_insert_tbl_view FROM stdin; -test1 -\. - -SELECT * FROM instead_of_insert_tbl; - --- Test of COPY optimization with view using INSTEAD OF INSERT --- trigger when relation is created in the same transaction as --- when COPY is executed. -BEGIN; -CREATE VIEW instead_of_insert_tbl_view_2 as select ''::text as str; -CREATE TRIGGER trig_instead_of_insert_tbl_view_2 - INSTEAD OF INSERT ON instead_of_insert_tbl_view_2 - FOR EACH ROW EXECUTE PROCEDURE fun_instead_of_insert_tbl(); - -COPY instead_of_insert_tbl_view_2 FROM stdin; -test1 -\. - -SELECT * FROM instead_of_insert_tbl; -COMMIT; - --- clean up -DROP TABLE forcetest; -DROP TABLE vistest; -DROP FUNCTION truncate_in_subxact(); -DROP TABLE x, y; -DROP TABLE rls_t1 CASCADE; -DROP ROLE regress_rls_copy_user; -DROP ROLE regress_rls_copy_user_colperms; -DROP FUNCTION fn_x_before(); -DROP FUNCTION fn_x_after(); -DROP TABLE instead_of_insert_tbl; -DROP VIEW instead_of_insert_tbl_view; -DROP VIEW instead_of_insert_tbl_view_2; -DROP FUNCTION fun_instead_of_insert_tbl(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopydml.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopydml.sql deleted file mode 100644 index 4578342253..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcopydml.sql +++ /dev/null @@ -1,91 +0,0 @@ --- --- Test cases for COPY (INSERT/UPDATE/DELETE) TO --- -create table copydml_test (id serial, t text); -insert into copydml_test (t) values ('a'); -insert into copydml_test (t) values ('b'); -insert into copydml_test (t) values ('c'); -insert into copydml_test (t) values ('d'); -insert into copydml_test (t) values ('e'); - --- --- Test COPY (insert/update/delete ...) --- -copy (insert into copydml_test (t) values ('f') returning id) to stdout; -copy (update copydml_test set t = 'g' where t = 'f' returning id) to stdout; -copy (delete from copydml_test where t = 'g' returning id) to stdout; - --- --- Test \copy (insert/update/delete ...) --- -\copy (insert into copydml_test (t) values ('f') returning id) to stdout; -\copy (update copydml_test set t = 'g' where t = 'f' returning id) to stdout; -\copy (delete from copydml_test where t = 'g' returning id) to stdout; - --- Error cases -copy (insert into copydml_test default values) to stdout; -copy (update copydml_test set t = 'g') to stdout; -copy (delete from copydml_test) to stdout; - -create rule qqq as on insert to copydml_test do instead nothing; -copy (insert into copydml_test default values) to stdout; -drop rule qqq on copydml_test; -create rule qqq as on insert to copydml_test do also delete from copydml_test; -copy (insert into copydml_test default values) to stdout; -drop rule qqq on copydml_test; -create rule qqq as on insert to copydml_test do instead (delete from copydml_test; delete from copydml_test); -copy (insert into copydml_test default values) to stdout; -drop rule qqq on copydml_test; -create rule qqq as on insert to copydml_test where new.t <> 'f' do instead delete from copydml_test; -copy (insert into copydml_test default values) to stdout; -drop rule qqq on copydml_test; - -create rule qqq as on update to copydml_test do instead nothing; -copy (update copydml_test set t = 'f') to stdout; -drop rule qqq on copydml_test; -create rule qqq as on update to copydml_test do also delete from copydml_test; -copy (update copydml_test set t = 'f') to stdout; -drop rule qqq on copydml_test; -create rule qqq as on update to copydml_test do instead (delete from copydml_test; delete from copydml_test); -copy (update copydml_test set t = 'f') to stdout; -drop rule qqq on copydml_test; -create rule qqq as on update to copydml_test where new.t <> 'f' do instead delete from copydml_test; -copy (update copydml_test set t = 'f') to stdout; -drop rule qqq on copydml_test; - -create rule qqq as on delete to copydml_test do instead nothing; -copy (delete from copydml_test) to stdout; -drop rule qqq on copydml_test; -create rule qqq as on delete to copydml_test do also insert into copydml_test default values; -copy (delete from copydml_test) to stdout; -drop rule qqq on copydml_test; -create rule qqq as on delete to copydml_test do instead (insert into copydml_test default values; insert into copydml_test default values); -copy (delete from copydml_test) to stdout; -drop rule qqq on copydml_test; -create rule qqq as on delete to copydml_test where old.t <> 'f' do instead insert into copydml_test default values; -copy (delete from copydml_test) to stdout; -drop rule qqq on copydml_test; - --- triggers -create function qqq_trig() returns trigger as $$ -begin -if tg_op in ('INSERT', 'UPDATE') then - raise notice '% % %', tg_when, tg_op, new.id; - return new; -else - raise notice '% % %', tg_when, tg_op, old.id; - return old; -end if; -end -$$ language plpgsql; -create trigger qqqbef before insert or update or delete on copydml_test - for each row execute procedure qqq_trig(); -create trigger qqqaf after insert or update or delete on copydml_test - for each row execute procedure qqq_trig(); - -copy (insert into copydml_test (t) values ('f') returning id) to stdout; -copy (update copydml_test set t = 'g' where t = 'f' returning id) to stdout; -copy (delete from copydml_test where t = 'g' returning id) to stdout; - -drop table copydml_test; -drop function qqq_trig(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_am.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_am.sql deleted file mode 100644 index 256884c959..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_am.sql +++ /dev/null @@ -1,241 +0,0 @@ --- --- Create access method tests --- - --- Make gist2 over gisthandler. In fact, it would be a synonym to gist. -CREATE ACCESS METHOD gist2 TYPE INDEX HANDLER gisthandler; - --- Verify return type checks for handlers -CREATE ACCESS METHOD bogus TYPE INDEX HANDLER int4in; -CREATE ACCESS METHOD bogus TYPE INDEX HANDLER heap_tableam_handler; - - --- Try to create gist2 index on fast_emp4000: fail because opclass doesn't exist -CREATE INDEX grect2ind2 ON fast_emp4000 USING gist2 (home_base); - --- Make operator class for boxes using gist2 -CREATE OPERATOR CLASS box_ops DEFAULT - FOR TYPE box USING gist2 AS - OPERATOR 1 <<, - OPERATOR 2 &<, - OPERATOR 3 &&, - OPERATOR 4 &>, - OPERATOR 5 >>, - OPERATOR 6 ~=, - OPERATOR 7 @>, - OPERATOR 8 <@, - OPERATOR 9 &<|, - OPERATOR 10 <<|, - OPERATOR 11 |>>, - OPERATOR 12 |&>, - FUNCTION 1 gist_box_consistent(internal, box, smallint, oid, internal), - FUNCTION 2 gist_box_union(internal, internal), - -- don't need compress, decompress, or fetch functions - FUNCTION 5 gist_box_penalty(internal, internal, internal), - FUNCTION 6 gist_box_picksplit(internal, internal), - FUNCTION 7 gist_box_same(box, box, internal); - --- Create gist2 index on fast_emp4000 -CREATE INDEX grect2ind2 ON fast_emp4000 USING gist2 (home_base); - --- Now check the results from plain indexscan; temporarily drop existing --- index grect2ind to ensure it doesn't capture the plan -BEGIN; -DROP INDEX grect2ind; -SET enable_seqscan = OFF; -SET enable_indexscan = ON; -SET enable_bitmapscan = OFF; - -EXPLAIN (COSTS OFF) -SELECT * FROM fast_emp4000 - WHERE home_base <@ '(200,200),(2000,1000)'::box - ORDER BY (home_base[0])[0]; -SELECT * FROM fast_emp4000 - WHERE home_base <@ '(200,200),(2000,1000)'::box - ORDER BY (home_base[0])[0]; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box; -SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL; -SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL; - -ROLLBACK; - --- Try to drop access method: fail because of dependent objects -DROP ACCESS METHOD gist2; - --- Drop access method cascade --- To prevent a (rare) deadlock against autovacuum, --- we must lock the table that owns the index that will be dropped -BEGIN; -LOCK TABLE fast_emp4000; -DROP ACCESS METHOD gist2 CASCADE; -COMMIT; - - --- --- Test table access methods --- - --- prevent empty values -SET default_table_access_method = ''; - --- prevent nonexistent values -SET default_table_access_method = 'I do not exist AM'; - --- prevent setting it to an index AM -SET default_table_access_method = 'btree'; - - --- Create a heap2 table am handler with heapam handler -CREATE ACCESS METHOD heap2 TYPE TABLE HANDLER heap_tableam_handler; - --- Verify return type checks for handlers -CREATE ACCESS METHOD bogus TYPE TABLE HANDLER int4in; -CREATE ACCESS METHOD bogus TYPE TABLE HANDLER bthandler; - -SELECT amname, amhandler, amtype FROM pg_am where amtype = 't' ORDER BY 1, 2; - - --- First create tables employing the new AM using USING - --- plain CREATE TABLE -CREATE TABLE tableam_tbl_heap2(f1 int) USING heap2; -INSERT INTO tableam_tbl_heap2 VALUES(1); -SELECT f1 FROM tableam_tbl_heap2 ORDER BY f1; - --- CREATE TABLE AS -CREATE TABLE tableam_tblas_heap2 USING heap2 AS SELECT * FROM tableam_tbl_heap2; -SELECT f1 FROM tableam_tbl_heap2 ORDER BY f1; - --- SELECT INTO doesn't support USING -SELECT INTO tableam_tblselectinto_heap2 USING heap2 FROM tableam_tbl_heap2; - --- CREATE VIEW doesn't support USING -CREATE VIEW tableam_view_heap2 USING heap2 AS SELECT * FROM tableam_tbl_heap2; - --- CREATE SEQUENCE doesn't support USING -CREATE SEQUENCE tableam_seq_heap2 USING heap2; - --- CREATE MATERIALIZED VIEW does support USING -CREATE MATERIALIZED VIEW tableam_tblmv_heap2 USING heap2 AS SELECT * FROM tableam_tbl_heap2; -SELECT f1 FROM tableam_tblmv_heap2 ORDER BY f1; - --- CREATE TABLE .. PARTITION BY doesn't not support USING -CREATE TABLE tableam_parted_heap2 (a text, b int) PARTITION BY list (a) USING heap2; - -CREATE TABLE tableam_parted_heap2 (a text, b int) PARTITION BY list (a); --- new partitions will inherit from the current default, rather the partition root -SET default_table_access_method = 'heap'; -CREATE TABLE tableam_parted_a_heap2 PARTITION OF tableam_parted_heap2 FOR VALUES IN ('a'); -SET default_table_access_method = 'heap2'; -CREATE TABLE tableam_parted_b_heap2 PARTITION OF tableam_parted_heap2 FOR VALUES IN ('b'); -RESET default_table_access_method; --- but the method can be explicitly specified -CREATE TABLE tableam_parted_c_heap2 PARTITION OF tableam_parted_heap2 FOR VALUES IN ('c') USING heap; -CREATE TABLE tableam_parted_d_heap2 PARTITION OF tableam_parted_heap2 FOR VALUES IN ('d') USING heap2; - --- List all objects in AM -SELECT - pc.relkind, - pa.amname, - CASE WHEN relkind = 't' THEN - (SELECT 'toast for ' || relname::regclass FROM pg_class pcm WHERE pcm.reltoastrelid = pc.oid) - ELSE - relname::regclass::text - END COLLATE "C" AS relname -FROM pg_class AS pc, - pg_am AS pa -WHERE pa.oid = pc.relam - AND pa.amname = 'heap2' -ORDER BY 3, 1, 2; - --- Show dependencies onto AM - there shouldn't be any for toast -SELECT pg_describe_object(classid,objid,objsubid) AS obj -FROM pg_depend, pg_am -WHERE pg_depend.refclassid = 'pg_am'::regclass - AND pg_am.oid = pg_depend.refobjid - AND pg_am.amname = 'heap2' -ORDER BY classid, objid, objsubid; - --- ALTER TABLE SET ACCESS METHOD -CREATE TABLE heaptable USING heap AS - SELECT a, repeat(a::text, 100) FROM generate_series(1,9) AS a; -SELECT amname FROM pg_class c, pg_am am - WHERE c.relam = am.oid AND c.oid = 'heaptable'::regclass; -ALTER TABLE heaptable SET ACCESS METHOD heap2; -SELECT amname FROM pg_class c, pg_am am - WHERE c.relam = am.oid AND c.oid = 'heaptable'::regclass; -SELECT COUNT(a), COUNT(1) FILTER(WHERE a=1) FROM heaptable; --- ALTER MATERIALIZED VIEW SET ACCESS METHOD -CREATE MATERIALIZED VIEW heapmv USING heap AS SELECT * FROM heaptable; -SELECT amname FROM pg_class c, pg_am am - WHERE c.relam = am.oid AND c.oid = 'heapmv'::regclass; -ALTER MATERIALIZED VIEW heapmv SET ACCESS METHOD heap2; -SELECT amname FROM pg_class c, pg_am am - WHERE c.relam = am.oid AND c.oid = 'heapmv'::regclass; -SELECT COUNT(a), COUNT(1) FILTER(WHERE a=1) FROM heapmv; --- No support for multiple subcommands -ALTER TABLE heaptable SET ACCESS METHOD heap, SET ACCESS METHOD heap2; -ALTER MATERIALIZED VIEW heapmv SET ACCESS METHOD heap, SET ACCESS METHOD heap2; -DROP MATERIALIZED VIEW heapmv; -DROP TABLE heaptable; --- No support for partitioned tables. -CREATE TABLE am_partitioned(x INT, y INT) - PARTITION BY hash (x); -ALTER TABLE am_partitioned SET ACCESS METHOD heap2; -DROP TABLE am_partitioned; - --- Second, create objects in the new AM by changing the default AM -BEGIN; -SET LOCAL default_table_access_method = 'heap2'; - --- following tests should all respect the default AM -CREATE TABLE tableam_tbl_heapx(f1 int); -CREATE TABLE tableam_tblas_heapx AS SELECT * FROM tableam_tbl_heapx; -SELECT INTO tableam_tblselectinto_heapx FROM tableam_tbl_heapx; -CREATE MATERIALIZED VIEW tableam_tblmv_heapx USING heap2 AS SELECT * FROM tableam_tbl_heapx; -CREATE TABLE tableam_parted_heapx (a text, b int) PARTITION BY list (a); -CREATE TABLE tableam_parted_1_heapx PARTITION OF tableam_parted_heapx FOR VALUES IN ('a', 'b'); - --- but an explicitly set AM overrides it -CREATE TABLE tableam_parted_2_heapx PARTITION OF tableam_parted_heapx FOR VALUES IN ('c', 'd') USING heap; - --- sequences, views and foreign servers shouldn't have an AM -CREATE VIEW tableam_view_heapx AS SELECT * FROM tableam_tbl_heapx; -CREATE SEQUENCE tableam_seq_heapx; -CREATE FOREIGN DATA WRAPPER fdw_heap2 VALIDATOR postgresql_fdw_validator; -CREATE SERVER fs_heap2 FOREIGN DATA WRAPPER fdw_heap2 ; -CREATE FOREIGN table tableam_fdw_heapx () SERVER fs_heap2; - --- Verify that new AM was used for tables, matviews, but not for sequences, views and fdws -SELECT - pc.relkind, - pa.amname, - CASE WHEN relkind = 't' THEN - (SELECT 'toast for ' || relname::regclass FROM pg_class pcm WHERE pcm.reltoastrelid = pc.oid) - ELSE - relname::regclass::text - END COLLATE "C" AS relname -FROM pg_class AS pc - LEFT JOIN pg_am AS pa ON (pa.oid = pc.relam) -WHERE pc.relname LIKE 'tableam_%_heapx' -ORDER BY 3, 1, 2; - --- don't want to keep those tables, nor the default -ROLLBACK; - --- Third, check that we can neither create a table using a nonexistent --- AM, nor using an index AM -CREATE TABLE i_am_a_failure() USING ""; -CREATE TABLE i_am_a_failure() USING i_do_not_exist_am; -CREATE TABLE i_am_a_failure() USING "I do not exist AM"; -CREATE TABLE i_am_a_failure() USING "btree"; - --- Drop table access method, which fails as objects depends on it -DROP ACCESS METHOD heap2; - --- we intentionally leave the objects created above alive, to verify pg_dump support diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_function_sql.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_function_sql.sql deleted file mode 100644 index cc0ccd8db1..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_function_sql.sql +++ /dev/null @@ -1,408 +0,0 @@ --- --- CREATE_FUNCTION_SQL --- --- Assorted tests using SQL-language functions --- - --- All objects made in this test are in temp_func_test schema - -CREATE USER regress_unpriv_user; - -CREATE SCHEMA temp_func_test; -GRANT ALL ON SCHEMA temp_func_test TO public; - -SET search_path TO temp_func_test, public; - --- --- Make sanity checks on the pg_proc entries created by CREATE FUNCTION --- - --- --- ARGUMENT and RETURN TYPES --- -CREATE FUNCTION functest_A_1(text, date) RETURNS bool LANGUAGE 'sql' - AS 'SELECT $1 = ''abcd'' AND $2 > ''2001-01-01'''; -CREATE FUNCTION functest_A_2(text[]) RETURNS int LANGUAGE 'sql' - AS 'SELECT $1[1]::int'; -CREATE FUNCTION functest_A_3() RETURNS bool LANGUAGE 'sql' - AS 'SELECT false'; -SELECT proname, prorettype::regtype, proargtypes::regtype[] FROM pg_proc - WHERE oid in ('functest_A_1'::regproc, - 'functest_A_2'::regproc, - 'functest_A_3'::regproc) ORDER BY proname; - -SELECT functest_A_1('abcd', '2020-01-01'); -SELECT functest_A_2(ARRAY['1', '2', '3']); -SELECT functest_A_3(); - --- --- IMMUTABLE | STABLE | VOLATILE --- -CREATE FUNCTION functest_B_1(int) RETURNS bool LANGUAGE 'sql' - AS 'SELECT $1 > 0'; -CREATE FUNCTION functest_B_2(int) RETURNS bool LANGUAGE 'sql' - IMMUTABLE AS 'SELECT $1 > 0'; -CREATE FUNCTION functest_B_3(int) RETURNS bool LANGUAGE 'sql' - STABLE AS 'SELECT $1 = 0'; -CREATE FUNCTION functest_B_4(int) RETURNS bool LANGUAGE 'sql' - VOLATILE AS 'SELECT $1 < 0'; -SELECT proname, provolatile FROM pg_proc - WHERE oid in ('functest_B_1'::regproc, - 'functest_B_2'::regproc, - 'functest_B_3'::regproc, - 'functest_B_4'::regproc) ORDER BY proname; - -ALTER FUNCTION functest_B_2(int) VOLATILE; -ALTER FUNCTION functest_B_3(int) COST 100; -- unrelated change, no effect -SELECT proname, provolatile FROM pg_proc - WHERE oid in ('functest_B_1'::regproc, - 'functest_B_2'::regproc, - 'functest_B_3'::regproc, - 'functest_B_4'::regproc) ORDER BY proname; - --- --- SECURITY DEFINER | INVOKER --- -CREATE FUNCTION functest_C_1(int) RETURNS bool LANGUAGE 'sql' - AS 'SELECT $1 > 0'; -CREATE FUNCTION functest_C_2(int) RETURNS bool LANGUAGE 'sql' - SECURITY DEFINER AS 'SELECT $1 = 0'; -CREATE FUNCTION functest_C_3(int) RETURNS bool LANGUAGE 'sql' - SECURITY INVOKER AS 'SELECT $1 < 0'; -SELECT proname, prosecdef FROM pg_proc - WHERE oid in ('functest_C_1'::regproc, - 'functest_C_2'::regproc, - 'functest_C_3'::regproc) ORDER BY proname; - -ALTER FUNCTION functest_C_1(int) IMMUTABLE; -- unrelated change, no effect -ALTER FUNCTION functest_C_2(int) SECURITY INVOKER; -ALTER FUNCTION functest_C_3(int) SECURITY DEFINER; -SELECT proname, prosecdef FROM pg_proc - WHERE oid in ('functest_C_1'::regproc, - 'functest_C_2'::regproc, - 'functest_C_3'::regproc) ORDER BY proname; - --- --- LEAKPROOF --- -CREATE FUNCTION functest_E_1(int) RETURNS bool LANGUAGE 'sql' - AS 'SELECT $1 > 100'; -CREATE FUNCTION functest_E_2(int) RETURNS bool LANGUAGE 'sql' - LEAKPROOF AS 'SELECT $1 > 100'; -SELECT proname, proleakproof FROM pg_proc - WHERE oid in ('functest_E_1'::regproc, - 'functest_E_2'::regproc) ORDER BY proname; - -ALTER FUNCTION functest_E_1(int) LEAKPROOF; -ALTER FUNCTION functest_E_2(int) STABLE; -- unrelated change, no effect -SELECT proname, proleakproof FROM pg_proc - WHERE oid in ('functest_E_1'::regproc, - 'functest_E_2'::regproc) ORDER BY proname; - -ALTER FUNCTION functest_E_2(int) NOT LEAKPROOF; -- remove leakproof attribute -SELECT proname, proleakproof FROM pg_proc - WHERE oid in ('functest_E_1'::regproc, - 'functest_E_2'::regproc) ORDER BY proname; - --- it takes superuser privilege to turn on leakproof, but not to turn off -ALTER FUNCTION functest_E_1(int) OWNER TO regress_unpriv_user; -ALTER FUNCTION functest_E_2(int) OWNER TO regress_unpriv_user; - -SET SESSION AUTHORIZATION regress_unpriv_user; -SET search_path TO temp_func_test, public; -ALTER FUNCTION functest_E_1(int) NOT LEAKPROOF; -ALTER FUNCTION functest_E_2(int) LEAKPROOF; - -CREATE FUNCTION functest_E_3(int) RETURNS bool LANGUAGE 'sql' - LEAKPROOF AS 'SELECT $1 < 200'; -- fail - -RESET SESSION AUTHORIZATION; - --- --- CALLED ON NULL INPUT | RETURNS NULL ON NULL INPUT | STRICT --- -CREATE FUNCTION functest_F_1(int) RETURNS bool LANGUAGE 'sql' - AS 'SELECT $1 > 50'; -CREATE FUNCTION functest_F_2(int) RETURNS bool LANGUAGE 'sql' - CALLED ON NULL INPUT AS 'SELECT $1 = 50'; -CREATE FUNCTION functest_F_3(int) RETURNS bool LANGUAGE 'sql' - RETURNS NULL ON NULL INPUT AS 'SELECT $1 < 50'; -CREATE FUNCTION functest_F_4(int) RETURNS bool LANGUAGE 'sql' - STRICT AS 'SELECT $1 = 50'; -SELECT proname, proisstrict FROM pg_proc - WHERE oid in ('functest_F_1'::regproc, - 'functest_F_2'::regproc, - 'functest_F_3'::regproc, - 'functest_F_4'::regproc) ORDER BY proname; - -ALTER FUNCTION functest_F_1(int) IMMUTABLE; -- unrelated change, no effect -ALTER FUNCTION functest_F_2(int) STRICT; -ALTER FUNCTION functest_F_3(int) CALLED ON NULL INPUT; -SELECT proname, proisstrict FROM pg_proc - WHERE oid in ('functest_F_1'::regproc, - 'functest_F_2'::regproc, - 'functest_F_3'::regproc, - 'functest_F_4'::regproc) ORDER BY proname; - - --- pg_get_functiondef tests - -SELECT pg_get_functiondef('functest_A_1'::regproc); -SELECT pg_get_functiondef('functest_B_3'::regproc); -SELECT pg_get_functiondef('functest_C_3'::regproc); -SELECT pg_get_functiondef('functest_F_2'::regproc); - - --- --- SQL-standard body --- -CREATE FUNCTION functest_S_1(a text, b date) RETURNS boolean - LANGUAGE SQL - RETURN a = 'abcd' AND b > '2001-01-01'; -CREATE FUNCTION functest_S_2(a text[]) RETURNS int - RETURN a[1]::int; -CREATE FUNCTION functest_S_3() RETURNS boolean - RETURN false; -CREATE FUNCTION functest_S_3a() RETURNS boolean - BEGIN ATOMIC - ;;RETURN false;; - END; - -CREATE FUNCTION functest_S_10(a text, b date) RETURNS boolean - LANGUAGE SQL - BEGIN ATOMIC - SELECT a = 'abcd' AND b > '2001-01-01'; - END; - -CREATE FUNCTION functest_S_13() RETURNS boolean - BEGIN ATOMIC - SELECT 1; - SELECT false; - END; - --- check display of function arguments in sub-SELECT -CREATE TABLE functest1 (i int); -CREATE FUNCTION functest_S_16(a int, b int) RETURNS void - LANGUAGE SQL - BEGIN ATOMIC - INSERT INTO functest1 SELECT a + $2; - END; - --- error: duplicate function body -CREATE FUNCTION functest_S_xxx(x int) RETURNS int - LANGUAGE SQL - AS $$ SELECT x * 2 $$ - RETURN x * 3; - --- polymorphic arguments not allowed in this form -CREATE FUNCTION functest_S_xx(x anyarray) RETURNS anyelement - LANGUAGE SQL - RETURN x[1]; - --- check reporting of parse-analysis errors -CREATE FUNCTION functest_S_xx(x date) RETURNS boolean - LANGUAGE SQL - RETURN x > 1; - --- tricky parsing -CREATE FUNCTION functest_S_15(x int) RETURNS boolean -LANGUAGE SQL -BEGIN ATOMIC - select case when x % 2 = 0 then true else false end; -END; - -SELECT functest_S_1('abcd', '2020-01-01'); -SELECT functest_S_2(ARRAY['1', '2', '3']); -SELECT functest_S_3(); - -SELECT functest_S_10('abcd', '2020-01-01'); -SELECT functest_S_13(); - -SELECT pg_get_functiondef('functest_S_1'::regproc); -SELECT pg_get_functiondef('functest_S_2'::regproc); -SELECT pg_get_functiondef('functest_S_3'::regproc); -SELECT pg_get_functiondef('functest_S_3a'::regproc); -SELECT pg_get_functiondef('functest_S_10'::regproc); -SELECT pg_get_functiondef('functest_S_13'::regproc); -SELECT pg_get_functiondef('functest_S_15'::regproc); -SELECT pg_get_functiondef('functest_S_16'::regproc); - -DROP TABLE functest1 CASCADE; - --- test with views -CREATE TABLE functest3 (a int); -INSERT INTO functest3 VALUES (1), (2); -CREATE VIEW functestv3 AS SELECT * FROM functest3; - -CREATE FUNCTION functest_S_14() RETURNS bigint - RETURN (SELECT count(*) FROM functestv3); - -SELECT functest_S_14(); - -DROP TABLE functest3 CASCADE; - - --- information_schema tests - -CREATE FUNCTION functest_IS_1(a int, b int default 1, c text default 'foo') - RETURNS int - LANGUAGE SQL - AS 'SELECT $1 + $2'; - -CREATE FUNCTION functest_IS_2(out a int, b int default 1) - RETURNS int - LANGUAGE SQL - AS 'SELECT $1'; - -CREATE FUNCTION functest_IS_3(a int default 1, out b int) - RETURNS int - LANGUAGE SQL - AS 'SELECT $1'; - -SELECT routine_name, ordinal_position, parameter_name, parameter_default - FROM information_schema.parameters JOIN information_schema.routines USING (specific_schema, specific_name) - WHERE routine_schema = 'temp_func_test' AND routine_name ~ '^functest_is_' - ORDER BY 1, 2; - -DROP FUNCTION functest_IS_1(int, int, text), functest_IS_2(int), functest_IS_3(int); - --- routine usage views - -CREATE FUNCTION functest_IS_4a() RETURNS int LANGUAGE SQL AS 'SELECT 1'; -CREATE FUNCTION functest_IS_4b(x int DEFAULT functest_IS_4a()) RETURNS int LANGUAGE SQL AS 'SELECT x'; - -CREATE SEQUENCE functest1; -CREATE FUNCTION functest_IS_5(x int DEFAULT nextval('functest1')) - RETURNS int - LANGUAGE SQL - AS 'SELECT x'; - -CREATE FUNCTION functest_IS_6() - RETURNS int - LANGUAGE SQL - RETURN nextval('functest1'); - -CREATE TABLE functest2 (a int, b int); - -CREATE FUNCTION functest_IS_7() - RETURNS int - LANGUAGE SQL - RETURN (SELECT count(a) FROM functest2); - -SELECT r0.routine_name, r1.routine_name - FROM information_schema.routine_routine_usage rru - JOIN information_schema.routines r0 ON r0.specific_name = rru.specific_name - JOIN information_schema.routines r1 ON r1.specific_name = rru.routine_name - WHERE r0.routine_schema = 'temp_func_test' AND - r1.routine_schema = 'temp_func_test' - ORDER BY 1, 2; -SELECT routine_name, sequence_name FROM information_schema.routine_sequence_usage - WHERE routine_schema = 'temp_func_test' - ORDER BY 1, 2; -SELECT routine_name, table_name, column_name FROM information_schema.routine_column_usage - WHERE routine_schema = 'temp_func_test' - ORDER BY 1, 2; -SELECT routine_name, table_name FROM information_schema.routine_table_usage - WHERE routine_schema = 'temp_func_test' - ORDER BY 1, 2; - -DROP FUNCTION functest_IS_4a CASCADE; -DROP SEQUENCE functest1 CASCADE; -DROP TABLE functest2 CASCADE; - - --- overload -CREATE FUNCTION functest_B_2(bigint) RETURNS bool LANGUAGE 'sql' - IMMUTABLE AS 'SELECT $1 > 0'; - -DROP FUNCTION functest_b_1; -DROP FUNCTION functest_b_1; -- error, not found -DROP FUNCTION functest_b_2; -- error, ambiguous - - --- CREATE OR REPLACE tests - -CREATE FUNCTION functest1(a int) RETURNS int LANGUAGE SQL AS 'SELECT $1'; -CREATE OR REPLACE FUNCTION functest1(a int) RETURNS int LANGUAGE SQL WINDOW AS 'SELECT $1'; -CREATE OR REPLACE PROCEDURE functest1(a int) LANGUAGE SQL AS 'SELECT $1'; -DROP FUNCTION functest1(a int); - - --- inlining of set-returning functions - -CREATE TABLE functest3 (a int); -INSERT INTO functest3 VALUES (1), (2), (3); - -CREATE FUNCTION functest_sri1() RETURNS SETOF int -LANGUAGE SQL -STABLE -AS ' - SELECT * FROM functest3; -'; - -SELECT * FROM functest_sri1(); -EXPLAIN (verbose, costs off) SELECT * FROM functest_sri1(); - -CREATE FUNCTION functest_sri2() RETURNS SETOF int -LANGUAGE SQL -STABLE -BEGIN ATOMIC - SELECT * FROM functest3; -END; - -SELECT * FROM functest_sri2(); -EXPLAIN (verbose, costs off) SELECT * FROM functest_sri2(); - -DROP TABLE functest3 CASCADE; - - --- Check behavior of VOID-returning SQL functions - -CREATE FUNCTION voidtest1(a int) RETURNS VOID LANGUAGE SQL AS -$$ SELECT a + 1 $$; -SELECT voidtest1(42); - -CREATE FUNCTION voidtest2(a int, b int) RETURNS VOID LANGUAGE SQL AS -$$ SELECT voidtest1(a + b) $$; -SELECT voidtest2(11,22); - --- currently, we can inline voidtest2 but not voidtest1 -EXPLAIN (verbose, costs off) SELECT voidtest2(11,22); - -CREATE TEMP TABLE sometable(f1 int); - -CREATE FUNCTION voidtest3(a int) RETURNS VOID LANGUAGE SQL AS -$$ INSERT INTO sometable VALUES(a + 1) $$; -SELECT voidtest3(17); - -CREATE FUNCTION voidtest4(a int) RETURNS VOID LANGUAGE SQL AS -$$ INSERT INTO sometable VALUES(a - 1) RETURNING f1 $$; -SELECT voidtest4(39); - -TABLE sometable; - -CREATE FUNCTION voidtest5(a int) RETURNS SETOF VOID LANGUAGE SQL AS -$$ SELECT generate_series(1, a) $$ STABLE; -SELECT * FROM voidtest5(3); - --- Things that shouldn't work: - -CREATE FUNCTION test1 (int) RETURNS int LANGUAGE SQL - AS 'SELECT ''not an integer'';'; - -CREATE FUNCTION test1 (int) RETURNS int LANGUAGE SQL - AS 'not even SQL'; - -CREATE FUNCTION test1 (int) RETURNS int LANGUAGE SQL - AS 'SELECT 1, 2, 3;'; - -CREATE FUNCTION test1 (int) RETURNS int LANGUAGE SQL - AS 'SELECT $2;'; - -CREATE FUNCTION test1 (int) RETURNS int LANGUAGE SQL - AS 'a', 'b'; - --- Cleanup -DROP SCHEMA temp_func_test CASCADE; -DROP USER regress_unpriv_user; -RESET search_path; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_index.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_index.sql deleted file mode 100644 index d8fded3d93..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_index.sql +++ /dev/null @@ -1,1253 +0,0 @@ --- --- CREATE_INDEX --- Create ancillary data structures (i.e. indices) --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - --- --- BTREE --- -CREATE INDEX onek_unique1 ON onek USING btree(unique1 int4_ops); - -CREATE INDEX IF NOT EXISTS onek_unique1 ON onek USING btree(unique1 int4_ops); - -CREATE INDEX IF NOT EXISTS ON onek USING btree(unique1 int4_ops); - -CREATE INDEX onek_unique2 ON onek USING btree(unique2 int4_ops); - -CREATE INDEX onek_hundred ON onek USING btree(hundred int4_ops); - -CREATE INDEX onek_stringu1 ON onek USING btree(stringu1 name_ops); - -CREATE INDEX tenk1_unique1 ON tenk1 USING btree(unique1 int4_ops); - -CREATE INDEX tenk1_unique2 ON tenk1 USING btree(unique2 int4_ops); - -CREATE INDEX tenk1_hundred ON tenk1 USING btree(hundred int4_ops); - -CREATE INDEX tenk1_thous_tenthous ON tenk1 (thousand, tenthous); - -CREATE INDEX tenk2_unique1 ON tenk2 USING btree(unique1 int4_ops); - -CREATE INDEX tenk2_unique2 ON tenk2 USING btree(unique2 int4_ops); - -CREATE INDEX tenk2_hundred ON tenk2 USING btree(hundred int4_ops); - -CREATE INDEX rix ON road USING btree (name text_ops); - -CREATE INDEX iix ON ihighway USING btree (name text_ops); - -CREATE INDEX six ON shighway USING btree (name text_ops); - --- test comments -COMMENT ON INDEX six_wrong IS 'bad index'; -COMMENT ON INDEX six IS 'good index'; -COMMENT ON INDEX six IS NULL; - --- --- BTREE partial indices --- -CREATE INDEX onek2_u1_prtl ON onek2 USING btree(unique1 int4_ops) - where unique1 < 20 or unique1 > 980; - -CREATE INDEX onek2_u2_prtl ON onek2 USING btree(unique2 int4_ops) - where stringu1 < 'B'; - -CREATE INDEX onek2_stu1_prtl ON onek2 USING btree(stringu1 name_ops) - where onek2.stringu1 >= 'J' and onek2.stringu1 < 'K'; - --- --- GiST (rtree-equivalent opclasses only) --- - -CREATE TABLE slow_emp4000 ( - home_base box -); - -CREATE TABLE fast_emp4000 ( - home_base box -); - -\set filename :abs_srcdir '/data/rect.data' -COPY slow_emp4000 FROM :'filename'; - -INSERT INTO fast_emp4000 SELECT * FROM slow_emp4000; - -ANALYZE slow_emp4000; -ANALYZE fast_emp4000; - -CREATE INDEX grect2ind ON fast_emp4000 USING gist (home_base); - --- we want to work with a point_tbl that includes a null -CREATE TEMP TABLE point_tbl AS SELECT * FROM public.point_tbl; -INSERT INTO POINT_TBL(f1) VALUES (NULL); - -CREATE INDEX gpointind ON point_tbl USING gist (f1); - -CREATE TEMP TABLE gpolygon_tbl AS - SELECT polygon(home_base) AS f1 FROM slow_emp4000; -INSERT INTO gpolygon_tbl VALUES ( '(1000,0,0,1000)' ); -INSERT INTO gpolygon_tbl VALUES ( '(0,1000,1000,1000)' ); - -CREATE TEMP TABLE gcircle_tbl AS - SELECT circle(home_base) AS f1 FROM slow_emp4000; - -CREATE INDEX ggpolygonind ON gpolygon_tbl USING gist (f1); - -CREATE INDEX ggcircleind ON gcircle_tbl USING gist (f1); - --- --- Test GiST indexes --- - --- get non-indexed results for comparison purposes - -SET enable_seqscan = ON; -SET enable_indexscan = OFF; -SET enable_bitmapscan = OFF; - -SELECT * FROM fast_emp4000 - WHERE home_base <@ '(200,200),(2000,1000)'::box - ORDER BY (home_base[0])[0]; - -SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box; - -SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL; - -SELECT count(*) FROM gpolygon_tbl WHERE f1 && '(1000,1000,0,0)'::polygon; - -SELECT count(*) FROM gcircle_tbl WHERE f1 && '<(500,500),500>'::circle; - -SELECT count(*) FROM point_tbl WHERE f1 <@ box '(0,0,100,100)'; - -SELECT count(*) FROM point_tbl WHERE box '(0,0,100,100)' @> f1; - -SELECT count(*) FROM point_tbl WHERE f1 <@ polygon '(0,0),(0,100),(100,100),(50,50),(100,0),(0,0)'; - -SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>'; - -SELECT count(*) FROM point_tbl p WHERE p.f1 << '(0.0, 0.0)'; - -SELECT count(*) FROM point_tbl p WHERE p.f1 >> '(0.0, 0.0)'; - -SELECT count(*) FROM point_tbl p WHERE p.f1 <<| '(0.0, 0.0)'; - -SELECT count(*) FROM point_tbl p WHERE p.f1 |>> '(0.0, 0.0)'; - -SELECT count(*) FROM point_tbl p WHERE p.f1 ~= '(-5, -12)'; - -SELECT * FROM point_tbl ORDER BY f1 <-> '0,1'; - -SELECT * FROM point_tbl WHERE f1 IS NULL; - -SELECT * FROM point_tbl WHERE f1 IS NOT NULL ORDER BY f1 <-> '0,1'; - -SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1'; - -SELECT * FROM gpolygon_tbl ORDER BY f1 <-> '(0,0)'::point LIMIT 10; - -SELECT circle_center(f1), round(radius(f1)) as radius FROM gcircle_tbl ORDER BY f1 <-> '(200,300)'::point LIMIT 10; - --- Now check the results from plain indexscan -SET enable_seqscan = OFF; -SET enable_indexscan = ON; -SET enable_bitmapscan = OFF; - -EXPLAIN (COSTS OFF) -SELECT * FROM fast_emp4000 - WHERE home_base <@ '(200,200),(2000,1000)'::box - ORDER BY (home_base[0])[0]; -SELECT * FROM fast_emp4000 - WHERE home_base <@ '(200,200),(2000,1000)'::box - ORDER BY (home_base[0])[0]; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box; -SELECT count(*) FROM fast_emp4000 WHERE home_base && '(1000,1000,0,0)'::box; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL; -SELECT count(*) FROM fast_emp4000 WHERE home_base IS NULL; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM gpolygon_tbl WHERE f1 && '(1000,1000,0,0)'::polygon; -SELECT count(*) FROM gpolygon_tbl WHERE f1 && '(1000,1000,0,0)'::polygon; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM gcircle_tbl WHERE f1 && '<(500,500),500>'::circle; -SELECT count(*) FROM gcircle_tbl WHERE f1 && '<(500,500),500>'::circle; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl WHERE f1 <@ box '(0,0,100,100)'; -SELECT count(*) FROM point_tbl WHERE f1 <@ box '(0,0,100,100)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl WHERE box '(0,0,100,100)' @> f1; -SELECT count(*) FROM point_tbl WHERE box '(0,0,100,100)' @> f1; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl WHERE f1 <@ polygon '(0,0),(0,100),(100,100),(50,50),(100,0),(0,0)'; -SELECT count(*) FROM point_tbl WHERE f1 <@ polygon '(0,0),(0,100),(100,100),(50,50),(100,0),(0,0)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>'; -SELECT count(*) FROM point_tbl WHERE f1 <@ circle '<(50,50),50>'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl p WHERE p.f1 << '(0.0, 0.0)'; -SELECT count(*) FROM point_tbl p WHERE p.f1 << '(0.0, 0.0)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl p WHERE p.f1 >> '(0.0, 0.0)'; -SELECT count(*) FROM point_tbl p WHERE p.f1 >> '(0.0, 0.0)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl p WHERE p.f1 <<| '(0.0, 0.0)'; -SELECT count(*) FROM point_tbl p WHERE p.f1 <<| '(0.0, 0.0)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl p WHERE p.f1 |>> '(0.0, 0.0)'; -SELECT count(*) FROM point_tbl p WHERE p.f1 |>> '(0.0, 0.0)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM point_tbl p WHERE p.f1 ~= '(-5, -12)'; -SELECT count(*) FROM point_tbl p WHERE p.f1 ~= '(-5, -12)'; - -EXPLAIN (COSTS OFF) -SELECT * FROM point_tbl ORDER BY f1 <-> '0,1'; -SELECT * FROM point_tbl ORDER BY f1 <-> '0,1'; - -EXPLAIN (COSTS OFF) -SELECT * FROM point_tbl WHERE f1 IS NULL; -SELECT * FROM point_tbl WHERE f1 IS NULL; - -EXPLAIN (COSTS OFF) -SELECT * FROM point_tbl WHERE f1 IS NOT NULL ORDER BY f1 <-> '0,1'; -SELECT * FROM point_tbl WHERE f1 IS NOT NULL ORDER BY f1 <-> '0,1'; - -EXPLAIN (COSTS OFF) -SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1'; -SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1'; - -EXPLAIN (COSTS OFF) -SELECT * FROM gpolygon_tbl ORDER BY f1 <-> '(0,0)'::point LIMIT 10; -SELECT * FROM gpolygon_tbl ORDER BY f1 <-> '(0,0)'::point LIMIT 10; - -EXPLAIN (COSTS OFF) -SELECT circle_center(f1), round(radius(f1)) as radius FROM gcircle_tbl ORDER BY f1 <-> '(200,300)'::point LIMIT 10; -SELECT circle_center(f1), round(radius(f1)) as radius FROM gcircle_tbl ORDER BY f1 <-> '(200,300)'::point LIMIT 10; - -EXPLAIN (COSTS OFF) -SELECT point(x,x), (SELECT f1 FROM gpolygon_tbl ORDER BY f1 <-> point(x,x) LIMIT 1) as c FROM generate_series(0,10,1) x; -SELECT point(x,x), (SELECT f1 FROM gpolygon_tbl ORDER BY f1 <-> point(x,x) LIMIT 1) as c FROM generate_series(0,10,1) x; - --- Now check the results from bitmap indexscan -SET enable_seqscan = OFF; -SET enable_indexscan = OFF; -SET enable_bitmapscan = ON; - -EXPLAIN (COSTS OFF) -SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1'; -SELECT * FROM point_tbl WHERE f1 <@ '(-10,-10),(10,10)':: box ORDER BY f1 <-> '0,1'; - -RESET enable_seqscan; -RESET enable_indexscan; -RESET enable_bitmapscan; - --- --- GIN over int[] and text[] --- --- Note: GIN currently supports only bitmap scans, not plain indexscans --- - -CREATE TABLE array_index_op_test ( - seqno int4, - i int4[], - t text[] -); - -\set filename :abs_srcdir '/data/array.data' -COPY array_index_op_test FROM :'filename'; -ANALYZE array_index_op_test; - -SELECT * FROM array_index_op_test WHERE i = '{NULL}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i @> '{NULL}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{NULL}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i <@ '{NULL}' ORDER BY seqno; - -SET enable_seqscan = OFF; -SET enable_indexscan = OFF; -SET enable_bitmapscan = ON; - -CREATE INDEX intarrayidx ON array_index_op_test USING gin (i); - -explain (costs off) -SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno; - -SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{32}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i @> '{17}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{17}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i @> '{32,17}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{32,17}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i <@ '{38,34,32,89}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i = '{47,77}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i = '{}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i @> '{}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i <@ '{}' ORDER BY seqno; - -CREATE INDEX textarrayidx ON array_index_op_test USING gin (t); - -explain (costs off) -SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAA72908}' ORDER BY seqno; - -SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAA72908}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t && '{AAAAAAAA72908}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t && '{AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAAA72908,AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t && '{AAAAAAAA72908,AAAAAAAAAA646}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t <@ '{AAAAAAAA72908,AAAAAAAAAAAAAAAAAAA17075,AA88409,AAAAAAAAAAAAAAAAAA36842,AAAAAAA48038,AAAAAAAAAAAAAA10611}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t = '{AAAAAAAAAA646,A87088}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t = '{}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t @> '{}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t && '{}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t <@ '{}' ORDER BY seqno; - --- And try it with a multicolumn GIN index - -DROP INDEX intarrayidx, textarrayidx; - -CREATE INDEX botharrayidx ON array_index_op_test USING gin (i, t); - -SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{32}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t @> '{AAAAAAA80240}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t && '{AAAAAAA80240}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i @> '{32}' AND t && '{AAAAAAA80240}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE i && '{32}' AND t @> '{AAAAAAA80240}' ORDER BY seqno; -SELECT * FROM array_index_op_test WHERE t = '{}' ORDER BY seqno; - -RESET enable_seqscan; -RESET enable_indexscan; -RESET enable_bitmapscan; - --- --- Try a GIN index with a lot of items with same key. (GIN creates a posting --- tree when there are enough duplicates) --- -CREATE TABLE array_gin_test (a int[]); - -INSERT INTO array_gin_test SELECT ARRAY[1, g%5, g] FROM generate_series(1, 10000) g; - -CREATE INDEX array_gin_test_idx ON array_gin_test USING gin (a); - -SELECT COUNT(*) FROM array_gin_test WHERE a @> '{2}'; - -DROP TABLE array_gin_test; - --- --- Test GIN index's reloptions --- -CREATE INDEX gin_relopts_test ON array_index_op_test USING gin (i) - WITH (FASTUPDATE=on, GIN_PENDING_LIST_LIMIT=128); -\d+ gin_relopts_test - --- --- HASH --- -CREATE UNLOGGED TABLE unlogged_hash_table (id int4); -CREATE INDEX unlogged_hash_index ON unlogged_hash_table USING hash (id int4_ops); -DROP TABLE unlogged_hash_table; - --- CREATE INDEX hash_ovfl_index ON hash_ovfl_heap USING hash (x int4_ops); - --- Test hash index build tuplesorting. Force hash tuplesort using low --- maintenance_work_mem setting and fillfactor: -SET maintenance_work_mem = '1MB'; -CREATE INDEX hash_tuplesort_idx ON tenk1 USING hash (stringu1 name_ops) WITH (fillfactor = 10); -EXPLAIN (COSTS OFF) -SELECT count(*) FROM tenk1 WHERE stringu1 = 'TVAAAA'; -SELECT count(*) FROM tenk1 WHERE stringu1 = 'TVAAAA'; -DROP INDEX hash_tuplesort_idx; -RESET maintenance_work_mem; - - --- --- Test unique null behavior --- -CREATE TABLE unique_tbl (i int, t text); - -CREATE UNIQUE INDEX unique_idx1 ON unique_tbl (i) NULLS DISTINCT; -CREATE UNIQUE INDEX unique_idx2 ON unique_tbl (i) NULLS NOT DISTINCT; - -INSERT INTO unique_tbl VALUES (1, 'one'); -INSERT INTO unique_tbl VALUES (2, 'two'); -INSERT INTO unique_tbl VALUES (3, 'three'); -INSERT INTO unique_tbl VALUES (4, 'four'); -INSERT INTO unique_tbl VALUES (5, 'one'); -INSERT INTO unique_tbl (t) VALUES ('six'); -INSERT INTO unique_tbl (t) VALUES ('seven'); -- error from unique_idx2 - -DROP INDEX unique_idx1, unique_idx2; - -INSERT INTO unique_tbl (t) VALUES ('seven'); - --- build indexes on filled table -CREATE UNIQUE INDEX unique_idx3 ON unique_tbl (i) NULLS DISTINCT; -- ok -CREATE UNIQUE INDEX unique_idx4 ON unique_tbl (i) NULLS NOT DISTINCT; -- error - -DELETE FROM unique_tbl WHERE t = 'seven'; - -CREATE UNIQUE INDEX unique_idx4 ON unique_tbl (i) NULLS NOT DISTINCT; -- ok now - -\d unique_tbl -\d unique_idx3 -\d unique_idx4 -SELECT pg_get_indexdef('unique_idx3'::regclass); -SELECT pg_get_indexdef('unique_idx4'::regclass); - -DROP TABLE unique_tbl; - - --- --- Test functional index --- -CREATE TABLE func_index_heap (f1 text, f2 text); -CREATE UNIQUE INDEX func_index_index on func_index_heap (textcat(f1,f2)); - -INSERT INTO func_index_heap VALUES('ABC','DEF'); -INSERT INTO func_index_heap VALUES('AB','CDEFG'); -INSERT INTO func_index_heap VALUES('QWE','RTY'); --- this should fail because of unique index: -INSERT INTO func_index_heap VALUES('ABCD', 'EF'); --- but this shouldn't: -INSERT INTO func_index_heap VALUES('QWERTY'); - --- while we're here, see that the metadata looks sane -\d func_index_heap -\d func_index_index - - --- --- Same test, expressional index --- -DROP TABLE func_index_heap; -CREATE TABLE func_index_heap (f1 text, f2 text); -CREATE UNIQUE INDEX func_index_index on func_index_heap ((f1 || f2) text_ops); - -INSERT INTO func_index_heap VALUES('ABC','DEF'); -INSERT INTO func_index_heap VALUES('AB','CDEFG'); -INSERT INTO func_index_heap VALUES('QWE','RTY'); --- this should fail because of unique index: -INSERT INTO func_index_heap VALUES('ABCD', 'EF'); --- but this shouldn't: -INSERT INTO func_index_heap VALUES('QWERTY'); - --- while we're here, see that the metadata looks sane -\d func_index_heap -\d func_index_index - --- this should fail because of unsafe column type (anonymous record) -create index on func_index_heap ((f1 || f2), (row(f1, f2))); - - --- --- Test unique index with included columns --- -CREATE TABLE covering_index_heap (f1 int, f2 int, f3 text); -CREATE UNIQUE INDEX covering_index_index on covering_index_heap (f1,f2) INCLUDE(f3); - -INSERT INTO covering_index_heap VALUES(1,1,'AAA'); -INSERT INTO covering_index_heap VALUES(1,2,'AAA'); --- this should fail because of unique index on f1,f2: -INSERT INTO covering_index_heap VALUES(1,2,'BBB'); --- and this shouldn't: -INSERT INTO covering_index_heap VALUES(1,4,'AAA'); --- Try to build index on table that already contains data -CREATE UNIQUE INDEX covering_pkey on covering_index_heap (f1,f2) INCLUDE(f3); --- Try to use existing covering index as primary key -ALTER TABLE covering_index_heap ADD CONSTRAINT covering_pkey PRIMARY KEY USING INDEX -covering_pkey; -DROP TABLE covering_index_heap; - --- --- Try some concurrent index builds --- --- Unfortunately this only tests about half the code paths because there are --- no concurrent updates happening to the table at the same time. - -CREATE TABLE concur_heap (f1 text, f2 text); --- empty table -CREATE INDEX CONCURRENTLY concur_index1 ON concur_heap(f2,f1); -CREATE INDEX CONCURRENTLY IF NOT EXISTS concur_index1 ON concur_heap(f2,f1); -INSERT INTO concur_heap VALUES ('a','b'); -INSERT INTO concur_heap VALUES ('b','b'); --- unique index -CREATE UNIQUE INDEX CONCURRENTLY concur_index2 ON concur_heap(f1); -CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS concur_index2 ON concur_heap(f1); --- check if constraint is set up properly to be enforced -INSERT INTO concur_heap VALUES ('b','x'); --- check if constraint is enforced properly at build time -CREATE UNIQUE INDEX CONCURRENTLY concur_index3 ON concur_heap(f2); --- test that expression indexes and partial indexes work concurrently -CREATE INDEX CONCURRENTLY concur_index4 on concur_heap(f2) WHERE f1='a'; -CREATE INDEX CONCURRENTLY concur_index5 on concur_heap(f2) WHERE f1='x'; --- here we also check that you can default the index name -CREATE INDEX CONCURRENTLY on concur_heap((f2||f1)); --- You can't do a concurrent index build in a transaction -BEGIN; -CREATE INDEX CONCURRENTLY concur_index7 ON concur_heap(f1); -COMMIT; --- test where predicate is able to do a transactional update during --- a concurrent build before switching pg_index state flags. -CREATE FUNCTION predicate_stable() RETURNS bool IMMUTABLE -LANGUAGE plpgsql AS $$ -BEGIN - EXECUTE 'SELECT txid_current()'; - RETURN true; -END; $$; -CREATE INDEX CONCURRENTLY concur_index8 ON concur_heap (f1) - WHERE predicate_stable(); -DROP INDEX concur_index8; -DROP FUNCTION predicate_stable(); - --- But you can do a regular index build in a transaction -BEGIN; -CREATE INDEX std_index on concur_heap(f2); -COMMIT; - --- Failed builds are left invalid by VACUUM FULL, fixed by REINDEX -VACUUM FULL concur_heap; -REINDEX TABLE concur_heap; -DELETE FROM concur_heap WHERE f1 = 'b'; -VACUUM FULL concur_heap; -\d concur_heap -REINDEX TABLE concur_heap; -\d concur_heap - --- Temporary tables with concurrent builds and on-commit actions --- CONCURRENTLY used with CREATE INDEX and DROP INDEX is ignored. --- PRESERVE ROWS, the default. -CREATE TEMP TABLE concur_temp (f1 int, f2 text) - ON COMMIT PRESERVE ROWS; -INSERT INTO concur_temp VALUES (1, 'foo'), (2, 'bar'); -CREATE INDEX CONCURRENTLY concur_temp_ind ON concur_temp(f1); -DROP INDEX CONCURRENTLY concur_temp_ind; -DROP TABLE concur_temp; --- ON COMMIT DROP -BEGIN; -CREATE TEMP TABLE concur_temp (f1 int, f2 text) - ON COMMIT DROP; -INSERT INTO concur_temp VALUES (1, 'foo'), (2, 'bar'); --- Fails when running in a transaction. -CREATE INDEX CONCURRENTLY concur_temp_ind ON concur_temp(f1); -COMMIT; --- ON COMMIT DELETE ROWS -CREATE TEMP TABLE concur_temp (f1 int, f2 text) - ON COMMIT DELETE ROWS; -INSERT INTO concur_temp VALUES (1, 'foo'), (2, 'bar'); -CREATE INDEX CONCURRENTLY concur_temp_ind ON concur_temp(f1); -DROP INDEX CONCURRENTLY concur_temp_ind; -DROP TABLE concur_temp; - --- --- Try some concurrent index drops --- -DROP INDEX CONCURRENTLY "concur_index2"; -- works -DROP INDEX CONCURRENTLY IF EXISTS "concur_index2"; -- notice - --- failures -DROP INDEX CONCURRENTLY "concur_index2", "concur_index3"; -BEGIN; -DROP INDEX CONCURRENTLY "concur_index5"; -ROLLBACK; - --- successes -DROP INDEX CONCURRENTLY IF EXISTS "concur_index3"; -DROP INDEX CONCURRENTLY "concur_index4"; -DROP INDEX CONCURRENTLY "concur_index5"; -DROP INDEX CONCURRENTLY "concur_index1"; -DROP INDEX CONCURRENTLY "concur_heap_expr_idx"; - -\d concur_heap - -DROP TABLE concur_heap; - --- --- Test ADD CONSTRAINT USING INDEX --- - -CREATE TABLE cwi_test( a int , b varchar(10), c char); - --- add some data so that all tests have something to work with. - -INSERT INTO cwi_test VALUES(1, 2), (3, 4), (5, 6); - -CREATE UNIQUE INDEX cwi_uniq_idx ON cwi_test(a , b); -ALTER TABLE cwi_test ADD primary key USING INDEX cwi_uniq_idx; - -\d cwi_test -\d cwi_uniq_idx - -CREATE UNIQUE INDEX cwi_uniq2_idx ON cwi_test(b , a); -ALTER TABLE cwi_test DROP CONSTRAINT cwi_uniq_idx, - ADD CONSTRAINT cwi_replaced_pkey PRIMARY KEY - USING INDEX cwi_uniq2_idx; - -\d cwi_test -\d cwi_replaced_pkey - -DROP INDEX cwi_replaced_pkey; -- Should fail; a constraint depends on it - --- Check that non-default index options are rejected -CREATE UNIQUE INDEX cwi_uniq3_idx ON cwi_test(a desc); -ALTER TABLE cwi_test ADD UNIQUE USING INDEX cwi_uniq3_idx; -- fail -CREATE UNIQUE INDEX cwi_uniq4_idx ON cwi_test(b collate "POSIX"); -ALTER TABLE cwi_test ADD UNIQUE USING INDEX cwi_uniq4_idx; -- fail - -DROP TABLE cwi_test; - --- ADD CONSTRAINT USING INDEX is forbidden on partitioned tables -CREATE TABLE cwi_test(a int) PARTITION BY hash (a); -create unique index on cwi_test (a); -alter table cwi_test add primary key using index cwi_test_a_idx ; -DROP TABLE cwi_test; - --- --- Check handling of indexes on system columns --- -CREATE TABLE syscol_table (a INT); - --- System columns cannot be indexed -CREATE INDEX ON syscolcol_table (ctid); - --- nor used in expressions -CREATE INDEX ON syscol_table ((ctid >= '(1000,0)')); - --- nor used in predicates -CREATE INDEX ON syscol_table (a) WHERE ctid >= '(1000,0)'; - -DROP TABLE syscol_table; - --- --- Tests for IS NULL/IS NOT NULL with b-tree indexes --- - -CREATE TABLE onek_with_null AS SELECT unique1, unique2 FROM onek; -INSERT INTO onek_with_null (unique1,unique2) VALUES (NULL, -1), (NULL, NULL); -CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2,unique1); - -SET enable_seqscan = OFF; -SET enable_indexscan = ON; -SET enable_bitmapscan = ON; - -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL AND unique1 > 500; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique1 > 500; - -DROP INDEX onek_nulltest; - -CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2 desc,unique1); - -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL AND unique1 > 500; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique1 > 500; - -DROP INDEX onek_nulltest; - -CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2 desc nulls last,unique1); - -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL AND unique1 > 500; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique1 > 500; - -DROP INDEX onek_nulltest; - -CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2 nulls first,unique1); - -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique2 IS NOT NULL; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NOT NULL AND unique1 > 500; -SELECT count(*) FROM onek_with_null WHERE unique1 IS NULL AND unique1 > 500; - -DROP INDEX onek_nulltest; - --- Check initial-positioning logic too - -CREATE UNIQUE INDEX onek_nulltest ON onek_with_null (unique2); - -SET enable_seqscan = OFF; -SET enable_indexscan = ON; -SET enable_bitmapscan = OFF; - -SELECT unique1, unique2 FROM onek_with_null - ORDER BY unique2 LIMIT 2; -SELECT unique1, unique2 FROM onek_with_null WHERE unique2 >= -1 - ORDER BY unique2 LIMIT 2; -SELECT unique1, unique2 FROM onek_with_null WHERE unique2 >= 0 - ORDER BY unique2 LIMIT 2; - -SELECT unique1, unique2 FROM onek_with_null - ORDER BY unique2 DESC LIMIT 2; -SELECT unique1, unique2 FROM onek_with_null WHERE unique2 >= -1 - ORDER BY unique2 DESC LIMIT 2; -SELECT unique1, unique2 FROM onek_with_null WHERE unique2 < 999 - ORDER BY unique2 DESC LIMIT 2; - -RESET enable_seqscan; -RESET enable_indexscan; -RESET enable_bitmapscan; - -DROP TABLE onek_with_null; - --- --- Check bitmap index path planning --- - -EXPLAIN (COSTS OFF) -SELECT * FROM tenk1 - WHERE thousand = 42 AND (tenthous = 1 OR tenthous = 3 OR tenthous = 42); -SELECT * FROM tenk1 - WHERE thousand = 42 AND (tenthous = 1 OR tenthous = 3 OR tenthous = 42); - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM tenk1 - WHERE hundred = 42 AND (thousand = 42 OR thousand = 99); -SELECT count(*) FROM tenk1 - WHERE hundred = 42 AND (thousand = 42 OR thousand = 99); - --- --- Check behavior with duplicate index column contents --- - -CREATE TABLE dupindexcols AS - SELECT unique1 as id, stringu2::text as f1 FROM tenk1; -CREATE INDEX dupindexcols_i ON dupindexcols (f1, id, f1 text_pattern_ops); -ANALYZE dupindexcols; - -EXPLAIN (COSTS OFF) - SELECT count(*) FROM dupindexcols - WHERE f1 BETWEEN 'WA' AND 'ZZZ' and id < 1000 and f1 ~<~ 'YX'; -SELECT count(*) FROM dupindexcols - WHERE f1 BETWEEN 'WA' AND 'ZZZ' and id < 1000 and f1 ~<~ 'YX'; - --- --- Check ordering of =ANY indexqual results (bug in 9.2.0) --- - -explain (costs off) -SELECT unique1 FROM tenk1 -WHERE unique1 IN (1,42,7) -ORDER BY unique1; - -SELECT unique1 FROM tenk1 -WHERE unique1 IN (1,42,7) -ORDER BY unique1; - -explain (costs off) -SELECT thousand, tenthous FROM tenk1 -WHERE thousand < 2 AND tenthous IN (1001,3000) -ORDER BY thousand; - -SELECT thousand, tenthous FROM tenk1 -WHERE thousand < 2 AND tenthous IN (1001,3000) -ORDER BY thousand; - -SET enable_indexonlyscan = OFF; - -explain (costs off) -SELECT thousand, tenthous FROM tenk1 -WHERE thousand < 2 AND tenthous IN (1001,3000) -ORDER BY thousand; - -SELECT thousand, tenthous FROM tenk1 -WHERE thousand < 2 AND tenthous IN (1001,3000) -ORDER BY thousand; - -RESET enable_indexonlyscan; - --- --- Check elimination of constant-NULL subexpressions --- - -explain (costs off) - select * from tenk1 where (thousand, tenthous) in ((1,1001), (null,null)); - --- --- Check matching of boolean index columns to WHERE conditions and sort keys --- - -create temp table boolindex (b bool, i int, unique(b, i), junk float); - -explain (costs off) - select * from boolindex order by b, i limit 10; -explain (costs off) - select * from boolindex where b order by i limit 10; -explain (costs off) - select * from boolindex where b = true order by i desc limit 10; -explain (costs off) - select * from boolindex where not b order by i limit 10; -explain (costs off) - select * from boolindex where b is true order by i desc limit 10; -explain (costs off) - select * from boolindex where b is false order by i desc limit 10; - --- --- REINDEX (VERBOSE) --- -CREATE TABLE reindex_verbose(id integer primary key); -\set VERBOSITY terse \\ -- suppress machine-dependent details -REINDEX (VERBOSE) TABLE reindex_verbose; -\set VERBOSITY default -DROP TABLE reindex_verbose; - --- --- REINDEX CONCURRENTLY --- -CREATE TABLE concur_reindex_tab (c1 int); --- REINDEX -REINDEX TABLE concur_reindex_tab; -- notice -REINDEX (CONCURRENTLY) TABLE concur_reindex_tab; -- notice -ALTER TABLE concur_reindex_tab ADD COLUMN c2 text; -- add toast index --- Normal index with integer column -CREATE UNIQUE INDEX concur_reindex_ind1 ON concur_reindex_tab(c1); --- Normal index with text column -CREATE INDEX concur_reindex_ind2 ON concur_reindex_tab(c2); --- UNIQUE index with expression -CREATE UNIQUE INDEX concur_reindex_ind3 ON concur_reindex_tab(abs(c1)); --- Duplicate column names -CREATE INDEX concur_reindex_ind4 ON concur_reindex_tab(c1, c1, c2); --- Create table for check on foreign key dependence switch with indexes swapped -ALTER TABLE concur_reindex_tab ADD PRIMARY KEY USING INDEX concur_reindex_ind1; -CREATE TABLE concur_reindex_tab2 (c1 int REFERENCES concur_reindex_tab); -INSERT INTO concur_reindex_tab VALUES (1, 'a'); -INSERT INTO concur_reindex_tab VALUES (2, 'a'); --- Reindex concurrently of exclusion constraint currently not supported -CREATE TABLE concur_reindex_tab3 (c1 int, c2 int4range, EXCLUDE USING gist (c2 WITH &&)); -INSERT INTO concur_reindex_tab3 VALUES (3, '[1,2]'); -REINDEX INDEX CONCURRENTLY concur_reindex_tab3_c2_excl; -- error -REINDEX TABLE CONCURRENTLY concur_reindex_tab3; -- succeeds with warning -INSERT INTO concur_reindex_tab3 VALUES (4, '[2,4]'); --- Check materialized views -CREATE MATERIALIZED VIEW concur_reindex_matview AS SELECT * FROM concur_reindex_tab; --- Dependency lookup before and after the follow-up REINDEX commands. --- These should remain consistent. -SELECT pg_describe_object(classid, objid, objsubid) as obj, - pg_describe_object(refclassid,refobjid,refobjsubid) as objref, - deptype -FROM pg_depend -WHERE classid = 'pg_class'::regclass AND - objid in ('concur_reindex_tab'::regclass, - 'concur_reindex_ind1'::regclass, - 'concur_reindex_ind2'::regclass, - 'concur_reindex_ind3'::regclass, - 'concur_reindex_ind4'::regclass, - 'concur_reindex_matview'::regclass) - ORDER BY 1, 2; -REINDEX INDEX CONCURRENTLY concur_reindex_ind1; -REINDEX TABLE CONCURRENTLY concur_reindex_tab; -REINDEX TABLE CONCURRENTLY concur_reindex_matview; -SELECT pg_describe_object(classid, objid, objsubid) as obj, - pg_describe_object(refclassid,refobjid,refobjsubid) as objref, - deptype -FROM pg_depend -WHERE classid = 'pg_class'::regclass AND - objid in ('concur_reindex_tab'::regclass, - 'concur_reindex_ind1'::regclass, - 'concur_reindex_ind2'::regclass, - 'concur_reindex_ind3'::regclass, - 'concur_reindex_ind4'::regclass, - 'concur_reindex_matview'::regclass) - ORDER BY 1, 2; --- Check that comments are preserved -CREATE TABLE testcomment (i int); -CREATE INDEX testcomment_idx1 ON testcomment (i); -COMMENT ON INDEX testcomment_idx1 IS 'test comment'; -SELECT obj_description('testcomment_idx1'::regclass, 'pg_class'); -REINDEX TABLE testcomment; -SELECT obj_description('testcomment_idx1'::regclass, 'pg_class'); -REINDEX TABLE CONCURRENTLY testcomment ; -SELECT obj_description('testcomment_idx1'::regclass, 'pg_class'); -DROP TABLE testcomment; --- Check that indisclustered updates are preserved -CREATE TABLE concur_clustered(i int); -CREATE INDEX concur_clustered_i_idx ON concur_clustered(i); -ALTER TABLE concur_clustered CLUSTER ON concur_clustered_i_idx; -REINDEX TABLE CONCURRENTLY concur_clustered; -SELECT indexrelid::regclass, indisclustered FROM pg_index - WHERE indrelid = 'concur_clustered'::regclass; -DROP TABLE concur_clustered; --- Check that indisreplident updates are preserved. -CREATE TABLE concur_replident(i int NOT NULL); -CREATE UNIQUE INDEX concur_replident_i_idx ON concur_replident(i); -ALTER TABLE concur_replident REPLICA IDENTITY - USING INDEX concur_replident_i_idx; -SELECT indexrelid::regclass, indisreplident FROM pg_index - WHERE indrelid = 'concur_replident'::regclass; -REINDEX TABLE CONCURRENTLY concur_replident; -SELECT indexrelid::regclass, indisreplident FROM pg_index - WHERE indrelid = 'concur_replident'::regclass; -DROP TABLE concur_replident; --- Check that opclass parameters are preserved -CREATE TABLE concur_appclass_tab(i tsvector, j tsvector, k tsvector); -CREATE INDEX concur_appclass_ind on concur_appclass_tab - USING gist (i tsvector_ops (siglen='1000'), j tsvector_ops (siglen='500')); -CREATE INDEX concur_appclass_ind_2 on concur_appclass_tab - USING gist (k tsvector_ops (siglen='300'), j tsvector_ops); -REINDEX TABLE CONCURRENTLY concur_appclass_tab; -\d concur_appclass_tab -DROP TABLE concur_appclass_tab; - --- Partitions --- Create some partitioned tables -CREATE TABLE concur_reindex_part (c1 int, c2 int) PARTITION BY RANGE (c1); -CREATE TABLE concur_reindex_part_0 PARTITION OF concur_reindex_part - FOR VALUES FROM (0) TO (10) PARTITION BY list (c2); -CREATE TABLE concur_reindex_part_0_1 PARTITION OF concur_reindex_part_0 - FOR VALUES IN (1); -CREATE TABLE concur_reindex_part_0_2 PARTITION OF concur_reindex_part_0 - FOR VALUES IN (2); --- This partitioned table will have no partitions. -CREATE TABLE concur_reindex_part_10 PARTITION OF concur_reindex_part - FOR VALUES FROM (10) TO (20) PARTITION BY list (c2); --- Create some partitioned indexes -CREATE INDEX concur_reindex_part_index ON ONLY concur_reindex_part (c1); -CREATE INDEX concur_reindex_part_index_0 ON ONLY concur_reindex_part_0 (c1); -ALTER INDEX concur_reindex_part_index ATTACH PARTITION concur_reindex_part_index_0; --- This partitioned index will have no partitions. -CREATE INDEX concur_reindex_part_index_10 ON ONLY concur_reindex_part_10 (c1); -ALTER INDEX concur_reindex_part_index ATTACH PARTITION concur_reindex_part_index_10; -CREATE INDEX concur_reindex_part_index_0_1 ON ONLY concur_reindex_part_0_1 (c1); -ALTER INDEX concur_reindex_part_index_0 ATTACH PARTITION concur_reindex_part_index_0_1; -CREATE INDEX concur_reindex_part_index_0_2 ON ONLY concur_reindex_part_0_2 (c1); -ALTER INDEX concur_reindex_part_index_0 ATTACH PARTITION concur_reindex_part_index_0_2; -SELECT relid, parentrelid, level FROM pg_partition_tree('concur_reindex_part_index') - ORDER BY relid, level; -SELECT relid, parentrelid, level FROM pg_partition_tree('concur_reindex_part_index') - ORDER BY relid, level; --- REINDEX should preserve dependencies of partition tree. -SELECT pg_describe_object(classid, objid, objsubid) as obj, - pg_describe_object(refclassid,refobjid,refobjsubid) as objref, - deptype -FROM pg_depend -WHERE classid = 'pg_class'::regclass AND - objid in ('concur_reindex_part'::regclass, - 'concur_reindex_part_0'::regclass, - 'concur_reindex_part_0_1'::regclass, - 'concur_reindex_part_0_2'::regclass, - 'concur_reindex_part_index'::regclass, - 'concur_reindex_part_index_0'::regclass, - 'concur_reindex_part_index_0_1'::regclass, - 'concur_reindex_part_index_0_2'::regclass) - ORDER BY 1, 2; -REINDEX INDEX CONCURRENTLY concur_reindex_part_index_0_1; -REINDEX INDEX CONCURRENTLY concur_reindex_part_index_0_2; -SELECT relid, parentrelid, level FROM pg_partition_tree('concur_reindex_part_index') - ORDER BY relid, level; -REINDEX TABLE CONCURRENTLY concur_reindex_part_0_1; -REINDEX TABLE CONCURRENTLY concur_reindex_part_0_2; -SELECT pg_describe_object(classid, objid, objsubid) as obj, - pg_describe_object(refclassid,refobjid,refobjsubid) as objref, - deptype -FROM pg_depend -WHERE classid = 'pg_class'::regclass AND - objid in ('concur_reindex_part'::regclass, - 'concur_reindex_part_0'::regclass, - 'concur_reindex_part_0_1'::regclass, - 'concur_reindex_part_0_2'::regclass, - 'concur_reindex_part_index'::regclass, - 'concur_reindex_part_index_0'::regclass, - 'concur_reindex_part_index_0_1'::regclass, - 'concur_reindex_part_index_0_2'::regclass) - ORDER BY 1, 2; -SELECT relid, parentrelid, level FROM pg_partition_tree('concur_reindex_part_index') - ORDER BY relid, level; - --- REINDEX for partitioned indexes --- REINDEX TABLE fails for partitioned indexes --- Top-most parent index -REINDEX TABLE concur_reindex_part_index; -- error -REINDEX TABLE CONCURRENTLY concur_reindex_part_index; -- error --- Partitioned index with no leaves -REINDEX TABLE concur_reindex_part_index_10; -- error -REINDEX TABLE CONCURRENTLY concur_reindex_part_index_10; -- error --- Cannot run in a transaction block -BEGIN; -REINDEX INDEX concur_reindex_part_index; -ROLLBACK; --- Helper functions to track changes of relfilenodes in a partition tree. --- Create a table tracking the relfilenode state. -CREATE OR REPLACE FUNCTION create_relfilenode_part(relname text, indname text) - RETURNS VOID AS - $func$ - BEGIN - EXECUTE format(' - CREATE TABLE %I AS - SELECT oid, relname, relfilenode, relkind, reltoastrelid - FROM pg_class - WHERE oid IN - (SELECT relid FROM pg_partition_tree(''%I''));', - relname, indname); - END - $func$ LANGUAGE plpgsql; -CREATE OR REPLACE FUNCTION compare_relfilenode_part(tabname text) - RETURNS TABLE (relname name, relkind "char", state text) AS - $func$ - BEGIN - RETURN QUERY EXECUTE - format( - 'SELECT b.relname, - b.relkind, - CASE WHEN a.relfilenode = b.relfilenode THEN ''relfilenode is unchanged'' - ELSE ''relfilenode has changed'' END - -- Do not join with OID here as CONCURRENTLY changes it. - FROM %I b JOIN pg_class a ON b.relname = a.relname - ORDER BY 1;', tabname); - END - $func$ LANGUAGE plpgsql; --- Check that expected relfilenodes are changed, non-concurrent case. -SELECT create_relfilenode_part('reindex_index_status', 'concur_reindex_part_index'); -REINDEX INDEX concur_reindex_part_index; -SELECT * FROM compare_relfilenode_part('reindex_index_status'); -DROP TABLE reindex_index_status; --- concurrent case. -SELECT create_relfilenode_part('reindex_index_status', 'concur_reindex_part_index'); -REINDEX INDEX CONCURRENTLY concur_reindex_part_index; -SELECT * FROM compare_relfilenode_part('reindex_index_status'); -DROP TABLE reindex_index_status; - --- REINDEX for partitioned tables --- REINDEX INDEX fails for partitioned tables --- Top-most parent -REINDEX INDEX concur_reindex_part; -- error -REINDEX INDEX CONCURRENTLY concur_reindex_part; -- error --- Partitioned with no leaves -REINDEX INDEX concur_reindex_part_10; -- error -REINDEX INDEX CONCURRENTLY concur_reindex_part_10; -- error --- Cannot run in a transaction block -BEGIN; -REINDEX TABLE concur_reindex_part; -ROLLBACK; --- Check that expected relfilenodes are changed, non-concurrent case. --- Note that the partition tree changes of the *indexes* need to be checked. -SELECT create_relfilenode_part('reindex_index_status', 'concur_reindex_part_index'); -REINDEX TABLE concur_reindex_part; -SELECT * FROM compare_relfilenode_part('reindex_index_status'); -DROP TABLE reindex_index_status; --- concurrent case. -SELECT create_relfilenode_part('reindex_index_status', 'concur_reindex_part_index'); -REINDEX TABLE CONCURRENTLY concur_reindex_part; -SELECT * FROM compare_relfilenode_part('reindex_index_status'); -DROP TABLE reindex_index_status; - -DROP FUNCTION create_relfilenode_part; -DROP FUNCTION compare_relfilenode_part; - --- Cleanup of partition tree used for REINDEX test. -DROP TABLE concur_reindex_part; - --- Check errors --- Cannot run inside a transaction block -BEGIN; -REINDEX TABLE CONCURRENTLY concur_reindex_tab; -COMMIT; -REINDEX TABLE CONCURRENTLY pg_class; -- no catalog relation -REINDEX INDEX CONCURRENTLY pg_class_oid_index; -- no catalog index --- These are the toast table and index of pg_authid. -REINDEX TABLE CONCURRENTLY pg_toast.pg_toast_1260; -- no catalog toast table -REINDEX INDEX CONCURRENTLY pg_toast.pg_toast_1260_index; -- no catalog toast index -REINDEX SYSTEM CONCURRENTLY postgres; -- not allowed for SYSTEM --- Warns about catalog relations -REINDEX SCHEMA CONCURRENTLY pg_catalog; - --- Check the relation status, there should not be invalid indexes -\d concur_reindex_tab -DROP MATERIALIZED VIEW concur_reindex_matview; -DROP TABLE concur_reindex_tab, concur_reindex_tab2, concur_reindex_tab3; - --- Check handling of invalid indexes -CREATE TABLE concur_reindex_tab4 (c1 int); -INSERT INTO concur_reindex_tab4 VALUES (1), (1), (2); --- This trick creates an invalid index. -CREATE UNIQUE INDEX CONCURRENTLY concur_reindex_ind5 ON concur_reindex_tab4 (c1); --- Reindexing concurrently this index fails with the same failure. --- The extra index created is itself invalid, and can be dropped. -REINDEX INDEX CONCURRENTLY concur_reindex_ind5; -\d concur_reindex_tab4 -DROP INDEX concur_reindex_ind5_ccnew; --- This makes the previous failure go away, so the index can become valid. -DELETE FROM concur_reindex_tab4 WHERE c1 = 1; --- The invalid index is not processed when running REINDEX TABLE. -REINDEX TABLE CONCURRENTLY concur_reindex_tab4; -\d concur_reindex_tab4 --- But it is fixed with REINDEX INDEX. -REINDEX INDEX CONCURRENTLY concur_reindex_ind5; -\d concur_reindex_tab4 -DROP TABLE concur_reindex_tab4; - --- Check handling of indexes with expressions and predicates. The --- definitions of the rebuilt indexes should match the original --- definitions. -CREATE TABLE concur_exprs_tab (c1 int , c2 boolean); -INSERT INTO concur_exprs_tab (c1, c2) VALUES (1369652450, FALSE), - (414515746, TRUE), - (897778963, FALSE); -CREATE UNIQUE INDEX concur_exprs_index_expr - ON concur_exprs_tab ((c1::text COLLATE "C")); -CREATE UNIQUE INDEX concur_exprs_index_pred ON concur_exprs_tab (c1) - WHERE (c1::text > 500000000::text COLLATE "C"); -CREATE UNIQUE INDEX concur_exprs_index_pred_2 - ON concur_exprs_tab ((1 / c1)) - WHERE ('-H') >= (c2::TEXT) COLLATE "C"; -ALTER INDEX concur_exprs_index_expr ALTER COLUMN 1 SET STATISTICS 100; -ANALYZE concur_exprs_tab; -SELECT starelid::regclass, count(*) FROM pg_statistic WHERE starelid IN ( - 'concur_exprs_index_expr'::regclass, - 'concur_exprs_index_pred'::regclass, - 'concur_exprs_index_pred_2'::regclass) - GROUP BY starelid ORDER BY starelid::regclass::text; -SELECT pg_get_indexdef('concur_exprs_index_expr'::regclass); -SELECT pg_get_indexdef('concur_exprs_index_pred'::regclass); -SELECT pg_get_indexdef('concur_exprs_index_pred_2'::regclass); -REINDEX TABLE CONCURRENTLY concur_exprs_tab; -SELECT pg_get_indexdef('concur_exprs_index_expr'::regclass); -SELECT pg_get_indexdef('concur_exprs_index_pred'::regclass); -SELECT pg_get_indexdef('concur_exprs_index_pred_2'::regclass); --- ALTER TABLE recreates the indexes, which should keep their collations. -ALTER TABLE concur_exprs_tab ALTER c2 TYPE TEXT; -SELECT pg_get_indexdef('concur_exprs_index_expr'::regclass); -SELECT pg_get_indexdef('concur_exprs_index_pred'::regclass); -SELECT pg_get_indexdef('concur_exprs_index_pred_2'::regclass); --- Statistics should remain intact. -SELECT starelid::regclass, count(*) FROM pg_statistic WHERE starelid IN ( - 'concur_exprs_index_expr'::regclass, - 'concur_exprs_index_pred'::regclass, - 'concur_exprs_index_pred_2'::regclass) - GROUP BY starelid ORDER BY starelid::regclass::text; --- attstattarget should remain intact -SELECT attrelid::regclass, attnum, attstattarget - FROM pg_attribute WHERE attrelid IN ( - 'concur_exprs_index_expr'::regclass, - 'concur_exprs_index_pred'::regclass, - 'concur_exprs_index_pred_2'::regclass) - ORDER BY attrelid::regclass::text, attnum; -DROP TABLE concur_exprs_tab; - --- Temporary tables and on-commit actions, where CONCURRENTLY is ignored. --- ON COMMIT PRESERVE ROWS, the default. -CREATE TEMP TABLE concur_temp_tab_1 (c1 int, c2 text) - ON COMMIT PRESERVE ROWS; -INSERT INTO concur_temp_tab_1 VALUES (1, 'foo'), (2, 'bar'); -CREATE INDEX concur_temp_ind_1 ON concur_temp_tab_1(c2); -REINDEX TABLE CONCURRENTLY concur_temp_tab_1; -REINDEX INDEX CONCURRENTLY concur_temp_ind_1; --- Still fails in transaction blocks -BEGIN; -REINDEX INDEX CONCURRENTLY concur_temp_ind_1; -COMMIT; --- ON COMMIT DELETE ROWS -CREATE TEMP TABLE concur_temp_tab_2 (c1 int, c2 text) - ON COMMIT DELETE ROWS; -CREATE INDEX concur_temp_ind_2 ON concur_temp_tab_2(c2); -REINDEX TABLE CONCURRENTLY concur_temp_tab_2; -REINDEX INDEX CONCURRENTLY concur_temp_ind_2; --- ON COMMIT DROP -BEGIN; -CREATE TEMP TABLE concur_temp_tab_3 (c1 int, c2 text) - ON COMMIT PRESERVE ROWS; -INSERT INTO concur_temp_tab_3 VALUES (1, 'foo'), (2, 'bar'); -CREATE INDEX concur_temp_ind_3 ON concur_temp_tab_3(c2); --- Fails when running in a transaction -REINDEX INDEX CONCURRENTLY concur_temp_ind_3; -COMMIT; --- REINDEX SCHEMA processes all temporary relations -CREATE TABLE reindex_temp_before AS -SELECT oid, relname, relfilenode, relkind, reltoastrelid - FROM pg_class - WHERE relname IN ('concur_temp_ind_1', 'concur_temp_ind_2'); -SELECT pg_my_temp_schema()::regnamespace as temp_schema_name \gset -REINDEX SCHEMA CONCURRENTLY :temp_schema_name; -SELECT b.relname, - b.relkind, - CASE WHEN a.relfilenode = b.relfilenode THEN 'relfilenode is unchanged' - ELSE 'relfilenode has changed' END - FROM reindex_temp_before b JOIN pg_class a ON b.oid = a.oid - ORDER BY 1; -DROP TABLE concur_temp_tab_1, concur_temp_tab_2, reindex_temp_before; - --- --- REINDEX SCHEMA --- -REINDEX SCHEMA schema_to_reindex; -- failure, schema does not exist -CREATE SCHEMA schema_to_reindex; -SET search_path = 'schema_to_reindex'; -CREATE TABLE table1(col1 SERIAL PRIMARY KEY); -INSERT INTO table1 SELECT generate_series(1,400); -CREATE TABLE table2(col1 SERIAL PRIMARY KEY, col2 TEXT NOT NULL); -INSERT INTO table2 SELECT generate_series(1,400), 'abc'; -CREATE INDEX ON table2(col2); -CREATE MATERIALIZED VIEW matview AS SELECT col1 FROM table2; -CREATE INDEX ON matview(col1); -CREATE VIEW view AS SELECT col2 FROM table2; -CREATE TABLE reindex_before AS -SELECT oid, relname, relfilenode, relkind, reltoastrelid - FROM pg_class - where relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'schema_to_reindex'); -INSERT INTO reindex_before -SELECT oid, 'pg_toast_TABLE', relfilenode, relkind, reltoastrelid -FROM pg_class WHERE oid IN - (SELECT reltoastrelid FROM reindex_before WHERE reltoastrelid > 0); -INSERT INTO reindex_before -SELECT oid, 'pg_toast_TABLE_index', relfilenode, relkind, reltoastrelid -FROM pg_class where oid in - (select indexrelid from pg_index where indrelid in - (select reltoastrelid from reindex_before where reltoastrelid > 0)); -REINDEX SCHEMA schema_to_reindex; -CREATE TABLE reindex_after AS SELECT oid, relname, relfilenode, relkind - FROM pg_class - where relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'schema_to_reindex'); -SELECT b.relname, - b.relkind, - CASE WHEN a.relfilenode = b.relfilenode THEN 'relfilenode is unchanged' - ELSE 'relfilenode has changed' END - FROM reindex_before b JOIN pg_class a ON b.oid = a.oid - ORDER BY 1; -REINDEX SCHEMA schema_to_reindex; -BEGIN; -REINDEX SCHEMA schema_to_reindex; -- failure, cannot run in a transaction -END; - --- concurrently -REINDEX SCHEMA CONCURRENTLY schema_to_reindex; - --- Failure for unauthorized user -CREATE ROLE regress_reindexuser NOLOGIN; -SET SESSION ROLE regress_reindexuser; -REINDEX SCHEMA schema_to_reindex; --- Permission failures with toast tables and indexes (pg_authid here) -RESET ROLE; -GRANT USAGE ON SCHEMA pg_toast TO regress_reindexuser; -SET SESSION ROLE regress_reindexuser; -REINDEX TABLE pg_toast.pg_toast_1260; -REINDEX INDEX pg_toast.pg_toast_1260_index; - --- Clean up -RESET ROLE; -REVOKE USAGE ON SCHEMA pg_toast FROM regress_reindexuser; -DROP ROLE regress_reindexuser; -DROP SCHEMA schema_to_reindex CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_operator.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_operator.sql deleted file mode 100644 index f53e24db3c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_operator.sql +++ /dev/null @@ -1,225 +0,0 @@ --- --- CREATE_OPERATOR --- - -CREATE OPERATOR ## ( - leftarg = path, - rightarg = path, - function = path_inter, - commutator = ## -); - -CREATE OPERATOR @#@ ( - rightarg = int8, -- prefix - procedure = factorial -); - -CREATE OPERATOR #%# ( - leftarg = int8, -- fail, postfix is no longer supported - procedure = factorial -); - --- Test operator created above -SELECT @#@ 24; - --- Test comments -COMMENT ON OPERATOR ###### (NONE, int4) IS 'bad prefix'; -COMMENT ON OPERATOR ###### (int4, NONE) IS 'bad postfix'; -COMMENT ON OPERATOR ###### (int4, int8) IS 'bad infix'; - --- Check that DROP on a nonexistent op behaves sanely, too -DROP OPERATOR ###### (NONE, int4); -DROP OPERATOR ###### (int4, NONE); -DROP OPERATOR ###### (int4, int8); - --- => is disallowed as an operator name now -CREATE OPERATOR => ( - rightarg = int8, - procedure = factorial -); - --- lexing of <=, >=, <>, != has a number of edge cases --- (=> is tested elsewhere) - --- this is legal because ! is not allowed in sql ops -CREATE OPERATOR !=- ( - rightarg = int8, - procedure = factorial -); -SELECT !=- 10; --- postfix operators don't work anymore -SELECT 10 !=-; --- make sure lexer returns != as <> even in edge cases -SELECT 2 !=/**/ 1, 2 !=/**/ 2; -SELECT 2 !=-- comment to be removed by psql - 1; -DO $$ -- use DO to protect -- from psql - declare r boolean; - begin - execute $e$ select 2 !=-- comment - 1 $e$ into r; - raise info 'r = %', r; - end; -$$; - --- check that <= etc. followed by more operator characters are returned --- as the correct token with correct precedence -SELECT true<>-1 BETWEEN 1 AND 1; -- BETWEEN has prec. above <> but below Op -SELECT false<>/**/1 BETWEEN 1 AND 1; -SELECT false<=-1 BETWEEN 1 AND 1; -SELECT false>=-1 BETWEEN 1 AND 1; -SELECT 2<=/**/3, 3>=/**/2, 2<>/**/3; -SELECT 3<=/**/2, 2>=/**/3, 2<>/**/2; - --- Should fail. CREATE OPERATOR requires USAGE on SCHEMA -BEGIN TRANSACTION; -CREATE ROLE regress_rol_op1; -CREATE SCHEMA schema_op1; -GRANT USAGE ON SCHEMA schema_op1 TO PUBLIC; -REVOKE USAGE ON SCHEMA schema_op1 FROM regress_rol_op1; -SET ROLE regress_rol_op1; -CREATE OPERATOR schema_op1.#*# ( - rightarg = int8, - procedure = factorial -); -ROLLBACK; - - --- Should fail. SETOF type functions not allowed as argument (testing leftarg) -BEGIN TRANSACTION; -CREATE OPERATOR #*# ( - leftarg = SETOF int8, - procedure = factorial -); -ROLLBACK; - - --- Should fail. SETOF type functions not allowed as argument (testing rightarg) -BEGIN TRANSACTION; -CREATE OPERATOR #*# ( - rightarg = SETOF int8, - procedure = factorial -); -ROLLBACK; - - --- Should work. Sample text-book case -BEGIN TRANSACTION; -CREATE OR REPLACE FUNCTION fn_op2(boolean, boolean) -RETURNS boolean AS $$ - SELECT NULL::BOOLEAN; -$$ LANGUAGE sql IMMUTABLE; -CREATE OPERATOR === ( - LEFTARG = boolean, - RIGHTARG = boolean, - PROCEDURE = fn_op2, - COMMUTATOR = ===, - NEGATOR = !==, - RESTRICT = contsel, - JOIN = contjoinsel, - SORT1, SORT2, LTCMP, GTCMP, HASHES, MERGES -); -ROLLBACK; - --- Should fail. Invalid attribute -CREATE OPERATOR #@%# ( - rightarg = int8, - procedure = factorial, - invalid_att = int8 -); - --- Should fail. At least rightarg should be mandatorily specified -CREATE OPERATOR #@%# ( - procedure = factorial -); - --- Should fail. Procedure should be mandatorily specified -CREATE OPERATOR #@%# ( - rightarg = int8 -); - --- Should fail. CREATE OPERATOR requires USAGE on TYPE -BEGIN TRANSACTION; -CREATE ROLE regress_rol_op3; -CREATE TYPE type_op3 AS ENUM ('new', 'open', 'closed'); -CREATE FUNCTION fn_op3(type_op3, int8) -RETURNS int8 AS $$ - SELECT NULL::int8; -$$ LANGUAGE sql IMMUTABLE; -REVOKE USAGE ON TYPE type_op3 FROM regress_rol_op3; -REVOKE USAGE ON TYPE type_op3 FROM PUBLIC; -- Need to do this so that regress_rol_op3 is not allowed USAGE via PUBLIC -SET ROLE regress_rol_op3; -CREATE OPERATOR #*# ( - leftarg = type_op3, - rightarg = int8, - procedure = fn_op3 -); -ROLLBACK; - --- Should fail. CREATE OPERATOR requires USAGE on TYPE (need to check separately for rightarg) -BEGIN TRANSACTION; -CREATE ROLE regress_rol_op4; -CREATE TYPE type_op4 AS ENUM ('new', 'open', 'closed'); -CREATE FUNCTION fn_op4(int8, type_op4) -RETURNS int8 AS $$ - SELECT NULL::int8; -$$ LANGUAGE sql IMMUTABLE; -REVOKE USAGE ON TYPE type_op4 FROM regress_rol_op4; -REVOKE USAGE ON TYPE type_op4 FROM PUBLIC; -- Need to do this so that regress_rol_op3 is not allowed USAGE via PUBLIC -SET ROLE regress_rol_op4; -CREATE OPERATOR #*# ( - leftarg = int8, - rightarg = type_op4, - procedure = fn_op4 -); -ROLLBACK; - --- Should fail. CREATE OPERATOR requires EXECUTE on function -BEGIN TRANSACTION; -CREATE ROLE regress_rol_op5; -CREATE TYPE type_op5 AS ENUM ('new', 'open', 'closed'); -CREATE FUNCTION fn_op5(int8, int8) -RETURNS int8 AS $$ - SELECT NULL::int8; -$$ LANGUAGE sql IMMUTABLE; -REVOKE EXECUTE ON FUNCTION fn_op5(int8, int8) FROM regress_rol_op5; -REVOKE EXECUTE ON FUNCTION fn_op5(int8, int8) FROM PUBLIC;-- Need to do this so that regress_rol_op3 is not allowed EXECUTE via PUBLIC -SET ROLE regress_rol_op5; -CREATE OPERATOR #*# ( - leftarg = int8, - rightarg = int8, - procedure = fn_op5 -); -ROLLBACK; - --- Should fail. CREATE OPERATOR requires USAGE on return TYPE -BEGIN TRANSACTION; -CREATE ROLE regress_rol_op6; -CREATE TYPE type_op6 AS ENUM ('new', 'open', 'closed'); -CREATE FUNCTION fn_op6(int8, int8) -RETURNS type_op6 AS $$ - SELECT NULL::type_op6; -$$ LANGUAGE sql IMMUTABLE; -REVOKE USAGE ON TYPE type_op6 FROM regress_rol_op6; -REVOKE USAGE ON TYPE type_op6 FROM PUBLIC; -- Need to do this so that regress_rol_op3 is not allowed USAGE via PUBLIC -SET ROLE regress_rol_op6; -CREATE OPERATOR #*# ( - leftarg = int8, - rightarg = int8, - procedure = fn_op6 -); -ROLLBACK; - --- invalid: non-lowercase quoted identifiers -CREATE OPERATOR === -( - "Leftarg" = box, - "Rightarg" = box, - "Procedure" = area_equal_function, - "Commutator" = ===, - "Negator" = !==, - "Restrict" = area_restriction_function, - "Join" = area_join_function, - "Hashes", - "Merges" -); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_procedure.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_procedure.sql deleted file mode 100644 index 75cc0fcf2a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_procedure.sql +++ /dev/null @@ -1,253 +0,0 @@ -CALL nonexistent(); -- error -CALL random(); -- error - -CREATE FUNCTION cp_testfunc1(a int) RETURNS int LANGUAGE SQL AS $$ SELECT a $$; - -CREATE TABLE cp_test (a int, b text); - -CREATE PROCEDURE ptest1(x text) -LANGUAGE SQL -AS $$ -INSERT INTO cp_test VALUES (1, x); -$$; - -\df ptest1 -SELECT pg_get_functiondef('ptest1'::regproc); - --- show only normal functions -\dfn public.*test*1 - --- show only procedures -\dfp public.*test*1 - -SELECT ptest1('x'); -- error -CALL ptest1('a'); -- ok -CALL ptest1('xy' || 'zzy'); -- ok, constant-folded arg -CALL ptest1(substring(random()::numeric(20,15)::text, 1, 1)); -- ok, volatile arg - -SELECT * FROM cp_test ORDER BY b COLLATE "C"; - - --- SQL-standard body -CREATE PROCEDURE ptest1s(x text) -LANGUAGE SQL -BEGIN ATOMIC - INSERT INTO cp_test VALUES (1, x); -END; - -\df ptest1s -SELECT pg_get_functiondef('ptest1s'::regproc); - -CALL ptest1s('b'); - -SELECT * FROM cp_test ORDER BY b COLLATE "C"; - --- utitlity functions currently not supported here -CREATE PROCEDURE ptestx() -LANGUAGE SQL -BEGIN ATOMIC - CREATE TABLE x (a int); -END; - - -CREATE PROCEDURE ptest2() -LANGUAGE SQL -AS $$ -SELECT 5; -$$; - -CALL ptest2(); - - --- nested CALL -TRUNCATE cp_test; - -CREATE PROCEDURE ptest3(y text) -LANGUAGE SQL -AS $$ -CALL ptest1(y); -CALL ptest1($1); -$$; - -CALL ptest3('b'); - -SELECT * FROM cp_test; - - --- output arguments - -CREATE PROCEDURE ptest4a(INOUT a int, INOUT b int) -LANGUAGE SQL -AS $$ -SELECT 1, 2; -$$; - -CALL ptest4a(NULL, NULL); - -CREATE PROCEDURE ptest4b(INOUT b int, INOUT a int) -LANGUAGE SQL -AS $$ -CALL ptest4a(a, b); -- error, not supported -$$; - -DROP PROCEDURE ptest4a; - - --- named and default parameters - -CREATE OR REPLACE PROCEDURE ptest5(a int, b text, c int default 100) -LANGUAGE SQL -AS $$ -INSERT INTO cp_test VALUES(a, b); -INSERT INTO cp_test VALUES(c, b); -$$; - -TRUNCATE cp_test; - -CALL ptest5(10, 'Hello', 20); -CALL ptest5(10, 'Hello'); -CALL ptest5(10, b => 'Hello'); -CALL ptest5(b => 'Hello', a => 10); - -SELECT * FROM cp_test; - - --- polymorphic types - -CREATE PROCEDURE ptest6(a int, b anyelement) -LANGUAGE SQL -AS $$ -SELECT NULL::int; -$$; - -CALL ptest6(1, 2); - - --- collation assignment - -CREATE PROCEDURE ptest7(a text, b text) -LANGUAGE SQL -AS $$ -SELECT a = b; -$$; - -CALL ptest7(least('a', 'b'), 'a'); - - --- empty body -CREATE PROCEDURE ptest8(x text) -BEGIN ATOMIC -END; - -\df ptest8 -SELECT pg_get_functiondef('ptest8'::regproc); -CALL ptest8(''); - - --- OUT parameters - -CREATE PROCEDURE ptest9(OUT a int) -LANGUAGE SQL -AS $$ -INSERT INTO cp_test VALUES (1, 'a'); -SELECT 1; -$$; - --- standard way to do a call: -CALL ptest9(NULL); --- you can write an expression, but it's not evaluated -CALL ptest9(1/0); -- no error --- ... and it had better match the type of the parameter -CALL ptest9(1./0.); -- error - --- check named-parameter matching -CREATE PROCEDURE ptest10(OUT a int, IN b int, IN c int) -LANGUAGE SQL AS $$ SELECT b - c $$; - -CALL ptest10(null, 7, 4); -CALL ptest10(a => null, b => 8, c => 2); -CALL ptest10(null, 7, c => 2); -CALL ptest10(null, c => 4, b => 11); -CALL ptest10(b => 8, c => 2, a => 0); - -CREATE PROCEDURE ptest11(a OUT int, VARIADIC b int[]) LANGUAGE SQL - AS $$ SELECT b[1] + b[2] $$; - -CALL ptest11(null, 11, 12, 13); - --- check resolution of ambiguous DROP commands - -CREATE PROCEDURE ptest10(IN a int, IN b int, IN c int) -LANGUAGE SQL AS $$ SELECT a + b - c $$; - -\df ptest10 - -drop procedure ptest10; -- fail -drop procedure ptest10(int, int, int); -- fail -begin; -drop procedure ptest10(out int, int, int); -\df ptest10 -drop procedure ptest10(int, int, int); -- now this would work -rollback; -begin; -drop procedure ptest10(in int, int, int); -\df ptest10 -drop procedure ptest10(int, int, int); -- now this would work -rollback; - --- various error cases - -CALL version(); -- error: not a procedure -CALL sum(1); -- error: not a procedure - -CREATE PROCEDURE ptestx() LANGUAGE SQL WINDOW AS $$ INSERT INTO cp_test VALUES (1, 'a') $$; -CREATE PROCEDURE ptestx() LANGUAGE SQL STRICT AS $$ INSERT INTO cp_test VALUES (1, 'a') $$; -CREATE PROCEDURE ptestx(a VARIADIC int[], b OUT int) LANGUAGE SQL - AS $$ SELECT a[1] $$; -CREATE PROCEDURE ptestx(a int DEFAULT 42, b OUT int) LANGUAGE SQL - AS $$ SELECT a $$; - -ALTER PROCEDURE ptest1(text) STRICT; -ALTER FUNCTION ptest1(text) VOLATILE; -- error: not a function -ALTER PROCEDURE cp_testfunc1(int) VOLATILE; -- error: not a procedure -ALTER PROCEDURE nonexistent() VOLATILE; - -DROP FUNCTION ptest1(text); -- error: not a function -DROP PROCEDURE cp_testfunc1(int); -- error: not a procedure -DROP PROCEDURE nonexistent(); - - --- privileges - -CREATE USER regress_cp_user1; -GRANT INSERT ON cp_test TO regress_cp_user1; -REVOKE EXECUTE ON PROCEDURE ptest1(text) FROM PUBLIC; -SET ROLE regress_cp_user1; -CALL ptest1('a'); -- error -RESET ROLE; -GRANT EXECUTE ON PROCEDURE ptest1(text) TO regress_cp_user1; -SET ROLE regress_cp_user1; -CALL ptest1('a'); -- ok -RESET ROLE; - - --- ROUTINE syntax - -ALTER ROUTINE cp_testfunc1(int) RENAME TO cp_testfunc1a; -ALTER ROUTINE cp_testfunc1a RENAME TO cp_testfunc1; - -ALTER ROUTINE ptest1(text) RENAME TO ptest1a; -ALTER ROUTINE ptest1a RENAME TO ptest1; - -DROP ROUTINE cp_testfunc1(int); - - --- cleanup - -DROP PROCEDURE ptest1; -DROP PROCEDURE ptest1s; -DROP PROCEDURE ptest2; - -DROP TABLE cp_test; - -DROP USER regress_cp_user1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_table.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_table.sql deleted file mode 100644 index 5175f404f7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_table.sql +++ /dev/null @@ -1,735 +0,0 @@ --- --- CREATE_TABLE --- - --- Error cases -CREATE TABLE unknowntab ( - u unknown -- fail -); - -CREATE TYPE unknown_comptype AS ( - u unknown -- fail -); - --- invalid: non-lowercase quoted reloptions identifiers -CREATE TABLE tas_case WITH ("Fillfactor" = 10) AS SELECT 1 a; - -CREATE UNLOGGED TABLE unlogged1 (a int primary key); -- OK -CREATE TEMPORARY TABLE unlogged2 (a int primary key); -- OK -SELECT relname, relkind, relpersistence FROM pg_class WHERE relname ~ '^unlogged\d' ORDER BY relname; -REINDEX INDEX unlogged1_pkey; -REINDEX INDEX unlogged2_pkey; -SELECT relname, relkind, relpersistence FROM pg_class WHERE relname ~ '^unlogged\d' ORDER BY relname; -DROP TABLE unlogged2; -INSERT INTO unlogged1 VALUES (42); -CREATE UNLOGGED TABLE public.unlogged2 (a int primary key); -- also OK -CREATE UNLOGGED TABLE pg_temp.unlogged3 (a int primary key); -- not OK -CREATE TABLE pg_temp.implicitly_temp (a int primary key); -- OK -CREATE TEMP TABLE explicitly_temp (a int primary key); -- also OK -CREATE TEMP TABLE pg_temp.doubly_temp (a int primary key); -- also OK -CREATE TEMP TABLE public.temp_to_perm (a int primary key); -- not OK -DROP TABLE unlogged1, public.unlogged2; - -CREATE TABLE as_select1 AS SELECT * FROM pg_class WHERE relkind = 'r'; -CREATE TABLE as_select1 AS SELECT * FROM pg_class WHERE relkind = 'r'; -CREATE TABLE IF NOT EXISTS as_select1 AS SELECT * FROM pg_class WHERE relkind = 'r'; -DROP TABLE as_select1; - -PREPARE select1 AS SELECT 1 as a; -CREATE TABLE as_select1 AS EXECUTE select1; -CREATE TABLE as_select1 AS EXECUTE select1; -SELECT * FROM as_select1; -CREATE TABLE IF NOT EXISTS as_select1 AS EXECUTE select1; -DROP TABLE as_select1; -DEALLOCATE select1; - --- create an extra wide table to test for issues related to that --- (temporarily hide query, to avoid the long CREATE TABLE stmt) -\set ECHO none -SELECT 'CREATE TABLE extra_wide_table(firstc text, '|| array_to_string(array_agg('c'||i||' bool'),',')||', lastc text);' -FROM generate_series(1, 1100) g(i) -\gexec -\set ECHO all -INSERT INTO extra_wide_table(firstc, lastc) VALUES('first col', 'last col'); -SELECT firstc, lastc FROM extra_wide_table; - --- check that tables with oids cannot be created anymore -CREATE TABLE withoid() WITH OIDS; -CREATE TABLE withoid() WITH (oids); -CREATE TABLE withoid() WITH (oids = true); - --- but explicitly not adding oids is still supported -CREATE TEMP TABLE withoutoid() WITHOUT OIDS; DROP TABLE withoutoid; -CREATE TEMP TABLE withoutoid() WITH (oids = false); DROP TABLE withoutoid; - --- check restriction with default expressions --- invalid use of column reference in default expressions -CREATE TABLE default_expr_column (id int DEFAULT (id)); -CREATE TABLE default_expr_column (id int DEFAULT (bar.id)); -CREATE TABLE default_expr_agg_column (id int DEFAULT (avg(id))); --- invalid column definition -CREATE TABLE default_expr_non_column (a int DEFAULT (avg(non_existent))); --- invalid use of aggregate -CREATE TABLE default_expr_agg (a int DEFAULT (avg(1))); --- invalid use of subquery -CREATE TABLE default_expr_agg (a int DEFAULT (select 1)); --- invalid use of set-returning function -CREATE TABLE default_expr_agg (a int DEFAULT (generate_series(1,3))); - --- Verify that subtransaction rollback restores rd_createSubid. -BEGIN; -CREATE TABLE remember_create_subid (c int); -SAVEPOINT q; DROP TABLE remember_create_subid; ROLLBACK TO q; -COMMIT; -DROP TABLE remember_create_subid; - --- Verify that subtransaction rollback restores rd_firstRelfilenodeSubid. -CREATE TABLE remember_node_subid (c int); -BEGIN; -ALTER TABLE remember_node_subid ALTER c TYPE bigint; -SAVEPOINT q; DROP TABLE remember_node_subid; ROLLBACK TO q; -COMMIT; -DROP TABLE remember_node_subid; - --- --- Partitioned tables --- - --- cannot combine INHERITS and PARTITION BY (although grammar allows) -CREATE TABLE partitioned ( - a int -) INHERITS (some_table) PARTITION BY LIST (a); - --- cannot use more than 1 column as partition key for list partitioned table -CREATE TABLE partitioned ( - a1 int, - a2 int -) PARTITION BY LIST (a1, a2); -- fail - --- unsupported constraint type for partitioned tables -CREATE TABLE partitioned ( - a int, - EXCLUDE USING gist (a WITH &&) -) PARTITION BY RANGE (a); - --- prevent using prohibited expressions in the key -CREATE FUNCTION retset (a int) RETURNS SETOF int AS $$ SELECT 1; $$ LANGUAGE SQL IMMUTABLE; -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE (retset(a)); -DROP FUNCTION retset(int); - -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE ((avg(a))); - -CREATE TABLE partitioned ( - a int, - b int -) PARTITION BY RANGE ((avg(a) OVER (PARTITION BY b))); - -CREATE TABLE partitioned ( - a int -) PARTITION BY LIST ((a LIKE (SELECT 1))); - -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE ((42)); - -CREATE FUNCTION const_func () RETURNS int AS $$ SELECT 1; $$ LANGUAGE SQL IMMUTABLE; -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE (const_func()); -DROP FUNCTION const_func(); - --- only accept valid partitioning strategy -CREATE TABLE partitioned ( - a int -) PARTITION BY MAGIC (a); - --- specified column must be present in the table -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE (b); - --- cannot use system columns in partition key -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE (xmin); - --- cannot use pseudotypes -CREATE TABLE partitioned ( - a int, - b int -) PARTITION BY RANGE (((a, b))); -CREATE TABLE partitioned ( - a int, - b int -) PARTITION BY RANGE (a, ('unknown')); - --- functions in key must be immutable -CREATE FUNCTION immut_func (a int) RETURNS int AS $$ SELECT a + random()::int; $$ LANGUAGE SQL; -CREATE TABLE partitioned ( - a int -) PARTITION BY RANGE (immut_func(a)); -DROP FUNCTION immut_func(int); - --- prevent using columns of unsupported types in key (type must have a btree operator class) -CREATE TABLE partitioned ( - a point -) PARTITION BY LIST (a); -CREATE TABLE partitioned ( - a point -) PARTITION BY LIST (a point_ops); -CREATE TABLE partitioned ( - a point -) PARTITION BY RANGE (a); -CREATE TABLE partitioned ( - a point -) PARTITION BY RANGE (a point_ops); - --- cannot add NO INHERIT constraints to partitioned tables -CREATE TABLE partitioned ( - a int, - CONSTRAINT check_a CHECK (a > 0) NO INHERIT -) PARTITION BY RANGE (a); - --- some checks after successful creation of a partitioned table -CREATE FUNCTION plusone(a int) RETURNS INT AS $$ SELECT a+1; $$ LANGUAGE SQL; - -CREATE TABLE partitioned ( - a int, - b int, - c text, - d text -) PARTITION BY RANGE (a oid_ops, plusone(b), c collate "default", d collate "C"); - --- check relkind -SELECT relkind FROM pg_class WHERE relname = 'partitioned'; - --- prevent a function referenced in partition key from being dropped -DROP FUNCTION plusone(int); - --- partitioned table cannot participate in regular inheritance -CREATE TABLE partitioned2 ( - a int, - b text -) PARTITION BY RANGE ((a+1), substr(b, 1, 5)); -CREATE TABLE fail () INHERITS (partitioned2); - --- Partition key in describe output -\d partitioned -\d+ partitioned2 - -INSERT INTO partitioned2 VALUES (1, 'hello'); -CREATE TABLE part2_1 PARTITION OF partitioned2 FOR VALUES FROM (-1, 'aaaaa') TO (100, 'ccccc'); -\d+ part2_1 - -DROP TABLE partitioned, partitioned2; - --- check reference to partitioned table's rowtype in partition descriptor -create table partitioned (a int, b int) - partition by list ((row(a, b)::partitioned)); -create table partitioned1 - partition of partitioned for values in ('(1,2)'::partitioned); -create table partitioned2 - partition of partitioned for values in ('(2,4)'::partitioned); -explain (costs off) -select * from partitioned where row(a,b)::partitioned = '(1,2)'::partitioned; -drop table partitioned; - --- whole-row Var in partition key works too -create table partitioned (a int, b int) - partition by list ((partitioned)); -create table partitioned1 - partition of partitioned for values in ('(1,2)'); -create table partitioned2 - partition of partitioned for values in ('(2,4)'); -explain (costs off) -select * from partitioned where partitioned = '(1,2)'::partitioned; -\d+ partitioned1 -drop table partitioned; - --- check that dependencies of partition columns are handled correctly -create domain intdom1 as int; - -create table partitioned ( - a intdom1, - b text -) partition by range (a); - -alter table partitioned drop column a; -- fail - -drop domain intdom1; -- fail, requires cascade - -drop domain intdom1 cascade; - -table partitioned; -- gone - --- likewise for columns used in partition expressions -create domain intdom1 as int; - -create table partitioned ( - a intdom1, - b text -) partition by range (plusone(a)); - -alter table partitioned drop column a; -- fail - -drop domain intdom1; -- fail, requires cascade - -drop domain intdom1 cascade; - -table partitioned; -- gone - - --- --- Partitions --- - --- check partition bound syntax - -CREATE TABLE list_parted ( - a int -) PARTITION BY LIST (a); -CREATE TABLE part_p1 PARTITION OF list_parted FOR VALUES IN ('1'); -CREATE TABLE part_p2 PARTITION OF list_parted FOR VALUES IN (2); -CREATE TABLE part_p3 PARTITION OF list_parted FOR VALUES IN ((2+1)); -CREATE TABLE part_null PARTITION OF list_parted FOR VALUES IN (null); -\d+ list_parted - --- forbidden expressions for partition bound with list partitioned table -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (somename); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (somename.somename); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (a); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (sum(a)); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (sum(somename)); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (sum(1)); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN ((select 1)); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN (generate_series(4, 6)); -CREATE TABLE part_bogus_expr_fail PARTITION OF list_parted FOR VALUES IN ((1+1) collate "POSIX"); - --- syntax does not allow empty list of values for list partitions -CREATE TABLE fail_part PARTITION OF list_parted FOR VALUES IN (); --- trying to specify range for list partitioned table -CREATE TABLE fail_part PARTITION OF list_parted FOR VALUES FROM (1) TO (2); --- trying to specify modulus and remainder for list partitioned table -CREATE TABLE fail_part PARTITION OF list_parted FOR VALUES WITH (MODULUS 10, REMAINDER 1); - --- check default partition cannot be created more than once -CREATE TABLE part_default PARTITION OF list_parted DEFAULT; -CREATE TABLE fail_default_part PARTITION OF list_parted DEFAULT; - --- specified literal can't be cast to the partition column data type -CREATE TABLE bools ( - a bool -) PARTITION BY LIST (a); -CREATE TABLE bools_true PARTITION OF bools FOR VALUES IN (1); -DROP TABLE bools; - --- specified literal can be cast, and the cast might not be immutable -CREATE TABLE moneyp ( - a money -) PARTITION BY LIST (a); -CREATE TABLE moneyp_10 PARTITION OF moneyp FOR VALUES IN (10); -CREATE TABLE moneyp_11 PARTITION OF moneyp FOR VALUES IN ('11'); -CREATE TABLE moneyp_12 PARTITION OF moneyp FOR VALUES IN (to_char(12, '99')::int); -DROP TABLE moneyp; - --- cast is immutable -CREATE TABLE bigintp ( - a bigint -) PARTITION BY LIST (a); -CREATE TABLE bigintp_10 PARTITION OF bigintp FOR VALUES IN (10); --- fails due to overlap: -CREATE TABLE bigintp_10_2 PARTITION OF bigintp FOR VALUES IN ('10'); -DROP TABLE bigintp; - -CREATE TABLE range_parted ( - a date -) PARTITION BY RANGE (a); - --- forbidden expressions for partition bounds with range partitioned table -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (somename) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (somename.somename) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (a) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (max(a)) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (max(somename)) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (max('2019-02-01'::date)) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM ((select 1)) TO ('2019-01-01'); -CREATE TABLE part_bogus_expr_fail PARTITION OF range_parted - FOR VALUES FROM (generate_series(1, 3)) TO ('2019-01-01'); - --- trying to specify list for range partitioned table -CREATE TABLE fail_part PARTITION OF range_parted FOR VALUES IN ('a'); --- trying to specify modulus and remainder for range partitioned table -CREATE TABLE fail_part PARTITION OF range_parted FOR VALUES WITH (MODULUS 10, REMAINDER 1); --- each of start and end bounds must have same number of values as the --- length of the partition key -CREATE TABLE fail_part PARTITION OF range_parted FOR VALUES FROM ('a', 1) TO ('z'); -CREATE TABLE fail_part PARTITION OF range_parted FOR VALUES FROM ('a') TO ('z', 1); - --- cannot specify null values in range bounds -CREATE TABLE fail_part PARTITION OF range_parted FOR VALUES FROM (null) TO (maxvalue); - --- trying to specify modulus and remainder for range partitioned table -CREATE TABLE fail_part PARTITION OF range_parted FOR VALUES WITH (MODULUS 10, REMAINDER 1); - --- check partition bound syntax for the hash partition -CREATE TABLE hash_parted ( - a int -) PARTITION BY HASH (a); -CREATE TABLE hpart_1 PARTITION OF hash_parted FOR VALUES WITH (MODULUS 10, REMAINDER 0); -CREATE TABLE hpart_2 PARTITION OF hash_parted FOR VALUES WITH (MODULUS 50, REMAINDER 1); -CREATE TABLE hpart_3 PARTITION OF hash_parted FOR VALUES WITH (MODULUS 200, REMAINDER 2); -CREATE TABLE hpart_4 PARTITION OF hash_parted FOR VALUES WITH (MODULUS 10, REMAINDER 3); --- modulus 25 is factor of modulus of 50 but 10 is not a factor of 25. -CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES WITH (MODULUS 25, REMAINDER 3); --- previous modulus 50 is factor of 150 but this modulus is not a factor of next modulus 200. -CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES WITH (MODULUS 150, REMAINDER 3); --- overlapping remainders -CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES WITH (MODULUS 100, REMAINDER 3); --- trying to specify range for the hash partitioned table -CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES FROM ('a', 1) TO ('z'); --- trying to specify list value for the hash partitioned table -CREATE TABLE fail_part PARTITION OF hash_parted FOR VALUES IN (1000); - --- trying to create default partition for the hash partitioned table -CREATE TABLE fail_default_part PARTITION OF hash_parted DEFAULT; - --- check if compatible with the specified parent - --- cannot create as partition of a non-partitioned table -CREATE TABLE unparted ( - a int -); -CREATE TABLE fail_part PARTITION OF unparted FOR VALUES IN ('a'); -CREATE TABLE fail_part PARTITION OF unparted FOR VALUES WITH (MODULUS 2, REMAINDER 1); -DROP TABLE unparted; - --- cannot create a permanent rel as partition of a temp rel -CREATE TEMP TABLE temp_parted ( - a int -) PARTITION BY LIST (a); -CREATE TABLE fail_part PARTITION OF temp_parted FOR VALUES IN ('a'); -DROP TABLE temp_parted; - --- check for partition bound overlap and other invalid specifications - -CREATE TABLE list_parted2 ( - a varchar -) PARTITION BY LIST (a); -CREATE TABLE part_null_z PARTITION OF list_parted2 FOR VALUES IN (null, 'z'); -CREATE TABLE part_ab PARTITION OF list_parted2 FOR VALUES IN ('a', 'b'); -CREATE TABLE list_parted2_def PARTITION OF list_parted2 DEFAULT; - -CREATE TABLE fail_part PARTITION OF list_parted2 FOR VALUES IN (null); -CREATE TABLE fail_part PARTITION OF list_parted2 FOR VALUES IN ('b', 'c'); --- check default partition overlap -INSERT INTO list_parted2 VALUES('X'); -CREATE TABLE fail_part PARTITION OF list_parted2 FOR VALUES IN ('W', 'X', 'Y'); - -CREATE TABLE range_parted2 ( - a int -) PARTITION BY RANGE (a); - --- trying to create range partition with empty range -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (1) TO (0); --- note that the range '[1, 1)' has no elements -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (1) TO (1); - -CREATE TABLE part0 PARTITION OF range_parted2 FOR VALUES FROM (minvalue) TO (1); -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (minvalue) TO (2); -CREATE TABLE part1 PARTITION OF range_parted2 FOR VALUES FROM (1) TO (10); -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (-1) TO (1); -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (9) TO (maxvalue); -CREATE TABLE part2 PARTITION OF range_parted2 FOR VALUES FROM (20) TO (30); -CREATE TABLE part3 PARTITION OF range_parted2 FOR VALUES FROM (30) TO (40); -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (10) TO (30); -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (10) TO (50); - --- Create a default partition for range partitioned table -CREATE TABLE range2_default PARTITION OF range_parted2 DEFAULT; - --- More than one default partition is not allowed, so this should give error -CREATE TABLE fail_default_part PARTITION OF range_parted2 DEFAULT; - --- Check if the range for default partitions overlap -INSERT INTO range_parted2 VALUES (85); -CREATE TABLE fail_part PARTITION OF range_parted2 FOR VALUES FROM (80) TO (90); -CREATE TABLE part4 PARTITION OF range_parted2 FOR VALUES FROM (90) TO (100); - --- now check for multi-column range partition key -CREATE TABLE range_parted3 ( - a int, - b int -) PARTITION BY RANGE (a, (b+1)); - -CREATE TABLE part00 PARTITION OF range_parted3 FOR VALUES FROM (0, minvalue) TO (0, maxvalue); -CREATE TABLE fail_part PARTITION OF range_parted3 FOR VALUES FROM (0, minvalue) TO (0, 1); - -CREATE TABLE part10 PARTITION OF range_parted3 FOR VALUES FROM (1, minvalue) TO (1, 1); -CREATE TABLE part11 PARTITION OF range_parted3 FOR VALUES FROM (1, 1) TO (1, 10); -CREATE TABLE part12 PARTITION OF range_parted3 FOR VALUES FROM (1, 10) TO (1, maxvalue); -CREATE TABLE fail_part PARTITION OF range_parted3 FOR VALUES FROM (1, 10) TO (1, 20); -CREATE TABLE range3_default PARTITION OF range_parted3 DEFAULT; - --- cannot create a partition that says column b is allowed to range --- from -infinity to +infinity, while there exist partitions that have --- more specific ranges -CREATE TABLE fail_part PARTITION OF range_parted3 FOR VALUES FROM (1, minvalue) TO (1, maxvalue); - --- check for partition bound overlap and other invalid specifications for the hash partition -CREATE TABLE hash_parted2 ( - a varchar -) PARTITION BY HASH (a); -CREATE TABLE h2part_1 PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 4, REMAINDER 2); -CREATE TABLE h2part_2 PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 8, REMAINDER 0); -CREATE TABLE h2part_3 PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 8, REMAINDER 4); -CREATE TABLE h2part_4 PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 8, REMAINDER 5); --- overlap with part_4 -CREATE TABLE fail_part PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 2, REMAINDER 1); --- modulus must be greater than zero -CREATE TABLE fail_part PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 0, REMAINDER 1); --- remainder must be greater than or equal to zero and less than modulus -CREATE TABLE fail_part PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 8, REMAINDER 8); - --- check schema propagation from parent - -CREATE TABLE parted ( - a text, - b int NOT NULL DEFAULT 0, - CONSTRAINT check_a CHECK (length(a) > 0) -) PARTITION BY LIST (a); - -CREATE TABLE part_a PARTITION OF parted FOR VALUES IN ('a'); - --- only inherited attributes (never local ones) -SELECT attname, attislocal, attinhcount FROM pg_attribute - WHERE attrelid = 'part_a'::regclass and attnum > 0 - ORDER BY attnum; - --- able to specify column default, column constraint, and table constraint - --- first check the "column specified more than once" error -CREATE TABLE part_b PARTITION OF parted ( - b NOT NULL, - b DEFAULT 1, - b CHECK (b >= 0), - CONSTRAINT check_a CHECK (length(a) > 0) -) FOR VALUES IN ('b'); - -CREATE TABLE part_b PARTITION OF parted ( - b NOT NULL DEFAULT 1, - CONSTRAINT check_a CHECK (length(a) > 0), - CONSTRAINT check_b CHECK (b >= 0) -) FOR VALUES IN ('b'); --- conislocal should be false for any merged constraints, true otherwise -SELECT conislocal, coninhcount FROM pg_constraint WHERE conrelid = 'part_b'::regclass ORDER BY conislocal, coninhcount; - --- Once check_b is added to the parent, it should be made non-local for part_b -ALTER TABLE parted ADD CONSTRAINT check_b CHECK (b >= 0); -SELECT conislocal, coninhcount FROM pg_constraint WHERE conrelid = 'part_b'::regclass; - --- Neither check_a nor check_b are droppable from part_b -ALTER TABLE part_b DROP CONSTRAINT check_a; -ALTER TABLE part_b DROP CONSTRAINT check_b; - --- And dropping it from parted should leave no trace of them on part_b, unlike --- traditional inheritance where they will be left behind, because they would --- be local constraints. -ALTER TABLE parted DROP CONSTRAINT check_a, DROP CONSTRAINT check_b; -SELECT conislocal, coninhcount FROM pg_constraint WHERE conrelid = 'part_b'::regclass; - --- specify PARTITION BY for a partition -CREATE TABLE fail_part_col_not_found PARTITION OF parted FOR VALUES IN ('c') PARTITION BY RANGE (c); -CREATE TABLE part_c PARTITION OF parted (b WITH OPTIONS NOT NULL DEFAULT 0) FOR VALUES IN ('c') PARTITION BY RANGE ((b)); - --- create a level-2 partition -CREATE TABLE part_c_1_10 PARTITION OF part_c FOR VALUES FROM (1) TO (10); - --- check that NOT NULL and default value are inherited correctly -create table parted_notnull_inh_test (a int default 1, b int not null default 0) partition by list (a); -create table parted_notnull_inh_test1 partition of parted_notnull_inh_test (a not null, b default 1) for values in (1); -insert into parted_notnull_inh_test (b) values (null); --- note that while b's default is overridden, a's default is preserved -\d parted_notnull_inh_test1 -drop table parted_notnull_inh_test; - --- check that collations are assigned in partition bound expressions -create table parted_boolean_col (a bool, b text) partition by list(a); -create table parted_boolean_less partition of parted_boolean_col - for values in ('foo' < 'bar'); -create table parted_boolean_greater partition of parted_boolean_col - for values in ('foo' > 'bar'); -drop table parted_boolean_col; - --- check for a conflicting COLLATE clause -create table parted_collate_must_match (a text collate "C", b text collate "C") - partition by range (a); --- on the partition key -create table parted_collate_must_match1 partition of parted_collate_must_match - (a collate "POSIX") for values from ('a') to ('m'); --- on another column -create table parted_collate_must_match2 partition of parted_collate_must_match - (b collate "POSIX") for values from ('m') to ('z'); -drop table parted_collate_must_match; - --- check that non-matching collations for partition bound --- expressions are coerced to the right collation - -create table test_part_coll_posix (a text) partition by range (a collate "POSIX"); --- ok, collation is implicitly coerced -create table test_part_coll partition of test_part_coll_posix for values from ('a' collate "C") to ('g'); --- ok -create table test_part_coll2 partition of test_part_coll_posix for values from ('g') to ('m'); --- ok, collation is implicitly coerced -create table test_part_coll_cast partition of test_part_coll_posix for values from (name 'm' collate "C") to ('s'); --- ok; partition collation silently overrides the default collation of type 'name' -create table test_part_coll_cast2 partition of test_part_coll_posix for values from (name 's') to ('z'); - -drop table test_part_coll_posix; - --- Partition bound in describe output -\d+ part_b - --- Both partition bound and partition key in describe output -\d+ part_c - --- a level-2 partition's constraint will include the parent's expressions -\d+ part_c_1_10 - --- Show partition count in the parent's describe output --- Tempted to include \d+ output listing partitions with bound info but --- output could vary depending on the order in which partition oids are --- returned. -\d parted -\d hash_parted - --- check that we get the expected partition constraints -CREATE TABLE range_parted4 (a int, b int, c int) PARTITION BY RANGE (abs(a), abs(b), c); -CREATE TABLE unbounded_range_part PARTITION OF range_parted4 FOR VALUES FROM (MINVALUE, MINVALUE, MINVALUE) TO (MAXVALUE, MAXVALUE, MAXVALUE); -\d+ unbounded_range_part -DROP TABLE unbounded_range_part; -CREATE TABLE range_parted4_1 PARTITION OF range_parted4 FOR VALUES FROM (MINVALUE, MINVALUE, MINVALUE) TO (1, MAXVALUE, MAXVALUE); -\d+ range_parted4_1 -CREATE TABLE range_parted4_2 PARTITION OF range_parted4 FOR VALUES FROM (3, 4, 5) TO (6, 7, MAXVALUE); -\d+ range_parted4_2 -CREATE TABLE range_parted4_3 PARTITION OF range_parted4 FOR VALUES FROM (6, 8, MINVALUE) TO (9, MAXVALUE, MAXVALUE); -\d+ range_parted4_3 -DROP TABLE range_parted4; - --- user-defined operator class in partition key -CREATE FUNCTION my_int4_sort(int4,int4) RETURNS int LANGUAGE sql - AS $$ SELECT CASE WHEN $1 = $2 THEN 0 WHEN $1 > $2 THEN 1 ELSE -1 END; $$; -CREATE OPERATOR CLASS test_int4_ops FOR TYPE int4 USING btree AS - OPERATOR 1 < (int4,int4), OPERATOR 2 <= (int4,int4), - OPERATOR 3 = (int4,int4), OPERATOR 4 >= (int4,int4), - OPERATOR 5 > (int4,int4), FUNCTION 1 my_int4_sort(int4,int4); -CREATE TABLE partkey_t (a int4) PARTITION BY RANGE (a test_int4_ops); -CREATE TABLE partkey_t_1 PARTITION OF partkey_t FOR VALUES FROM (0) TO (1000); -INSERT INTO partkey_t VALUES (100); -INSERT INTO partkey_t VALUES (200); - --- cleanup -DROP TABLE parted, list_parted, range_parted, list_parted2, range_parted2, range_parted3; -DROP TABLE partkey_t, hash_parted, hash_parted2; -DROP OPERATOR CLASS test_int4_ops USING btree; -DROP FUNCTION my_int4_sort(int4,int4); - --- comments on partitioned tables columns -CREATE TABLE parted_col_comment (a int, b text) PARTITION BY LIST (a); -COMMENT ON TABLE parted_col_comment IS 'Am partitioned table'; -COMMENT ON COLUMN parted_col_comment.a IS 'Partition key'; -SELECT obj_description('parted_col_comment'::regclass); -\d+ parted_col_comment -DROP TABLE parted_col_comment; - --- list partitioning on array type column -CREATE TABLE arrlp (a int[]) PARTITION BY LIST (a); -CREATE TABLE arrlp12 PARTITION OF arrlp FOR VALUES IN ('{1}', '{2}'); -\d+ arrlp12 -DROP TABLE arrlp; - --- partition on boolean column -create table boolspart (a bool) partition by list (a); -create table boolspart_t partition of boolspart for values in (true); -create table boolspart_f partition of boolspart for values in (false); -\d+ boolspart -drop table boolspart; - --- partitions mixing temporary and permanent relations -create table perm_parted (a int) partition by list (a); -create temporary table temp_parted (a int) partition by list (a); -create table perm_part partition of temp_parted default; -- error -create temp table temp_part partition of perm_parted default; -- error -create temp table temp_part partition of temp_parted default; -- ok -drop table perm_parted cascade; -drop table temp_parted cascade; - --- check that adding partitions to a table while it is being used is prevented -create table tab_part_create (a int) partition by list (a); -create or replace function func_part_create() returns trigger - language plpgsql as $$ - begin - execute 'create table tab_part_create_1 partition of tab_part_create for values in (1)'; - return null; - end $$; -create trigger trig_part_create before insert on tab_part_create - for each statement execute procedure func_part_create(); -insert into tab_part_create values (1); -drop table tab_part_create; -drop function func_part_create(); - --- test using a volatile expression as partition bound -create table volatile_partbound_test (partkey timestamp) partition by range (partkey); -create table volatile_partbound_test1 partition of volatile_partbound_test for values from (minvalue) to (current_timestamp); -create table volatile_partbound_test2 partition of volatile_partbound_test for values from (current_timestamp) to (maxvalue); --- this should go into the partition volatile_partbound_test2 -insert into volatile_partbound_test values (current_timestamp); -select tableoid::regclass from volatile_partbound_test; -drop table volatile_partbound_test; - --- test the case where a check constraint on default partition allows --- to avoid scanning it when adding a new partition -create table defcheck (a int, b int) partition by list (b); -create table defcheck_def (a int, c int, b int); -alter table defcheck_def drop c; -alter table defcheck attach partition defcheck_def default; -alter table defcheck_def add check (b <= 0 and b is not null); -create table defcheck_1 partition of defcheck for values in (1, null); - --- test that complex default partition constraints are enforced correctly -insert into defcheck_def values (0, 0); -create table defcheck_0 partition of defcheck for values in (0); -drop table defcheck; - --- tests of column drop with partition tables and indexes using --- predicates and expressions. -create table part_column_drop ( - useless_1 int, - id int, - useless_2 int, - d int, - b int, - useless_3 int -) partition by range (id); -alter table part_column_drop drop column useless_1; -alter table part_column_drop drop column useless_2; -alter table part_column_drop drop column useless_3; -create index part_column_drop_b_pred on part_column_drop(b) where b = 1; -create index part_column_drop_b_expr on part_column_drop((b = 1)); -create index part_column_drop_d_pred on part_column_drop(d) where d = 2; -create index part_column_drop_d_expr on part_column_drop((d = 2)); -create table part_column_drop_1_10 partition of - part_column_drop for values from (1) to (10); -\d part_column_drop -\d part_column_drop_1_10 -drop table part_column_drop; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_table_like.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_table_like.sql deleted file mode 100644 index 4929d373a2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_table_like.sql +++ /dev/null @@ -1,217 +0,0 @@ -/* Test inheritance of structure (LIKE) */ -CREATE TABLE inhx (xx text DEFAULT 'text'); - -/* - * Test double inheritance - * - * Ensure that defaults are NOT included unless - * INCLUDING DEFAULTS is specified - */ -CREATE TABLE ctla (aa TEXT); -CREATE TABLE ctlb (bb TEXT) INHERITS (ctla); - -CREATE TABLE foo (LIKE nonexistent); - -CREATE TABLE inhe (ee text, LIKE inhx) inherits (ctlb); -INSERT INTO inhe VALUES ('ee-col1', 'ee-col2', DEFAULT, 'ee-col4'); -SELECT * FROM inhe; /* Columns aa, bb, xx value NULL, ee */ -SELECT * FROM inhx; /* Empty set since LIKE inherits structure only */ -SELECT * FROM ctlb; /* Has ee entry */ -SELECT * FROM ctla; /* Has ee entry */ - -CREATE TABLE inhf (LIKE inhx, LIKE inhx); /* Throw error */ - -CREATE TABLE inhf (LIKE inhx INCLUDING DEFAULTS INCLUDING CONSTRAINTS); -INSERT INTO inhf DEFAULT VALUES; -SELECT * FROM inhf; /* Single entry with value 'text' */ - -ALTER TABLE inhx add constraint foo CHECK (xx = 'text'); -ALTER TABLE inhx ADD PRIMARY KEY (xx); -CREATE TABLE inhg (LIKE inhx); /* Doesn't copy constraint */ -INSERT INTO inhg VALUES ('foo'); -DROP TABLE inhg; -CREATE TABLE inhg (x text, LIKE inhx INCLUDING CONSTRAINTS, y text); /* Copies constraints */ -INSERT INTO inhg VALUES ('x', 'text', 'y'); /* Succeeds */ -INSERT INTO inhg VALUES ('x', 'text', 'y'); /* Succeeds -- Unique constraints not copied */ -INSERT INTO inhg VALUES ('x', 'foo', 'y'); /* fails due to constraint */ -SELECT * FROM inhg; /* Two records with three columns in order x=x, xx=text, y=y */ -DROP TABLE inhg; - -CREATE TABLE test_like_id_1 (a bigint GENERATED ALWAYS AS IDENTITY, b text); -\d test_like_id_1 -INSERT INTO test_like_id_1 (b) VALUES ('b1'); -SELECT * FROM test_like_id_1; -CREATE TABLE test_like_id_2 (LIKE test_like_id_1); -\d test_like_id_2 -INSERT INTO test_like_id_2 (b) VALUES ('b2'); -SELECT * FROM test_like_id_2; -- identity was not copied -CREATE TABLE test_like_id_3 (LIKE test_like_id_1 INCLUDING IDENTITY); -\d test_like_id_3 -INSERT INTO test_like_id_3 (b) VALUES ('b3'); -SELECT * FROM test_like_id_3; -- identity was copied and applied -DROP TABLE test_like_id_1, test_like_id_2, test_like_id_3; - -CREATE TABLE test_like_gen_1 (a int, b int GENERATED ALWAYS AS (a * 2) STORED); -\d test_like_gen_1 -INSERT INTO test_like_gen_1 (a) VALUES (1); -SELECT * FROM test_like_gen_1; -CREATE TABLE test_like_gen_2 (LIKE test_like_gen_1); -\d test_like_gen_2 -INSERT INTO test_like_gen_2 (a) VALUES (1); -SELECT * FROM test_like_gen_2; -CREATE TABLE test_like_gen_3 (LIKE test_like_gen_1 INCLUDING GENERATED); -\d test_like_gen_3 -INSERT INTO test_like_gen_3 (a) VALUES (1); -SELECT * FROM test_like_gen_3; -DROP TABLE test_like_gen_1, test_like_gen_2, test_like_gen_3; - --- also test generated column with a "forward" reference (bug #16342) -CREATE TABLE test_like_4 (b int DEFAULT 42, - c int GENERATED ALWAYS AS (a * 2) STORED, - a int CHECK (a > 0)); -\d test_like_4 -CREATE TABLE test_like_4a (LIKE test_like_4); -CREATE TABLE test_like_4b (LIKE test_like_4 INCLUDING DEFAULTS); -CREATE TABLE test_like_4c (LIKE test_like_4 INCLUDING GENERATED); -CREATE TABLE test_like_4d (LIKE test_like_4 INCLUDING DEFAULTS INCLUDING GENERATED); -\d test_like_4a -INSERT INTO test_like_4a (a) VALUES(11); -SELECT a, b, c FROM test_like_4a; -\d test_like_4b -INSERT INTO test_like_4b (a) VALUES(11); -SELECT a, b, c FROM test_like_4b; -\d test_like_4c -INSERT INTO test_like_4c (a) VALUES(11); -SELECT a, b, c FROM test_like_4c; -\d test_like_4d -INSERT INTO test_like_4d (a) VALUES(11); -SELECT a, b, c FROM test_like_4d; - --- Test renumbering of Vars when combining LIKE with inheritance -CREATE TABLE test_like_5 (x point, y point, z point); -CREATE TABLE test_like_5x (p int CHECK (p > 0), - q int GENERATED ALWAYS AS (p * 2) STORED); -CREATE TABLE test_like_5c (LIKE test_like_4 INCLUDING ALL) - INHERITS (test_like_5, test_like_5x); -\d test_like_5c - -DROP TABLE test_like_4, test_like_4a, test_like_4b, test_like_4c, test_like_4d; -DROP TABLE test_like_5, test_like_5x, test_like_5c; - -CREATE TABLE inhg (x text, LIKE inhx INCLUDING INDEXES, y text); /* copies indexes */ -INSERT INTO inhg VALUES (5, 10); -INSERT INTO inhg VALUES (20, 10); -- should fail -DROP TABLE inhg; -/* Multiple primary keys creation should fail */ -CREATE TABLE inhg (x text, LIKE inhx INCLUDING INDEXES, PRIMARY KEY(x)); /* fails */ -CREATE TABLE inhz (xx text DEFAULT 'text', yy int UNIQUE); -CREATE UNIQUE INDEX inhz_xx_idx on inhz (xx) WHERE xx <> 'test'; -/* Ok to create multiple unique indexes */ -CREATE TABLE inhg (x text UNIQUE, LIKE inhz INCLUDING INDEXES); -INSERT INTO inhg (xx, yy, x) VALUES ('test', 5, 10); -INSERT INTO inhg (xx, yy, x) VALUES ('test', 10, 15); -INSERT INTO inhg (xx, yy, x) VALUES ('foo', 10, 15); -- should fail -DROP TABLE inhg; -DROP TABLE inhz; - -/* Use primary key imported by LIKE for self-referential FK constraint */ -CREATE TABLE inhz (x text REFERENCES inhz, LIKE inhx INCLUDING INDEXES); -\d inhz -DROP TABLE inhz; - --- including storage and comments -CREATE TABLE ctlt1 (a text CHECK (length(a) > 2) PRIMARY KEY, b text); -CREATE INDEX ctlt1_b_key ON ctlt1 (b); -CREATE INDEX ctlt1_fnidx ON ctlt1 ((a || b)); -CREATE STATISTICS ctlt1_a_b_stat ON a,b FROM ctlt1; -CREATE STATISTICS ctlt1_expr_stat ON (a || b) FROM ctlt1; -COMMENT ON STATISTICS ctlt1_a_b_stat IS 'ab stats'; -COMMENT ON STATISTICS ctlt1_expr_stat IS 'ab expr stats'; -COMMENT ON COLUMN ctlt1.a IS 'A'; -COMMENT ON COLUMN ctlt1.b IS 'B'; -COMMENT ON CONSTRAINT ctlt1_a_check ON ctlt1 IS 't1_a_check'; -COMMENT ON INDEX ctlt1_pkey IS 'index pkey'; -COMMENT ON INDEX ctlt1_b_key IS 'index b_key'; -ALTER TABLE ctlt1 ALTER COLUMN a SET STORAGE MAIN; - -CREATE TABLE ctlt2 (c text); -ALTER TABLE ctlt2 ALTER COLUMN c SET STORAGE EXTERNAL; -COMMENT ON COLUMN ctlt2.c IS 'C'; - -CREATE TABLE ctlt3 (a text CHECK (length(a) < 5), c text CHECK (length(c) < 7)); -ALTER TABLE ctlt3 ALTER COLUMN c SET STORAGE EXTERNAL; -ALTER TABLE ctlt3 ALTER COLUMN a SET STORAGE MAIN; -CREATE INDEX ctlt3_fnidx ON ctlt3 ((a || c)); -COMMENT ON COLUMN ctlt3.a IS 'A3'; -COMMENT ON COLUMN ctlt3.c IS 'C'; -COMMENT ON CONSTRAINT ctlt3_a_check ON ctlt3 IS 't3_a_check'; - -CREATE TABLE ctlt4 (a text, c text); -ALTER TABLE ctlt4 ALTER COLUMN c SET STORAGE EXTERNAL; - -CREATE TABLE ctlt12_storage (LIKE ctlt1 INCLUDING STORAGE, LIKE ctlt2 INCLUDING STORAGE); -\d+ ctlt12_storage -CREATE TABLE ctlt12_comments (LIKE ctlt1 INCLUDING COMMENTS, LIKE ctlt2 INCLUDING COMMENTS); -\d+ ctlt12_comments -CREATE TABLE ctlt1_inh (LIKE ctlt1 INCLUDING CONSTRAINTS INCLUDING COMMENTS) INHERITS (ctlt1); -\d+ ctlt1_inh -SELECT description FROM pg_description, pg_constraint c WHERE classoid = 'pg_constraint'::regclass AND objoid = c.oid AND c.conrelid = 'ctlt1_inh'::regclass; -CREATE TABLE ctlt13_inh () INHERITS (ctlt1, ctlt3); -\d+ ctlt13_inh -CREATE TABLE ctlt13_like (LIKE ctlt3 INCLUDING CONSTRAINTS INCLUDING INDEXES INCLUDING COMMENTS INCLUDING STORAGE) INHERITS (ctlt1); -\d+ ctlt13_like -SELECT description FROM pg_description, pg_constraint c WHERE classoid = 'pg_constraint'::regclass AND objoid = c.oid AND c.conrelid = 'ctlt13_like'::regclass; - -CREATE TABLE ctlt_all (LIKE ctlt1 INCLUDING ALL); -\d+ ctlt_all -SELECT c.relname, objsubid, description FROM pg_description, pg_index i, pg_class c WHERE classoid = 'pg_class'::regclass AND objoid = i.indexrelid AND c.oid = i.indexrelid AND i.indrelid = 'ctlt_all'::regclass ORDER BY c.relname, objsubid; -SELECT s.stxname, objsubid, description FROM pg_description, pg_statistic_ext s WHERE classoid = 'pg_statistic_ext'::regclass AND objoid = s.oid AND s.stxrelid = 'ctlt_all'::regclass ORDER BY s.stxname, objsubid; - -CREATE TABLE inh_error1 () INHERITS (ctlt1, ctlt4); -CREATE TABLE inh_error2 (LIKE ctlt4 INCLUDING STORAGE) INHERITS (ctlt1); - --- Check that LIKE isn't confused by a system catalog of the same name -CREATE TABLE pg_attrdef (LIKE ctlt1 INCLUDING ALL); -\d+ public.pg_attrdef -DROP TABLE public.pg_attrdef; - --- Check that LIKE isn't confused when new table masks the old, either -BEGIN; -CREATE SCHEMA ctl_schema; -SET LOCAL search_path = ctl_schema, public; -CREATE TABLE ctlt1 (LIKE ctlt1 INCLUDING ALL); -\d+ ctlt1 -ROLLBACK; - -DROP TABLE ctlt1, ctlt2, ctlt3, ctlt4, ctlt12_storage, ctlt12_comments, ctlt1_inh, ctlt13_inh, ctlt13_like, ctlt_all, ctla, ctlb CASCADE; - --- LIKE must respect NO INHERIT property of constraints -CREATE TABLE noinh_con_copy (a int CHECK (a > 0) NO INHERIT); -CREATE TABLE noinh_con_copy1 (LIKE noinh_con_copy INCLUDING CONSTRAINTS); -\d noinh_con_copy1 - --- fail, as partitioned tables don't allow NO INHERIT constraints -CREATE TABLE noinh_con_copy1_parted (LIKE noinh_con_copy INCLUDING ALL) - PARTITION BY LIST (a); - -DROP TABLE noinh_con_copy, noinh_con_copy1; - - -/* LIKE with other relation kinds */ - -CREATE TABLE ctlt4 (a int, b text); - -CREATE SEQUENCE ctlseq1; -CREATE TABLE ctlt10 (LIKE ctlseq1); -- fail - -CREATE VIEW ctlv1 AS SELECT * FROM ctlt4; -CREATE TABLE ctlt11 (LIKE ctlv1); -CREATE TABLE ctlt11a (LIKE ctlv1 INCLUDING ALL); - -CREATE TYPE ctlty1 AS (a int, b text); -CREATE TABLE ctlt12 (LIKE ctlty1); - -DROP SEQUENCE ctlseq1; -DROP TYPE ctlty1; -DROP VIEW ctlv1; -DROP TABLE IF EXISTS ctlt4, ctlt10, ctlt11, ctlt11a, ctlt12; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_view.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_view.sql deleted file mode 100644 index 50acfe96e6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fcreate_view.sql +++ /dev/null @@ -1,742 +0,0 @@ --- --- CREATE_VIEW --- Virtual class definitions --- (this also tests the query rewrite system) --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - -CREATE FUNCTION interpt_pp(path, path) - RETURNS point - AS :'regresslib' - LANGUAGE C STRICT; - -CREATE TABLE real_city ( - pop int4, - cname text, - outline path -); - -\set filename :abs_srcdir '/data/real_city.data' -COPY real_city FROM :'filename'; -ANALYZE real_city; - -SELECT * - INTO TABLE ramp - FROM ONLY road - WHERE name ~ '.*Ramp'; - -CREATE VIEW street AS - SELECT r.name, r.thepath, c.cname AS cname - FROM ONLY road r, real_city c - WHERE c.outline ?# r.thepath; - -CREATE VIEW iexit AS - SELECT ih.name, ih.thepath, - interpt_pp(ih.thepath, r.thepath) AS exit - FROM ihighway ih, ramp r - WHERE ih.thepath ?# r.thepath; - -CREATE VIEW toyemp AS - SELECT name, age, location, 12*salary AS annualsal - FROM emp; - --- Test comments -COMMENT ON VIEW noview IS 'no view'; -COMMENT ON VIEW toyemp IS 'is a view'; -COMMENT ON VIEW toyemp IS NULL; - --- These views are left around mainly to exercise special cases in pg_dump. - -CREATE TABLE view_base_table (key int PRIMARY KEY, data varchar(20)); - -CREATE VIEW key_dependent_view AS - SELECT * FROM view_base_table GROUP BY key; - -ALTER TABLE view_base_table DROP CONSTRAINT view_base_table_pkey; -- fails - -CREATE VIEW key_dependent_view_no_cols AS - SELECT FROM view_base_table GROUP BY key HAVING length(data) > 0; - --- --- CREATE OR REPLACE VIEW --- - -CREATE TABLE viewtest_tbl (a int, b int, c numeric(10,1), d text COLLATE "C"); - -COPY viewtest_tbl FROM stdin; -5 10 1.1 xy -10 15 2.2 xyz -15 20 3.3 xyzz -20 25 4.4 xyzzy -\. - -CREATE OR REPLACE VIEW viewtest AS - SELECT * FROM viewtest_tbl; - -CREATE OR REPLACE VIEW viewtest AS - SELECT * FROM viewtest_tbl WHERE a > 10; - -SELECT * FROM viewtest; - -CREATE OR REPLACE VIEW viewtest AS - SELECT a, b, c, d FROM viewtest_tbl WHERE a > 5 ORDER BY b DESC; - -SELECT * FROM viewtest; - --- should fail -CREATE OR REPLACE VIEW viewtest AS - SELECT a FROM viewtest_tbl WHERE a <> 20; - --- should fail -CREATE OR REPLACE VIEW viewtest AS - SELECT 1, * FROM viewtest_tbl; - --- should fail -CREATE OR REPLACE VIEW viewtest AS - SELECT a, b::numeric, c, d FROM viewtest_tbl; - --- should fail -CREATE OR REPLACE VIEW viewtest AS - SELECT a, b, c::numeric(10,2), d FROM viewtest_tbl; - --- should fail -CREATE OR REPLACE VIEW viewtest AS - SELECT a, b, c, d COLLATE "POSIX" FROM viewtest_tbl; - --- should work -CREATE OR REPLACE VIEW viewtest AS - SELECT a, b, c, d, 0 AS e FROM viewtest_tbl; - -DROP VIEW viewtest; -DROP TABLE viewtest_tbl; - --- tests for temporary views - -CREATE SCHEMA temp_view_test - CREATE TABLE base_table (a int, id int) - CREATE TABLE base_table2 (a int, id int); - -SET search_path TO temp_view_test, public; - -CREATE TEMPORARY TABLE temp_table (a int, id int); - --- should be created in temp_view_test schema -CREATE VIEW v1 AS SELECT * FROM base_table; --- should be created in temp object schema -CREATE VIEW v1_temp AS SELECT * FROM temp_table; --- should be created in temp object schema -CREATE TEMP VIEW v2_temp AS SELECT * FROM base_table; --- should be created in temp_views schema -CREATE VIEW temp_view_test.v2 AS SELECT * FROM base_table; --- should fail -CREATE VIEW temp_view_test.v3_temp AS SELECT * FROM temp_table; --- should fail -CREATE SCHEMA test_view_schema - CREATE TEMP VIEW testview AS SELECT 1; - --- joins: if any of the join relations are temporary, the view --- should also be temporary - --- should be non-temp -CREATE VIEW v3 AS - SELECT t1.a AS t1_a, t2.a AS t2_a - FROM base_table t1, base_table2 t2 - WHERE t1.id = t2.id; --- should be temp (one join rel is temp) -CREATE VIEW v4_temp AS - SELECT t1.a AS t1_a, t2.a AS t2_a - FROM base_table t1, temp_table t2 - WHERE t1.id = t2.id; --- should be temp -CREATE VIEW v5_temp AS - SELECT t1.a AS t1_a, t2.a AS t2_a, t3.a AS t3_a - FROM base_table t1, base_table2 t2, temp_table t3 - WHERE t1.id = t2.id and t2.id = t3.id; - --- subqueries -CREATE VIEW v4 AS SELECT * FROM base_table WHERE id IN (SELECT id FROM base_table2); -CREATE VIEW v5 AS SELECT t1.id, t2.a FROM base_table t1, (SELECT * FROM base_table2) t2; -CREATE VIEW v6 AS SELECT * FROM base_table WHERE EXISTS (SELECT 1 FROM base_table2); -CREATE VIEW v7 AS SELECT * FROM base_table WHERE NOT EXISTS (SELECT 1 FROM base_table2); -CREATE VIEW v8 AS SELECT * FROM base_table WHERE EXISTS (SELECT 1); - -CREATE VIEW v6_temp AS SELECT * FROM base_table WHERE id IN (SELECT id FROM temp_table); -CREATE VIEW v7_temp AS SELECT t1.id, t2.a FROM base_table t1, (SELECT * FROM temp_table) t2; -CREATE VIEW v8_temp AS SELECT * FROM base_table WHERE EXISTS (SELECT 1 FROM temp_table); -CREATE VIEW v9_temp AS SELECT * FROM base_table WHERE NOT EXISTS (SELECT 1 FROM temp_table); - --- a view should also be temporary if it references a temporary view -CREATE VIEW v10_temp AS SELECT * FROM v7_temp; -CREATE VIEW v11_temp AS SELECT t1.id, t2.a FROM base_table t1, v10_temp t2; -CREATE VIEW v12_temp AS SELECT true FROM v11_temp; - --- a view should also be temporary if it references a temporary sequence -CREATE SEQUENCE seq1; -CREATE TEMPORARY SEQUENCE seq1_temp; -CREATE VIEW v9 AS SELECT seq1.is_called FROM seq1; -CREATE VIEW v13_temp AS SELECT seq1_temp.is_called FROM seq1_temp; - -SELECT relname FROM pg_class - WHERE relname LIKE 'v_' - AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'temp_view_test') - ORDER BY relname; -SELECT relname FROM pg_class - WHERE relname LIKE 'v%' - AND relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname LIKE 'pg_temp%') - ORDER BY relname; - -CREATE SCHEMA testviewschm2; -SET search_path TO testviewschm2, public; - -CREATE TABLE t1 (num int, name text); -CREATE TABLE t2 (num2 int, value text); -CREATE TEMP TABLE tt (num2 int, value text); - -CREATE VIEW nontemp1 AS SELECT * FROM t1 CROSS JOIN t2; -CREATE VIEW temporal1 AS SELECT * FROM t1 CROSS JOIN tt; -CREATE VIEW nontemp2 AS SELECT * FROM t1 INNER JOIN t2 ON t1.num = t2.num2; -CREATE VIEW temporal2 AS SELECT * FROM t1 INNER JOIN tt ON t1.num = tt.num2; -CREATE VIEW nontemp3 AS SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num2; -CREATE VIEW temporal3 AS SELECT * FROM t1 LEFT JOIN tt ON t1.num = tt.num2; -CREATE VIEW nontemp4 AS SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num2 AND t2.value = 'xxx'; -CREATE VIEW temporal4 AS SELECT * FROM t1 LEFT JOIN tt ON t1.num = tt.num2 AND tt.value = 'xxx'; - -SELECT relname FROM pg_class - WHERE relname LIKE 'nontemp%' - AND relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'testviewschm2') - ORDER BY relname; -SELECT relname FROM pg_class - WHERE relname LIKE 'temporal%' - AND relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname LIKE 'pg_temp%') - ORDER BY relname; - -CREATE TABLE tbl1 ( a int, b int); -CREATE TABLE tbl2 (c int, d int); -CREATE TABLE tbl3 (e int, f int); -CREATE TABLE tbl4 (g int, h int); -CREATE TEMP TABLE tmptbl (i int, j int); - ---Should be in testviewschm2 -CREATE VIEW pubview AS SELECT * FROM tbl1 WHERE tbl1.a -BETWEEN (SELECT d FROM tbl2 WHERE c = 1) AND (SELECT e FROM tbl3 WHERE f = 2) -AND EXISTS (SELECT g FROM tbl4 LEFT JOIN tbl3 ON tbl4.h = tbl3.f); - -SELECT count(*) FROM pg_class where relname = 'pubview' -AND relnamespace IN (SELECT OID FROM pg_namespace WHERE nspname = 'testviewschm2'); - ---Should be in temp object schema -CREATE VIEW mytempview AS SELECT * FROM tbl1 WHERE tbl1.a -BETWEEN (SELECT d FROM tbl2 WHERE c = 1) AND (SELECT e FROM tbl3 WHERE f = 2) -AND EXISTS (SELECT g FROM tbl4 LEFT JOIN tbl3 ON tbl4.h = tbl3.f) -AND NOT EXISTS (SELECT g FROM tbl4 LEFT JOIN tmptbl ON tbl4.h = tmptbl.j); - -SELECT count(*) FROM pg_class where relname LIKE 'mytempview' -And relnamespace IN (SELECT OID FROM pg_namespace WHERE nspname LIKE 'pg_temp%'); - --- --- CREATE VIEW and WITH(...) clause --- -CREATE VIEW mysecview1 - AS SELECT * FROM tbl1 WHERE a = 0; -CREATE VIEW mysecview2 WITH (security_barrier=true) - AS SELECT * FROM tbl1 WHERE a > 0; -CREATE VIEW mysecview3 WITH (security_barrier=false) - AS SELECT * FROM tbl1 WHERE a < 0; -CREATE VIEW mysecview4 WITH (security_barrier) - AS SELECT * FROM tbl1 WHERE a <> 0; -CREATE VIEW mysecview5 WITH (security_barrier=100) -- Error - AS SELECT * FROM tbl1 WHERE a > 100; -CREATE VIEW mysecview6 WITH (invalid_option) -- Error - AS SELECT * FROM tbl1 WHERE a < 100; -CREATE VIEW mysecview7 WITH (security_invoker=true) - AS SELECT * FROM tbl1 WHERE a = 100; -CREATE VIEW mysecview8 WITH (security_invoker=false, security_barrier=true) - AS SELECT * FROM tbl1 WHERE a > 100; -CREATE VIEW mysecview9 WITH (security_invoker) - AS SELECT * FROM tbl1 WHERE a < 100; -CREATE VIEW mysecview10 WITH (security_invoker=100) -- Error - AS SELECT * FROM tbl1 WHERE a <> 100; -SELECT relname, relkind, reloptions FROM pg_class - WHERE oid in ('mysecview1'::regclass, 'mysecview2'::regclass, - 'mysecview3'::regclass, 'mysecview4'::regclass, - 'mysecview7'::regclass, 'mysecview8'::regclass, - 'mysecview9'::regclass) - ORDER BY relname; - -CREATE OR REPLACE VIEW mysecview1 - AS SELECT * FROM tbl1 WHERE a = 256; -CREATE OR REPLACE VIEW mysecview2 - AS SELECT * FROM tbl1 WHERE a > 256; -CREATE OR REPLACE VIEW mysecview3 WITH (security_barrier=true) - AS SELECT * FROM tbl1 WHERE a < 256; -CREATE OR REPLACE VIEW mysecview4 WITH (security_barrier=false) - AS SELECT * FROM tbl1 WHERE a <> 256; -CREATE OR REPLACE VIEW mysecview7 - AS SELECT * FROM tbl1 WHERE a > 256; -CREATE OR REPLACE VIEW mysecview8 WITH (security_invoker=true) - AS SELECT * FROM tbl1 WHERE a < 256; -CREATE OR REPLACE VIEW mysecview9 WITH (security_invoker=false, security_barrier=true) - AS SELECT * FROM tbl1 WHERE a <> 256; -SELECT relname, relkind, reloptions FROM pg_class - WHERE oid in ('mysecview1'::regclass, 'mysecview2'::regclass, - 'mysecview3'::regclass, 'mysecview4'::regclass, - 'mysecview7'::regclass, 'mysecview8'::regclass, - 'mysecview9'::regclass) - ORDER BY relname; - --- Check that unknown literals are converted to "text" in CREATE VIEW, --- so that we don't end up with unknown-type columns. - -CREATE VIEW unspecified_types AS - SELECT 42 as i, 42.5 as num, 'foo' as u, 'foo'::unknown as u2, null as n; -\d+ unspecified_types -SELECT * FROM unspecified_types; - --- This test checks that proper typmods are assigned in a multi-row VALUES - -CREATE VIEW tt1 AS - SELECT * FROM ( - VALUES - ('abc'::varchar(3), '0123456789', 42, 'abcd'::varchar(4)), - ('0123456789', 'abc'::varchar(3), 42.12, 'abc'::varchar(4)) - ) vv(a,b,c,d); -\d+ tt1 -SELECT * FROM tt1; -SELECT a::varchar(3) FROM tt1; -DROP VIEW tt1; - --- Test view decompilation in the face of relation renaming conflicts - -CREATE TABLE tt1 (f1 int, f2 int, f3 text); -CREATE TABLE tx1 (x1 int, x2 int, x3 text); -CREATE TABLE temp_view_test.tt1 (y1 int, f2 int, f3 text); - -CREATE VIEW aliased_view_1 AS - select * from tt1 - where exists (select 1 from tx1 where tt1.f1 = tx1.x1); -CREATE VIEW aliased_view_2 AS - select * from tt1 a1 - where exists (select 1 from tx1 where a1.f1 = tx1.x1); -CREATE VIEW aliased_view_3 AS - select * from tt1 - where exists (select 1 from tx1 a2 where tt1.f1 = a2.x1); -CREATE VIEW aliased_view_4 AS - select * from temp_view_test.tt1 - where exists (select 1 from tt1 where temp_view_test.tt1.y1 = tt1.f1); - -\d+ aliased_view_1 -\d+ aliased_view_2 -\d+ aliased_view_3 -\d+ aliased_view_4 - -ALTER TABLE tx1 RENAME TO a1; - -\d+ aliased_view_1 -\d+ aliased_view_2 -\d+ aliased_view_3 -\d+ aliased_view_4 - -ALTER TABLE tt1 RENAME TO a2; - -\d+ aliased_view_1 -\d+ aliased_view_2 -\d+ aliased_view_3 -\d+ aliased_view_4 - -ALTER TABLE a1 RENAME TO tt1; - -\d+ aliased_view_1 -\d+ aliased_view_2 -\d+ aliased_view_3 -\d+ aliased_view_4 - -ALTER TABLE a2 RENAME TO tx1; -ALTER TABLE tx1 SET SCHEMA temp_view_test; - -\d+ aliased_view_1 -\d+ aliased_view_2 -\d+ aliased_view_3 -\d+ aliased_view_4 - -ALTER TABLE temp_view_test.tt1 RENAME TO tmp1; -ALTER TABLE temp_view_test.tmp1 SET SCHEMA testviewschm2; -ALTER TABLE tmp1 RENAME TO tx1; - -\d+ aliased_view_1 -\d+ aliased_view_2 -\d+ aliased_view_3 -\d+ aliased_view_4 - --- Test aliasing of joins - -create view view_of_joins as -select * from - (select * from (tbl1 cross join tbl2) same) ss, - (tbl3 cross join tbl4) same; - -\d+ view_of_joins - -create table tbl1a (a int, c int); -create view view_of_joins_2a as select * from tbl1 join tbl1a using (a); -create view view_of_joins_2b as select * from tbl1 join tbl1a using (a) as x; -create view view_of_joins_2c as select * from (tbl1 join tbl1a using (a)) as y; -create view view_of_joins_2d as select * from (tbl1 join tbl1a using (a) as x) as y; - -select pg_get_viewdef('view_of_joins_2a', true); -select pg_get_viewdef('view_of_joins_2b', true); -select pg_get_viewdef('view_of_joins_2c', true); -select pg_get_viewdef('view_of_joins_2d', true); - --- Test view decompilation in the face of column addition/deletion/renaming - -create table tt2 (a int, b int, c int); -create table tt3 (ax int8, b int2, c numeric); -create table tt4 (ay int, b int, q int); - -create view v1 as select * from tt2 natural join tt3; -create view v1a as select * from (tt2 natural join tt3) j; -create view v2 as select * from tt2 join tt3 using (b,c) join tt4 using (b); -create view v2a as select * from (tt2 join tt3 using (b,c) join tt4 using (b)) j; -create view v3 as select * from tt2 join tt3 using (b,c) full join tt4 using (b); - -select pg_get_viewdef('v1', true); -select pg_get_viewdef('v1a', true); -select pg_get_viewdef('v2', true); -select pg_get_viewdef('v2a', true); -select pg_get_viewdef('v3', true); - -alter table tt2 add column d int; -alter table tt2 add column e int; - -select pg_get_viewdef('v1', true); -select pg_get_viewdef('v1a', true); -select pg_get_viewdef('v2', true); -select pg_get_viewdef('v2a', true); -select pg_get_viewdef('v3', true); - -alter table tt3 rename c to d; - -select pg_get_viewdef('v1', true); -select pg_get_viewdef('v1a', true); -select pg_get_viewdef('v2', true); -select pg_get_viewdef('v2a', true); -select pg_get_viewdef('v3', true); - -alter table tt3 add column c int; -alter table tt3 add column e int; - -select pg_get_viewdef('v1', true); -select pg_get_viewdef('v1a', true); -select pg_get_viewdef('v2', true); -select pg_get_viewdef('v2a', true); -select pg_get_viewdef('v3', true); - -alter table tt2 drop column d; - -select pg_get_viewdef('v1', true); -select pg_get_viewdef('v1a', true); -select pg_get_viewdef('v2', true); -select pg_get_viewdef('v2a', true); -select pg_get_viewdef('v3', true); - -create table tt5 (a int, b int); -create table tt6 (c int, d int); -create view vv1 as select * from (tt5 cross join tt6) j(aa,bb,cc,dd); -select pg_get_viewdef('vv1', true); -alter table tt5 add column c int; -select pg_get_viewdef('vv1', true); -alter table tt5 add column cc int; -select pg_get_viewdef('vv1', true); -alter table tt5 drop column c; -select pg_get_viewdef('vv1', true); - -create view v4 as select * from v1; -alter view v1 rename column a to x; -select pg_get_viewdef('v1', true); -select pg_get_viewdef('v4', true); - - --- Unnamed FULL JOIN USING is lots of fun too - -create table tt7 (x int, xx int, y int); -alter table tt7 drop column xx; -create table tt8 (x int, z int); - -create view vv2 as -select * from (values(1,2,3,4,5)) v(a,b,c,d,e) -union all -select * from tt7 full join tt8 using (x), tt8 tt8x; - -select pg_get_viewdef('vv2', true); - -create view vv3 as -select * from (values(1,2,3,4,5,6)) v(a,b,c,x,e,f) -union all -select * from - tt7 full join tt8 using (x), - tt7 tt7x full join tt8 tt8x using (x); - -select pg_get_viewdef('vv3', true); - -create view vv4 as -select * from (values(1,2,3,4,5,6,7)) v(a,b,c,x,e,f,g) -union all -select * from - tt7 full join tt8 using (x), - tt7 tt7x full join tt8 tt8x using (x) full join tt8 tt8y using (x); - -select pg_get_viewdef('vv4', true); - -alter table tt7 add column zz int; -alter table tt7 add column z int; -alter table tt7 drop column zz; -alter table tt8 add column z2 int; - -select pg_get_viewdef('vv2', true); -select pg_get_viewdef('vv3', true); -select pg_get_viewdef('vv4', true); - --- Implicit coercions in a JOIN USING create issues similar to FULL JOIN - -create table tt7a (x date, xx int, y int); -alter table tt7a drop column xx; -create table tt8a (x timestamptz, z int); - -create view vv2a as -select * from (values(now(),2,3,now(),5)) v(a,b,c,d,e) -union all -select * from tt7a left join tt8a using (x), tt8a tt8ax; - -select pg_get_viewdef('vv2a', true); - --- --- Also check dropping a column that existed when the view was made --- - -create table tt9 (x int, xx int, y int); -create table tt10 (x int, z int); - -create view vv5 as select x,y,z from tt9 join tt10 using(x); - -select pg_get_viewdef('vv5', true); - -alter table tt9 drop column xx; - -select pg_get_viewdef('vv5', true); - --- --- Another corner case is that we might add a column to a table below a --- JOIN USING, and thereby make the USING column name ambiguous --- - -create table tt11 (x int, y int); -create table tt12 (x int, z int); -create table tt13 (z int, q int); - -create view vv6 as select x,y,z,q from - (tt11 join tt12 using(x)) join tt13 using(z); - -select pg_get_viewdef('vv6', true); - -alter table tt11 add column z int; - -select pg_get_viewdef('vv6', true); - --- --- Check cases involving dropped/altered columns in a function's rowtype result --- - -create table tt14t (f1 text, f2 text, f3 text, f4 text); -insert into tt14t values('foo', 'bar', 'baz', '42'); - -alter table tt14t drop column f2; - -create function tt14f() returns setof tt14t as -$$ -declare - rec1 record; -begin - for rec1 in select * from tt14t - loop - return next rec1; - end loop; -end; -$$ -language plpgsql; - -create view tt14v as select t.* from tt14f() t; - -select pg_get_viewdef('tt14v', true); -select * from tt14v; - -begin; - --- this perhaps should be rejected, but it isn't: -alter table tt14t drop column f3; - --- f3 is still in the view ... -select pg_get_viewdef('tt14v', true); --- but will fail at execution -select f1, f4 from tt14v; -select * from tt14v; - -rollback; - -begin; - --- this perhaps should be rejected, but it isn't: -alter table tt14t alter column f4 type integer using f4::integer; - --- f4 is still in the view ... -select pg_get_viewdef('tt14v', true); --- but will fail at execution -select f1, f3 from tt14v; -select * from tt14v; - -rollback; - --- check display of whole-row variables in some corner cases - -create type nestedcomposite as (x int8_tbl); -create view tt15v as select row(i)::nestedcomposite from int8_tbl i; -select * from tt15v; -select pg_get_viewdef('tt15v', true); -select row(i.*::int8_tbl)::nestedcomposite from int8_tbl i; - -create view tt16v as select * from int8_tbl i, lateral(values(i)) ss; -select * from tt16v; -select pg_get_viewdef('tt16v', true); -select * from int8_tbl i, lateral(values(i.*::int8_tbl)) ss; - -create view tt17v as select * from int8_tbl i where i in (values(i)); -select * from tt17v; -select pg_get_viewdef('tt17v', true); -select * from int8_tbl i where i.* in (values(i.*::int8_tbl)); - -create table tt15v_log(o tt15v, n tt15v, incr bool); -create rule updlog as on update to tt15v do also - insert into tt15v_log values(old, new, row(old,old) < row(new,new)); -\d+ tt15v - --- check unique-ification of overlength names - -create view tt18v as - select * from int8_tbl xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxy - union all - select * from int8_tbl xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz; -select pg_get_viewdef('tt18v', true); -explain (costs off) select * from tt18v; - --- check display of ScalarArrayOp with a sub-select - -select 'foo'::text = any(array['abc','def','foo']::text[]); -select 'foo'::text = any((select array['abc','def','foo']::text[])); -- fail -select 'foo'::text = any((select array['abc','def','foo']::text[])::text[]); - -create view tt19v as -select 'foo'::text = any(array['abc','def','foo']::text[]) c1, - 'foo'::text = any((select array['abc','def','foo']::text[])::text[]) c2; -select pg_get_viewdef('tt19v', true); - --- check display of assorted RTE_FUNCTION expressions - -create view tt20v as -select * from - coalesce(1,2) as c, - collation for ('x'::text) col, - current_date as d, - localtimestamp(3) as t, - cast(1+2 as int4) as i4, - cast(1+2 as int8) as i8; -select pg_get_viewdef('tt20v', true); - --- reverse-listing of various special function syntaxes required by SQL - -create view tt201v as -select - extract(day from now()) as extr, - (now(), '1 day'::interval) overlaps - (current_timestamp(2), '1 day'::interval) as o, - 'foo' is normalized isn, - 'foo' is nfkc normalized isnn, - normalize('foo') as n, - normalize('foo', nfkd) as nfkd, - overlay('foo' placing 'bar' from 2) as ovl, - overlay('foo' placing 'bar' from 2 for 3) as ovl2, - position('foo' in 'foobar') as p, - substring('foo' from 2 for 3) as s, - substring('foo' similar 'f' escape '#') as ss, - substring('foo' from 'oo') as ssf, -- historically-permitted abuse - trim(' ' from ' foo ') as bt, - trim(leading ' ' from ' foo ') as lt, - trim(trailing ' foo ') as rt, - trim(E'\\000'::bytea from E'\\000Tom\\000'::bytea) as btb, - trim(leading E'\\000'::bytea from E'\\000Tom\\000'::bytea) as ltb, - trim(trailing E'\\000'::bytea from E'\\000Tom\\000'::bytea) as rtb; -select pg_get_viewdef('tt201v', true); - --- corner cases with empty join conditions - -create view tt21v as -select * from tt5 natural inner join tt6; -select pg_get_viewdef('tt21v', true); - -create view tt22v as -select * from tt5 natural left join tt6; -select pg_get_viewdef('tt22v', true); - --- check handling of views with immediately-renamed columns - -create view tt23v (col_a, col_b) as -select q1 as other_name1, q2 as other_name2 from int8_tbl -union -select 42, 43; - -select pg_get_viewdef('tt23v', true); -select pg_get_ruledef(oid, true) from pg_rewrite - where ev_class = 'tt23v'::regclass and ev_type = '1'; - --- test extraction of FieldSelect field names (get_name_for_var_field) - -create view tt24v as -with cte as materialized (select r from (values(1,2),(3,4)) r) -select (r).column2 as col_a, (rr).column2 as col_b from - cte join (select rr from (values(1,7),(3,8)) rr limit 2) ss - on (r).column1 = (rr).column1; -select pg_get_viewdef('tt24v', true); -create view tt25v as -with cte as materialized (select pg_get_keywords() k) -select (k).word from cte; -select pg_get_viewdef('tt25v', true); --- also check cases seen only in EXPLAIN -explain (verbose, costs off) -select * from tt24v; -explain (verbose, costs off) -select (r).column2 from (select r from (values(1,2),(3,4)) r limit 1) ss; - --- test pretty-print parenthesization rules, and SubLink deparsing - -create view tt26v as -select x + y + z as c1, - (x * y) + z as c2, - x + (y * z) as c3, - (x + y) * z as c4, - x * (y + z) as c5, - x + (y + z) as c6, - x + (y # z) as c7, - (x > y) AND (y > z OR x > z) as c8, - (x > y) OR (y > z AND NOT (x > z)) as c9, - (x,y) <> ALL (values(1,2),(3,4)) as c10, - (x,y) <= ANY (values(1,2),(3,4)) as c11 -from (values(1,2,3)) v(x,y,z); -select pg_get_viewdef('tt26v', true); - --- clean up all the random objects we made above -DROP SCHEMA temp_view_test CASCADE; -DROP SCHEMA testviewschm2 CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdependency.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdependency.sql deleted file mode 100644 index 2559c62d0b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdependency.sql +++ /dev/null @@ -1,116 +0,0 @@ --- --- DEPENDENCIES --- - -CREATE USER regress_dep_user; -CREATE USER regress_dep_user2; -CREATE USER regress_dep_user3; -CREATE GROUP regress_dep_group; - -CREATE TABLE deptest (f1 serial primary key, f2 text); - -GRANT SELECT ON TABLE deptest TO GROUP regress_dep_group; -GRANT ALL ON TABLE deptest TO regress_dep_user, regress_dep_user2; - --- can't drop neither because they have privileges somewhere -DROP USER regress_dep_user; -DROP GROUP regress_dep_group; - --- if we revoke the privileges we can drop the group -REVOKE SELECT ON deptest FROM GROUP regress_dep_group; -DROP GROUP regress_dep_group; - --- can't drop the user if we revoke the privileges partially -REVOKE SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES ON deptest FROM regress_dep_user; -DROP USER regress_dep_user; - --- now we are OK to drop him -REVOKE TRIGGER ON deptest FROM regress_dep_user; -DROP USER regress_dep_user; - --- we are OK too if we drop the privileges all at once -REVOKE ALL ON deptest FROM regress_dep_user2; -DROP USER regress_dep_user2; - --- can't drop the owner of an object --- the error message detail here would include a pg_toast_nnn name that --- is not constant, so suppress it -\set VERBOSITY terse -ALTER TABLE deptest OWNER TO regress_dep_user3; -DROP USER regress_dep_user3; -\set VERBOSITY default - --- if we drop the object, we can drop the user too -DROP TABLE deptest; -DROP USER regress_dep_user3; - --- Test DROP OWNED -CREATE USER regress_dep_user0; -CREATE USER regress_dep_user1; -CREATE USER regress_dep_user2; -SET SESSION AUTHORIZATION regress_dep_user0; --- permission denied -DROP OWNED BY regress_dep_user1; -DROP OWNED BY regress_dep_user0, regress_dep_user2; -REASSIGN OWNED BY regress_dep_user0 TO regress_dep_user1; -REASSIGN OWNED BY regress_dep_user1 TO regress_dep_user0; --- this one is allowed -DROP OWNED BY regress_dep_user0; - -CREATE TABLE deptest1 (f1 int unique); -GRANT ALL ON deptest1 TO regress_dep_user1 WITH GRANT OPTION; - -SET SESSION AUTHORIZATION regress_dep_user1; -CREATE TABLE deptest (a serial primary key, b text); -GRANT ALL ON deptest1 TO regress_dep_user2; -RESET SESSION AUTHORIZATION; -\z deptest1 - -DROP OWNED BY regress_dep_user1; --- all grants revoked -\z deptest1 --- table was dropped -\d deptest - --- Test REASSIGN OWNED -GRANT ALL ON deptest1 TO regress_dep_user1; -GRANT CREATE ON DATABASE regression TO regress_dep_user1; - -SET SESSION AUTHORIZATION regress_dep_user1; -CREATE SCHEMA deptest; -CREATE TABLE deptest (a serial primary key, b text); -ALTER DEFAULT PRIVILEGES FOR ROLE regress_dep_user1 IN SCHEMA deptest - GRANT ALL ON TABLES TO regress_dep_user2; -CREATE FUNCTION deptest_func() RETURNS void LANGUAGE plpgsql - AS $$ BEGIN END; $$; -CREATE TYPE deptest_enum AS ENUM ('red'); -CREATE TYPE deptest_range AS RANGE (SUBTYPE = int4); - -CREATE TABLE deptest2 (f1 int); --- make a serial column the hard way -CREATE SEQUENCE ss1; -ALTER TABLE deptest2 ALTER f1 SET DEFAULT nextval('ss1'); -ALTER SEQUENCE ss1 OWNED BY deptest2.f1; - --- When reassigning ownership of a composite type, its pg_class entry --- should match -CREATE TYPE deptest_t AS (a int); -SELECT typowner = relowner -FROM pg_type JOIN pg_class c ON typrelid = c.oid WHERE typname = 'deptest_t'; - -RESET SESSION AUTHORIZATION; -REASSIGN OWNED BY regress_dep_user1 TO regress_dep_user2; -\dt deptest - -SELECT typowner = relowner -FROM pg_type JOIN pg_class c ON typrelid = c.oid WHERE typname = 'deptest_t'; - --- doesn't work: grant still exists -DROP USER regress_dep_user1; -DROP OWNED BY regress_dep_user1; -DROP USER regress_dep_user1; - -DROP USER regress_dep_user2; -DROP OWNED BY regress_dep_user2, regress_dep_user0; -DROP USER regress_dep_user2; -DROP USER regress_dep_user0; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdomain.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdomain.sql deleted file mode 100644 index bf48c53e9c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdomain.sql +++ /dev/null @@ -1,779 +0,0 @@ --- --- Test domains. --- - --- Test Comment / Drop -create domain domaindroptest int4; -comment on domain domaindroptest is 'About to drop this..'; - -create domain dependenttypetest domaindroptest; - --- fail because of dependent type -drop domain domaindroptest; - -drop domain domaindroptest cascade; - --- this should fail because already gone -drop domain domaindroptest cascade; - - --- Test domain input. - --- Note: the point of checking both INSERT and COPY FROM is that INSERT --- exercises CoerceToDomain while COPY exercises domain_in. - -create domain domainvarchar varchar(5); -create domain domainnumeric numeric(8,2); -create domain domainint4 int4; -create domain domaintext text; - --- Test explicit coercions --- these should succeed (and truncate) -SELECT cast('123456' as domainvarchar); -SELECT cast('12345' as domainvarchar); - --- Test tables using domains -create table basictest - ( testint4 domainint4 - , testtext domaintext - , testvarchar domainvarchar - , testnumeric domainnumeric - ); - -INSERT INTO basictest values ('88', 'haha', 'short', '123.12'); -- Good -INSERT INTO basictest values ('88', 'haha', 'short text', '123.12'); -- Bad varchar -INSERT INTO basictest values ('88', 'haha', 'short', '123.1212'); -- Truncate numeric - --- Test copy -COPY basictest (testvarchar) FROM stdin; -- fail -notsoshorttext -\. - -COPY basictest (testvarchar) FROM stdin; -short -\. - -select * from basictest; - --- check that domains inherit operations from base types -select testtext || testvarchar as concat, testnumeric + 42 as sum -from basictest; - --- check that union/case/coalesce type resolution handles domains properly -select pg_typeof(coalesce(4::domainint4, 7)); -select pg_typeof(coalesce(4::domainint4, 7::domainint4)); - -drop table basictest; -drop domain domainvarchar restrict; -drop domain domainnumeric restrict; -drop domain domainint4 restrict; -drop domain domaintext; - - --- Test domains over array types - -create domain domainint4arr int4[1]; -create domain domainchar4arr varchar(4)[2][3]; - -create table domarrtest - ( testint4arr domainint4arr - , testchar4arr domainchar4arr - ); -INSERT INTO domarrtest values ('{2,2}', '{{"a","b"},{"c","d"}}'); -INSERT INTO domarrtest values ('{{2,2},{2,2}}', '{{"a","b"}}'); -INSERT INTO domarrtest values ('{2,2}', '{{"a","b"},{"c","d"},{"e","f"}}'); -INSERT INTO domarrtest values ('{2,2}', '{{"a"},{"c"}}'); -INSERT INTO domarrtest values (NULL, '{{"a","b","c"},{"d","e","f"}}'); -INSERT INTO domarrtest values (NULL, '{{"toolong","b","c"},{"d","e","f"}}'); -INSERT INTO domarrtest (testint4arr[1], testint4arr[3]) values (11,22); -select * from domarrtest; -select testint4arr[1], testchar4arr[2:2] from domarrtest; -select array_dims(testint4arr), array_dims(testchar4arr) from domarrtest; - -COPY domarrtest FROM stdin; -{3,4} {q,w,e} -\N \N -\. - -COPY domarrtest FROM stdin; -- fail -{3,4} {qwerty,w,e} -\. - -select * from domarrtest; - -update domarrtest set - testint4arr[1] = testint4arr[1] + 1, - testint4arr[3] = testint4arr[3] - 1 -where testchar4arr is null; - -select * from domarrtest where testchar4arr is null; - -drop table domarrtest; -drop domain domainint4arr restrict; -drop domain domainchar4arr restrict; - -create domain dia as int[]; -select '{1,2,3}'::dia; -select array_dims('{1,2,3}'::dia); -select pg_typeof('{1,2,3}'::dia); -select pg_typeof('{1,2,3}'::dia || 42); -- should be int[] not dia -drop domain dia; - - --- Test domains over composites - -create type comptype as (r float8, i float8); -create domain dcomptype as comptype; -create table dcomptable (d1 dcomptype unique); - -insert into dcomptable values (row(1,2)::dcomptype); -insert into dcomptable values (row(3,4)::comptype); -insert into dcomptable values (row(1,2)::dcomptype); -- fail on uniqueness -insert into dcomptable (d1.r) values(11); - -select * from dcomptable; -select (d1).r, (d1).i, (d1).* from dcomptable; -update dcomptable set d1.r = (d1).r + 1 where (d1).i > 0; -select * from dcomptable; - -alter domain dcomptype add constraint c1 check ((value).r <= (value).i); -alter domain dcomptype add constraint c2 check ((value).r > (value).i); -- fail - -select row(2,1)::dcomptype; -- fail -insert into dcomptable values (row(1,2)::comptype); -insert into dcomptable values (row(2,1)::comptype); -- fail -insert into dcomptable (d1.r) values(99); -insert into dcomptable (d1.r, d1.i) values(99, 100); -insert into dcomptable (d1.r, d1.i) values(100, 99); -- fail -update dcomptable set d1.r = (d1).r + 1 where (d1).i > 0; -- fail -update dcomptable set d1.r = (d1).r - 1, d1.i = (d1).i + 1 where (d1).i > 0; -select * from dcomptable; - -explain (verbose, costs off) - update dcomptable set d1.r = (d1).r - 1, d1.i = (d1).i + 1 where (d1).i > 0; -create rule silly as on delete to dcomptable do instead - update dcomptable set d1.r = (d1).r - 1, d1.i = (d1).i + 1 where (d1).i > 0; -\d+ dcomptable - -drop table dcomptable; -drop type comptype cascade; - - --- check altering and dropping columns used by domain constraints -create type comptype as (r float8, i float8); -create domain dcomptype as comptype; -alter domain dcomptype add constraint c1 check ((value).r > 0); -comment on constraint c1 on domain dcomptype is 'random commentary'; - -select row(0,1)::dcomptype; -- fail - -alter type comptype alter attribute r type varchar; -- fail -alter type comptype alter attribute r type bigint; - -alter type comptype drop attribute r; -- fail -alter type comptype drop attribute i; - -select conname, obj_description(oid, 'pg_constraint') from pg_constraint - where contypid = 'dcomptype'::regtype; -- check comment is still there - -drop type comptype cascade; - - --- Test domains over arrays of composite - -create type comptype as (r float8, i float8); -create domain dcomptypea as comptype[]; -create table dcomptable (d1 dcomptypea unique); - -insert into dcomptable values (array[row(1,2)]::dcomptypea); -insert into dcomptable values (array[row(3,4), row(5,6)]::comptype[]); -insert into dcomptable values (array[row(7,8)::comptype, row(9,10)::comptype]); -insert into dcomptable values (array[row(1,2)]::dcomptypea); -- fail on uniqueness -insert into dcomptable (d1[1]) values(row(9,10)); -insert into dcomptable (d1[1].r) values(11); - -select * from dcomptable; -select d1[2], d1[1].r, d1[1].i from dcomptable; -update dcomptable set d1[2] = row(d1[2].i, d1[2].r); -select * from dcomptable; -update dcomptable set d1[1].r = d1[1].r + 1 where d1[1].i > 0; -select * from dcomptable; - -alter domain dcomptypea add constraint c1 check (value[1].r <= value[1].i); -alter domain dcomptypea add constraint c2 check (value[1].r > value[1].i); -- fail - -select array[row(2,1)]::dcomptypea; -- fail -insert into dcomptable values (array[row(1,2)]::comptype[]); -insert into dcomptable values (array[row(2,1)]::comptype[]); -- fail -insert into dcomptable (d1[1].r) values(99); -insert into dcomptable (d1[1].r, d1[1].i) values(99, 100); -insert into dcomptable (d1[1].r, d1[1].i) values(100, 99); -- fail -update dcomptable set d1[1].r = d1[1].r + 1 where d1[1].i > 0; -- fail -update dcomptable set d1[1].r = d1[1].r - 1, d1[1].i = d1[1].i + 1 - where d1[1].i > 0; -select * from dcomptable; - -explain (verbose, costs off) - update dcomptable set d1[1].r = d1[1].r - 1, d1[1].i = d1[1].i + 1 - where d1[1].i > 0; -create rule silly as on delete to dcomptable do instead - update dcomptable set d1[1].r = d1[1].r - 1, d1[1].i = d1[1].i + 1 - where d1[1].i > 0; -\d+ dcomptable - -drop table dcomptable; -drop type comptype cascade; - - --- Test arrays over domains - -create domain posint as int check (value > 0); - -create table pitable (f1 posint[]); -insert into pitable values(array[42]); -insert into pitable values(array[-1]); -- fail -insert into pitable values('{0}'); -- fail -update pitable set f1[1] = f1[1] + 1; -update pitable set f1[1] = 0; -- fail -select * from pitable; -drop table pitable; - -create domain vc4 as varchar(4); -create table vc4table (f1 vc4[]); -insert into vc4table values(array['too long']); -- fail -insert into vc4table values(array['too long']::vc4[]); -- cast truncates -select * from vc4table; -drop table vc4table; -drop type vc4; - --- You can sort of fake arrays-of-arrays by putting a domain in between -create domain dposinta as posint[]; -create table dposintatable (f1 dposinta[]); -insert into dposintatable values(array[array[42]]); -- fail -insert into dposintatable values(array[array[42]::posint[]]); -- still fail -insert into dposintatable values(array[array[42]::dposinta]); -- but this works -select f1, f1[1], (f1[1])[1] from dposintatable; -select pg_typeof(f1) from dposintatable; -select pg_typeof(f1[1]) from dposintatable; -select pg_typeof(f1[1][1]) from dposintatable; -select pg_typeof((f1[1])[1]) from dposintatable; -update dposintatable set f1[2] = array[99]; -select f1, f1[1], (f1[2])[1] from dposintatable; --- it'd be nice if you could do something like this, but for now you can't: -update dposintatable set f1[2][1] = array[97]; --- maybe someday we can make this syntax work: -update dposintatable set (f1[2])[1] = array[98]; - -drop table dposintatable; -drop domain posint cascade; - - --- Test arrays over domains of composite - -create type comptype as (cf1 int, cf2 int); -create domain dcomptype as comptype check ((value).cf1 > 0); - -create table dcomptable (f1 dcomptype[]); -insert into dcomptable values (null); -update dcomptable set f1[1].cf2 = 5; -table dcomptable; -update dcomptable set f1[1].cf1 = -1; -- fail -update dcomptable set f1[1].cf1 = 1; -table dcomptable; - -drop table dcomptable; -drop type comptype cascade; - - --- Test not-null restrictions - -create domain dnotnull varchar(15) NOT NULL; -create domain dnull varchar(15); -create domain dcheck varchar(15) NOT NULL CHECK (VALUE = 'a' OR VALUE = 'c' OR VALUE = 'd'); - -create table nulltest - ( col1 dnotnull - , col2 dnotnull NULL -- NOT NULL in the domain cannot be overridden - , col3 dnull NOT NULL - , col4 dnull - , col5 dcheck CHECK (col5 IN ('c', 'd')) - ); -INSERT INTO nulltest DEFAULT VALUES; -INSERT INTO nulltest values ('a', 'b', 'c', 'd', 'c'); -- Good -insert into nulltest values ('a', 'b', 'c', 'd', NULL); -insert into nulltest values ('a', 'b', 'c', 'd', 'a'); -INSERT INTO nulltest values (NULL, 'b', 'c', 'd', 'd'); -INSERT INTO nulltest values ('a', NULL, 'c', 'd', 'c'); -INSERT INTO nulltest values ('a', 'b', NULL, 'd', 'c'); -INSERT INTO nulltest values ('a', 'b', 'c', NULL, 'd'); -- Good - --- Test copy -COPY nulltest FROM stdin; --fail -a b \N d d -\. - -COPY nulltest FROM stdin; --fail -a b c d \N -\. - --- Last row is bad -COPY nulltest FROM stdin; -a b c \N c -a b c \N d -a b c \N a -\. - -select * from nulltest; - --- Test out coerced (casted) constraints -SELECT cast('1' as dnotnull); -SELECT cast(NULL as dnotnull); -- fail -SELECT cast(cast(NULL as dnull) as dnotnull); -- fail -SELECT cast(col4 as dnotnull) from nulltest; -- fail - --- cleanup -drop table nulltest; -drop domain dnotnull restrict; -drop domain dnull restrict; -drop domain dcheck restrict; - - -create domain ddef1 int4 DEFAULT 3; -create domain ddef2 oid DEFAULT '12'; --- Type mixing, function returns int8 -create domain ddef3 text DEFAULT 5; -create sequence ddef4_seq; -create domain ddef4 int4 DEFAULT nextval('ddef4_seq'); -create domain ddef5 numeric(8,2) NOT NULL DEFAULT '12.12'; - -create table defaulttest - ( col1 ddef1 - , col2 ddef2 - , col3 ddef3 - , col4 ddef4 PRIMARY KEY - , col5 ddef1 NOT NULL DEFAULT NULL - , col6 ddef2 DEFAULT '88' - , col7 ddef4 DEFAULT 8000 - , col8 ddef5 - ); -insert into defaulttest(col4) values(0); -- fails, col5 defaults to null -alter table defaulttest alter column col5 drop default; -insert into defaulttest default values; -- succeeds, inserts domain default --- We used to treat SET DEFAULT NULL as equivalent to DROP DEFAULT; wrong -alter table defaulttest alter column col5 set default null; -insert into defaulttest(col4) values(0); -- fails -alter table defaulttest alter column col5 drop default; -insert into defaulttest default values; -insert into defaulttest default values; - --- Test defaults with copy -COPY defaulttest(col5) FROM stdin; -42 -\. - -select * from defaulttest; - -drop table defaulttest cascade; - --- Test ALTER DOMAIN .. NOT NULL -create domain dnotnulltest integer; -create table domnotnull -( col1 dnotnulltest -, col2 dnotnulltest -); - -insert into domnotnull default values; -alter domain dnotnulltest set not null; -- fails - -update domnotnull set col1 = 5; -alter domain dnotnulltest set not null; -- fails - -update domnotnull set col2 = 6; - -alter domain dnotnulltest set not null; - -update domnotnull set col1 = null; -- fails - -alter domain dnotnulltest drop not null; - -update domnotnull set col1 = null; - -drop domain dnotnulltest cascade; - --- Test ALTER DOMAIN .. DEFAULT .. -create table domdeftest (col1 ddef1); - -insert into domdeftest default values; -select * from domdeftest; - -alter domain ddef1 set default '42'; -insert into domdeftest default values; -select * from domdeftest; - -alter domain ddef1 drop default; -insert into domdeftest default values; -select * from domdeftest; - -drop table domdeftest; - --- Test ALTER DOMAIN .. CONSTRAINT .. -create domain con as integer; -create table domcontest (col1 con); - -insert into domcontest values (1); -insert into domcontest values (2); -alter domain con add constraint t check (VALUE < 1); -- fails - -alter domain con add constraint t check (VALUE < 34); -alter domain con add check (VALUE > 0); - -insert into domcontest values (-5); -- fails -insert into domcontest values (42); -- fails -insert into domcontest values (5); - -alter domain con drop constraint t; -insert into domcontest values (-5); --fails -insert into domcontest values (42); - -alter domain con drop constraint nonexistent; -alter domain con drop constraint if exists nonexistent; - --- Test ALTER DOMAIN .. CONSTRAINT .. NOT VALID -create domain things AS INT; -CREATE TABLE thethings (stuff things); -INSERT INTO thethings (stuff) VALUES (55); -ALTER DOMAIN things ADD CONSTRAINT meow CHECK (VALUE < 11); -ALTER DOMAIN things ADD CONSTRAINT meow CHECK (VALUE < 11) NOT VALID; -ALTER DOMAIN things VALIDATE CONSTRAINT meow; -UPDATE thethings SET stuff = 10; -ALTER DOMAIN things VALIDATE CONSTRAINT meow; - --- Confirm ALTER DOMAIN with RULES. -create table domtab (col1 integer); -create domain dom as integer; -create view domview as select cast(col1 as dom) from domtab; -insert into domtab (col1) values (null); -insert into domtab (col1) values (5); -select * from domview; - -alter domain dom set not null; -select * from domview; -- fail - -alter domain dom drop not null; -select * from domview; - -alter domain dom add constraint domchkgt6 check(value > 6); -select * from domview; --fail - -alter domain dom drop constraint domchkgt6 restrict; -select * from domview; - --- cleanup -drop domain ddef1 restrict; -drop domain ddef2 restrict; -drop domain ddef3 restrict; -drop domain ddef4 restrict; -drop domain ddef5 restrict; -drop sequence ddef4_seq; - --- Test domains over domains -create domain vchar4 varchar(4); -create domain dinter vchar4 check (substring(VALUE, 1, 1) = 'x'); -create domain dtop dinter check (substring(VALUE, 2, 1) = '1'); - -select 'x123'::dtop; -select 'x1234'::dtop; -- explicit coercion should truncate -select 'y1234'::dtop; -- fail -select 'y123'::dtop; -- fail -select 'yz23'::dtop; -- fail -select 'xz23'::dtop; -- fail - -create temp table dtest(f1 dtop); - -insert into dtest values('x123'); -insert into dtest values('x1234'); -- fail, implicit coercion -insert into dtest values('y1234'); -- fail, implicit coercion -insert into dtest values('y123'); -- fail -insert into dtest values('yz23'); -- fail -insert into dtest values('xz23'); -- fail - -drop table dtest; -drop domain vchar4 cascade; - --- Make sure that constraints of newly-added domain columns are --- enforced correctly, even if there's no default value for the new --- column. Per bug #1433 -create domain str_domain as text not null; - -create table domain_test (a int, b int); - -insert into domain_test values (1, 2); -insert into domain_test values (1, 2); - --- should fail -alter table domain_test add column c str_domain; - -create domain str_domain2 as text check (value <> 'foo') default 'foo'; - --- should fail -alter table domain_test add column d str_domain2; - --- Check that domain constraints on prepared statement parameters of --- unknown type are enforced correctly. -create domain pos_int as int4 check (value > 0) not null; -prepare s1 as select $1::pos_int = 10 as "is_ten"; - -execute s1(10); -execute s1(0); -- should fail -execute s1(NULL); -- should fail - --- Check that domain constraints on plpgsql function parameters, results, --- and local variables are enforced correctly. - -create function doubledecrement(p1 pos_int) returns pos_int as $$ -declare v pos_int; -begin - return p1; -end$$ language plpgsql; - -select doubledecrement(3); -- fail because of implicit null assignment - -create or replace function doubledecrement(p1 pos_int) returns pos_int as $$ -declare v pos_int := 0; -begin - return p1; -end$$ language plpgsql; - -select doubledecrement(3); -- fail at initialization assignment - -create or replace function doubledecrement(p1 pos_int) returns pos_int as $$ -declare v pos_int := 1; -begin - v := p1 - 1; - return v - 1; -end$$ language plpgsql; - -select doubledecrement(null); -- fail before call -select doubledecrement(0); -- fail before call -select doubledecrement(1); -- fail at assignment to v -select doubledecrement(2); -- fail at return -select doubledecrement(3); -- good - --- Check that ALTER DOMAIN tests columns of derived types - -create domain posint as int4; - --- Currently, this doesn't work for composite types, but verify it complains -create type ddtest1 as (f1 posint); -create table ddtest2(f1 ddtest1); -insert into ddtest2 values(row(-1)); -alter domain posint add constraint c1 check(value >= 0); -drop table ddtest2; - --- Likewise for domains within arrays of composite -create table ddtest2(f1 ddtest1[]); -insert into ddtest2 values('{(-1)}'); -alter domain posint add constraint c1 check(value >= 0); -drop table ddtest2; - --- Likewise for domains within domains over composite -create domain ddtest1d as ddtest1; -create table ddtest2(f1 ddtest1d); -insert into ddtest2 values('(-1)'); -alter domain posint add constraint c1 check(value >= 0); -drop table ddtest2; -drop domain ddtest1d; - --- Likewise for domains within domains over array of composite -create domain ddtest1d as ddtest1[]; -create table ddtest2(f1 ddtest1d); -insert into ddtest2 values('{(-1)}'); -alter domain posint add constraint c1 check(value >= 0); -drop table ddtest2; -drop domain ddtest1d; - --- Doesn't work for ranges, either -create type rposint as range (subtype = posint); -create table ddtest2(f1 rposint); -insert into ddtest2 values('(-1,3]'); -alter domain posint add constraint c1 check(value >= 0); -drop table ddtest2; -drop type rposint; - -alter domain posint add constraint c1 check(value >= 0); - -create domain posint2 as posint check (value % 2 = 0); -create table ddtest2(f1 posint2); -insert into ddtest2 values(11); -- fail -insert into ddtest2 values(-2); -- fail -insert into ddtest2 values(2); - -alter domain posint add constraint c2 check(value >= 10); -- fail -alter domain posint add constraint c2 check(value > 0); -- OK - -drop table ddtest2; -drop type ddtest1; -drop domain posint cascade; - --- --- Check enforcement of domain-related typmod in plpgsql (bug #5717) --- - -create or replace function array_elem_check(numeric) returns numeric as $$ -declare - x numeric(4,2)[1]; -begin - x[1] := $1; - return x[1]; -end$$ language plpgsql; - -select array_elem_check(121.00); -select array_elem_check(1.23456); - -create domain mynums as numeric(4,2)[1]; - -create or replace function array_elem_check(numeric) returns numeric as $$ -declare - x mynums; -begin - x[1] := $1; - return x[1]; -end$$ language plpgsql; - -select array_elem_check(121.00); -select array_elem_check(1.23456); - -create domain mynums2 as mynums; - -create or replace function array_elem_check(numeric) returns numeric as $$ -declare - x mynums2; -begin - x[1] := $1; - return x[1]; -end$$ language plpgsql; - -select array_elem_check(121.00); -select array_elem_check(1.23456); - -drop function array_elem_check(numeric); - --- --- Check enforcement of array-level domain constraints --- - -create domain orderedpair as int[2] check (value[1] < value[2]); - -select array[1,2]::orderedpair; -select array[2,1]::orderedpair; -- fail - -create temp table op (f1 orderedpair); -insert into op values (array[1,2]); -insert into op values (array[2,1]); -- fail - -update op set f1[2] = 3; -update op set f1[2] = 0; -- fail -select * from op; - -create or replace function array_elem_check(int) returns int as $$ -declare - x orderedpair := '{1,2}'; -begin - x[2] := $1; - return x[2]; -end$$ language plpgsql; - -select array_elem_check(3); -select array_elem_check(-1); - -drop function array_elem_check(int); - --- --- Check enforcement of changing constraints in plpgsql --- - -create domain di as int; - -create function dom_check(int) returns di as $$ -declare d di; -begin - d := $1::di; - return d; -end -$$ language plpgsql immutable; - -select dom_check(0); - -alter domain di add constraint pos check (value > 0); - -select dom_check(0); -- fail - -alter domain di drop constraint pos; - -select dom_check(0); - --- implicit cast during assignment is a separate code path, test that too - -create or replace function dom_check(int) returns di as $$ -declare d di; -begin - d := $1; - return d; -end -$$ language plpgsql immutable; - -select dom_check(0); - -alter domain di add constraint pos check (value > 0); - -select dom_check(0); -- fail - -alter domain di drop constraint pos; - -select dom_check(0); - -drop function dom_check(int); - -drop domain di; - --- --- Check use of a (non-inline-able) SQL function in a domain constraint; --- this has caused issues in the past --- - -create function sql_is_distinct_from(anyelement, anyelement) -returns boolean language sql -as 'select $1 is distinct from $2 limit 1'; - -create domain inotnull int - check (sql_is_distinct_from(value, null)); - -select 1::inotnull; -select null::inotnull; - -create table dom_table (x inotnull); -insert into dom_table values ('1'); -insert into dom_table values (1); -insert into dom_table values (null); - -drop table dom_table; -drop domain inotnull; -drop function sql_is_distinct_from(anyelement, anyelement); - --- --- Renaming --- - -create domain testdomain1 as int; -alter domain testdomain1 rename to testdomain2; -alter type testdomain2 rename to testdomain3; -- alter type also works -drop domain testdomain3; - - --- --- Renaming domain constraints --- - -create domain testdomain1 as int constraint unsigned check (value > 0); -alter domain testdomain1 rename constraint unsigned to unsigned_foo; -alter domain testdomain1 drop constraint unsigned_foo; -drop domain testdomain1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdrop_if_exists.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdrop_if_exists.sql deleted file mode 100644 index ac6168b91f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fdrop_if_exists.sql +++ /dev/null @@ -1,304 +0,0 @@ --- --- IF EXISTS tests --- - --- table (will be really dropped at the end) - -DROP TABLE test_exists; - -DROP TABLE IF EXISTS test_exists; - -CREATE TABLE test_exists (a int, b text); - --- view - -DROP VIEW test_view_exists; - -DROP VIEW IF EXISTS test_view_exists; - -CREATE VIEW test_view_exists AS select * from test_exists; - -DROP VIEW IF EXISTS test_view_exists; - -DROP VIEW test_view_exists; - --- index - -DROP INDEX test_index_exists; - -DROP INDEX IF EXISTS test_index_exists; - -CREATE INDEX test_index_exists on test_exists(a); - -DROP INDEX IF EXISTS test_index_exists; - -DROP INDEX test_index_exists; - --- sequence - -DROP SEQUENCE test_sequence_exists; - -DROP SEQUENCE IF EXISTS test_sequence_exists; - -CREATE SEQUENCE test_sequence_exists; - -DROP SEQUENCE IF EXISTS test_sequence_exists; - -DROP SEQUENCE test_sequence_exists; - --- schema - -DROP SCHEMA test_schema_exists; - -DROP SCHEMA IF EXISTS test_schema_exists; - -CREATE SCHEMA test_schema_exists; - -DROP SCHEMA IF EXISTS test_schema_exists; - -DROP SCHEMA test_schema_exists; - --- type - -DROP TYPE test_type_exists; - -DROP TYPE IF EXISTS test_type_exists; - -CREATE type test_type_exists as (a int, b text); - -DROP TYPE IF EXISTS test_type_exists; - -DROP TYPE test_type_exists; - --- domain - -DROP DOMAIN test_domain_exists; - -DROP DOMAIN IF EXISTS test_domain_exists; - -CREATE domain test_domain_exists as int not null check (value > 0); - -DROP DOMAIN IF EXISTS test_domain_exists; - -DROP DOMAIN test_domain_exists; - ---- ---- role/user/group ---- - -CREATE USER regress_test_u1; -CREATE ROLE regress_test_r1; -CREATE GROUP regress_test_g1; - -DROP USER regress_test_u2; - -DROP USER IF EXISTS regress_test_u1, regress_test_u2; - -DROP USER regress_test_u1; - -DROP ROLE regress_test_r2; - -DROP ROLE IF EXISTS regress_test_r1, regress_test_r2; - -DROP ROLE regress_test_r1; - -DROP GROUP regress_test_g2; - -DROP GROUP IF EXISTS regress_test_g1, regress_test_g2; - -DROP GROUP regress_test_g1; - --- collation -DROP COLLATION IF EXISTS test_collation_exists; - --- conversion -DROP CONVERSION test_conversion_exists; -DROP CONVERSION IF EXISTS test_conversion_exists; -CREATE CONVERSION test_conversion_exists - FOR 'LATIN1' TO 'UTF8' FROM iso8859_1_to_utf8; -DROP CONVERSION test_conversion_exists; - --- text search parser -DROP TEXT SEARCH PARSER test_tsparser_exists; -DROP TEXT SEARCH PARSER IF EXISTS test_tsparser_exists; - --- text search dictionary -DROP TEXT SEARCH DICTIONARY test_tsdict_exists; -DROP TEXT SEARCH DICTIONARY IF EXISTS test_tsdict_exists; -CREATE TEXT SEARCH DICTIONARY test_tsdict_exists ( - Template=ispell, - DictFile=ispell_sample, - AffFile=ispell_sample -); -DROP TEXT SEARCH DICTIONARY test_tsdict_exists; - --- test search template -DROP TEXT SEARCH TEMPLATE test_tstemplate_exists; -DROP TEXT SEARCH TEMPLATE IF EXISTS test_tstemplate_exists; - --- text search configuration -DROP TEXT SEARCH CONFIGURATION test_tsconfig_exists; -DROP TEXT SEARCH CONFIGURATION IF EXISTS test_tsconfig_exists; -CREATE TEXT SEARCH CONFIGURATION test_tsconfig_exists (COPY=english); -DROP TEXT SEARCH CONFIGURATION test_tsconfig_exists; - --- extension -DROP EXTENSION test_extension_exists; -DROP EXTENSION IF EXISTS test_extension_exists; - --- functions -DROP FUNCTION test_function_exists(); -DROP FUNCTION IF EXISTS test_function_exists(); - -DROP FUNCTION test_function_exists(int, text, int[]); -DROP FUNCTION IF EXISTS test_function_exists(int, text, int[]); - --- aggregate -DROP AGGREGATE test_aggregate_exists(*); -DROP AGGREGATE IF EXISTS test_aggregate_exists(*); - -DROP AGGREGATE test_aggregate_exists(int); -DROP AGGREGATE IF EXISTS test_aggregate_exists(int); - --- operator -DROP OPERATOR @#@ (int, int); -DROP OPERATOR IF EXISTS @#@ (int, int); -CREATE OPERATOR @#@ - (leftarg = int8, rightarg = int8, procedure = int8xor); -DROP OPERATOR @#@ (int8, int8); - --- language -DROP LANGUAGE test_language_exists; -DROP LANGUAGE IF EXISTS test_language_exists; - --- cast -DROP CAST (text AS text); -DROP CAST IF EXISTS (text AS text); - --- trigger -DROP TRIGGER test_trigger_exists ON test_exists; -DROP TRIGGER IF EXISTS test_trigger_exists ON test_exists; - -DROP TRIGGER test_trigger_exists ON no_such_table; -DROP TRIGGER IF EXISTS test_trigger_exists ON no_such_table; - -DROP TRIGGER test_trigger_exists ON no_such_schema.no_such_table; -DROP TRIGGER IF EXISTS test_trigger_exists ON no_such_schema.no_such_table; - -CREATE TRIGGER test_trigger_exists - BEFORE UPDATE ON test_exists - FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger(); -DROP TRIGGER test_trigger_exists ON test_exists; - --- rule -DROP RULE test_rule_exists ON test_exists; -DROP RULE IF EXISTS test_rule_exists ON test_exists; - -DROP RULE test_rule_exists ON no_such_table; -DROP RULE IF EXISTS test_rule_exists ON no_such_table; - -DROP RULE test_rule_exists ON no_such_schema.no_such_table; -DROP RULE IF EXISTS test_rule_exists ON no_such_schema.no_such_table; - -CREATE RULE test_rule_exists AS ON INSERT TO test_exists - DO INSTEAD - INSERT INTO test_exists VALUES (NEW.a, NEW.b || NEW.a::text); -DROP RULE test_rule_exists ON test_exists; - --- foreign data wrapper -DROP FOREIGN DATA WRAPPER test_fdw_exists; -DROP FOREIGN DATA WRAPPER IF EXISTS test_fdw_exists; - --- foreign server -DROP SERVER test_server_exists; -DROP SERVER IF EXISTS test_server_exists; - --- operator class -DROP OPERATOR CLASS test_operator_class USING btree; -DROP OPERATOR CLASS IF EXISTS test_operator_class USING btree; - -DROP OPERATOR CLASS test_operator_class USING no_such_am; -DROP OPERATOR CLASS IF EXISTS test_operator_class USING no_such_am; - --- operator family -DROP OPERATOR FAMILY test_operator_family USING btree; -DROP OPERATOR FAMILY IF EXISTS test_operator_family USING btree; - -DROP OPERATOR FAMILY test_operator_family USING no_such_am; -DROP OPERATOR FAMILY IF EXISTS test_operator_family USING no_such_am; - --- access method -DROP ACCESS METHOD no_such_am; -DROP ACCESS METHOD IF EXISTS no_such_am; - --- drop the table - -DROP TABLE IF EXISTS test_exists; - -DROP TABLE test_exists; - --- be tolerant with missing schemas, types, etc - -DROP AGGREGATE IF EXISTS no_such_schema.foo(int); -DROP AGGREGATE IF EXISTS foo(no_such_type); -DROP AGGREGATE IF EXISTS foo(no_such_schema.no_such_type); -DROP CAST IF EXISTS (INTEGER AS no_such_type2); -DROP CAST IF EXISTS (no_such_type1 AS INTEGER); -DROP CAST IF EXISTS (INTEGER AS no_such_schema.bar); -DROP CAST IF EXISTS (no_such_schema.foo AS INTEGER); -DROP COLLATION IF EXISTS no_such_schema.foo; -DROP CONVERSION IF EXISTS no_such_schema.foo; -DROP DOMAIN IF EXISTS no_such_schema.foo; -DROP FOREIGN TABLE IF EXISTS no_such_schema.foo; -DROP FUNCTION IF EXISTS no_such_schema.foo(); -DROP FUNCTION IF EXISTS foo(no_such_type); -DROP FUNCTION IF EXISTS foo(no_such_schema.no_such_type); -DROP INDEX IF EXISTS no_such_schema.foo; -DROP MATERIALIZED VIEW IF EXISTS no_such_schema.foo; -DROP OPERATOR IF EXISTS no_such_schema.+ (int, int); -DROP OPERATOR IF EXISTS + (no_such_type, no_such_type); -DROP OPERATOR IF EXISTS + (no_such_schema.no_such_type, no_such_schema.no_such_type); -DROP OPERATOR IF EXISTS # (NONE, no_such_schema.no_such_type); -DROP OPERATOR CLASS IF EXISTS no_such_schema.widget_ops USING btree; -DROP OPERATOR FAMILY IF EXISTS no_such_schema.float_ops USING btree; -DROP RULE IF EXISTS foo ON no_such_schema.bar; -DROP SEQUENCE IF EXISTS no_such_schema.foo; -DROP TABLE IF EXISTS no_such_schema.foo; -DROP TEXT SEARCH CONFIGURATION IF EXISTS no_such_schema.foo; -DROP TEXT SEARCH DICTIONARY IF EXISTS no_such_schema.foo; -DROP TEXT SEARCH PARSER IF EXISTS no_such_schema.foo; -DROP TEXT SEARCH TEMPLATE IF EXISTS no_such_schema.foo; -DROP TRIGGER IF EXISTS foo ON no_such_schema.bar; -DROP TYPE IF EXISTS no_such_schema.foo; -DROP VIEW IF EXISTS no_such_schema.foo; - --- Check we receive an ambiguous function error when there are --- multiple matching functions. -CREATE FUNCTION test_ambiguous_funcname(int) returns int as $$ select $1; $$ language sql; -CREATE FUNCTION test_ambiguous_funcname(text) returns text as $$ select $1; $$ language sql; -DROP FUNCTION test_ambiguous_funcname; -DROP FUNCTION IF EXISTS test_ambiguous_funcname; - --- cleanup -DROP FUNCTION test_ambiguous_funcname(int); -DROP FUNCTION test_ambiguous_funcname(text); - --- Likewise for procedures. -CREATE PROCEDURE test_ambiguous_procname(int) as $$ begin end; $$ language plpgsql; -CREATE PROCEDURE test_ambiguous_procname(text) as $$ begin end; $$ language plpgsql; -DROP PROCEDURE test_ambiguous_procname; -DROP PROCEDURE IF EXISTS test_ambiguous_procname; - --- Check we get a similar error if we use ROUTINE instead of PROCEDURE. -DROP ROUTINE IF EXISTS test_ambiguous_procname; - --- cleanup -DROP PROCEDURE test_ambiguous_procname(int); -DROP PROCEDURE test_ambiguous_procname(text); - --- This test checks both the functionality of 'if exists' and the syntax --- of the drop database command. -drop database test_database_exists (force); -drop database test_database_exists with (force); -drop database if exists test_database_exists (force); -drop database if exists test_database_exists with (force); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fenum.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fenum.sql deleted file mode 100644 index 6affd0d1eb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fenum.sql +++ /dev/null @@ -1,341 +0,0 @@ --- --- Enum tests --- - -CREATE TYPE rainbow AS ENUM ('red', 'orange', 'yellow', 'green', 'blue', 'purple'); - --- --- Did it create the right number of rows? --- -SELECT COUNT(*) FROM pg_enum WHERE enumtypid = 'rainbow'::regtype; - --- --- I/O functions --- -SELECT 'red'::rainbow; -SELECT 'mauve'::rainbow; - --- --- adding new values --- - -CREATE TYPE planets AS ENUM ( 'venus', 'earth', 'mars' ); - -SELECT enumlabel, enumsortorder -FROM pg_enum -WHERE enumtypid = 'planets'::regtype -ORDER BY 2; - -ALTER TYPE planets ADD VALUE 'uranus'; - -SELECT enumlabel, enumsortorder -FROM pg_enum -WHERE enumtypid = 'planets'::regtype -ORDER BY 2; - -ALTER TYPE planets ADD VALUE 'mercury' BEFORE 'venus'; -ALTER TYPE planets ADD VALUE 'saturn' BEFORE 'uranus'; -ALTER TYPE planets ADD VALUE 'jupiter' AFTER 'mars'; -ALTER TYPE planets ADD VALUE 'neptune' AFTER 'uranus'; - -SELECT enumlabel, enumsortorder -FROM pg_enum -WHERE enumtypid = 'planets'::regtype -ORDER BY 2; - -SELECT enumlabel, enumsortorder -FROM pg_enum -WHERE enumtypid = 'planets'::regtype -ORDER BY enumlabel::planets; - --- errors for adding labels -ALTER TYPE planets ADD VALUE - 'plutoplutoplutoplutoplutoplutoplutoplutoplutoplutoplutoplutoplutopluto'; - -ALTER TYPE planets ADD VALUE 'pluto' AFTER 'zeus'; - --- if not exists tests - --- existing value gives error -ALTER TYPE planets ADD VALUE 'mercury'; - --- unless IF NOT EXISTS is specified -ALTER TYPE planets ADD VALUE IF NOT EXISTS 'mercury'; - --- should be neptune, not mercury -SELECT enum_last(NULL::planets); - -ALTER TYPE planets ADD VALUE IF NOT EXISTS 'pluto'; - --- should be pluto, i.e. the new value -SELECT enum_last(NULL::planets); - --- --- Test inserting so many values that we have to renumber --- - -create type insenum as enum ('L1', 'L2'); - -alter type insenum add value 'i1' before 'L2'; -alter type insenum add value 'i2' before 'L2'; -alter type insenum add value 'i3' before 'L2'; -alter type insenum add value 'i4' before 'L2'; -alter type insenum add value 'i5' before 'L2'; -alter type insenum add value 'i6' before 'L2'; -alter type insenum add value 'i7' before 'L2'; -alter type insenum add value 'i8' before 'L2'; -alter type insenum add value 'i9' before 'L2'; -alter type insenum add value 'i10' before 'L2'; -alter type insenum add value 'i11' before 'L2'; -alter type insenum add value 'i12' before 'L2'; -alter type insenum add value 'i13' before 'L2'; -alter type insenum add value 'i14' before 'L2'; -alter type insenum add value 'i15' before 'L2'; -alter type insenum add value 'i16' before 'L2'; -alter type insenum add value 'i17' before 'L2'; -alter type insenum add value 'i18' before 'L2'; -alter type insenum add value 'i19' before 'L2'; -alter type insenum add value 'i20' before 'L2'; -alter type insenum add value 'i21' before 'L2'; -alter type insenum add value 'i22' before 'L2'; -alter type insenum add value 'i23' before 'L2'; -alter type insenum add value 'i24' before 'L2'; -alter type insenum add value 'i25' before 'L2'; -alter type insenum add value 'i26' before 'L2'; -alter type insenum add value 'i27' before 'L2'; -alter type insenum add value 'i28' before 'L2'; -alter type insenum add value 'i29' before 'L2'; -alter type insenum add value 'i30' before 'L2'; - --- The exact values of enumsortorder will now depend on the local properties --- of float4, but in any reasonable implementation we should get at least --- 20 splits before having to renumber; so only hide values > 20. - -SELECT enumlabel, - case when enumsortorder > 20 then null else enumsortorder end as so -FROM pg_enum -WHERE enumtypid = 'insenum'::regtype -ORDER BY enumsortorder; - --- --- Basic table creation, row selection --- -CREATE TABLE enumtest (col rainbow); -INSERT INTO enumtest values ('red'), ('orange'), ('yellow'), ('green'); -COPY enumtest FROM stdin; -blue -purple -\. -SELECT * FROM enumtest; - --- --- Operators, no index --- -SELECT * FROM enumtest WHERE col = 'orange'; -SELECT * FROM enumtest WHERE col <> 'orange' ORDER BY col; -SELECT * FROM enumtest WHERE col > 'yellow' ORDER BY col; -SELECT * FROM enumtest WHERE col >= 'yellow' ORDER BY col; -SELECT * FROM enumtest WHERE col < 'green' ORDER BY col; -SELECT * FROM enumtest WHERE col <= 'green' ORDER BY col; - --- --- Cast to/from text --- -SELECT 'red'::rainbow::text || 'hithere'; -SELECT 'red'::text::rainbow = 'red'::rainbow; - --- --- Aggregates --- -SELECT min(col) FROM enumtest; -SELECT max(col) FROM enumtest; -SELECT max(col) FROM enumtest WHERE col < 'green'; - --- --- Index tests, force use of index --- -SET enable_seqscan = off; -SET enable_bitmapscan = off; - --- --- Btree index / opclass with the various operators --- -CREATE UNIQUE INDEX enumtest_btree ON enumtest USING btree (col); -SELECT * FROM enumtest WHERE col = 'orange'; -SELECT * FROM enumtest WHERE col <> 'orange' ORDER BY col; -SELECT * FROM enumtest WHERE col > 'yellow' ORDER BY col; -SELECT * FROM enumtest WHERE col >= 'yellow' ORDER BY col; -SELECT * FROM enumtest WHERE col < 'green' ORDER BY col; -SELECT * FROM enumtest WHERE col <= 'green' ORDER BY col; -SELECT min(col) FROM enumtest; -SELECT max(col) FROM enumtest; -SELECT max(col) FROM enumtest WHERE col < 'green'; -DROP INDEX enumtest_btree; - --- --- Hash index / opclass with the = operator --- -CREATE INDEX enumtest_hash ON enumtest USING hash (col); -SELECT * FROM enumtest WHERE col = 'orange'; -DROP INDEX enumtest_hash; - --- --- End index tests --- -RESET enable_seqscan; -RESET enable_bitmapscan; - --- --- Domains over enums --- -CREATE DOMAIN rgb AS rainbow CHECK (VALUE IN ('red', 'green', 'blue')); -SELECT 'red'::rgb; -SELECT 'purple'::rgb; -SELECT 'purple'::rainbow::rgb; -DROP DOMAIN rgb; - --- --- Arrays --- -SELECT '{red,green,blue}'::rainbow[]; -SELECT ('{red,green,blue}'::rainbow[])[2]; -SELECT 'red' = ANY ('{red,green,blue}'::rainbow[]); -SELECT 'yellow' = ANY ('{red,green,blue}'::rainbow[]); -SELECT 'red' = ALL ('{red,green,blue}'::rainbow[]); -SELECT 'red' = ALL ('{red,red}'::rainbow[]); - --- --- Support functions --- -SELECT enum_first(NULL::rainbow); -SELECT enum_last('green'::rainbow); -SELECT enum_range(NULL::rainbow); -SELECT enum_range('orange'::rainbow, 'green'::rainbow); -SELECT enum_range(NULL, 'green'::rainbow); -SELECT enum_range('orange'::rainbow, NULL); -SELECT enum_range(NULL::rainbow, NULL); - --- --- User functions, can't test perl/python etc here since may not be compiled. --- -CREATE FUNCTION echo_me(anyenum) RETURNS text AS $$ -BEGIN -RETURN $1::text || 'omg'; -END -$$ LANGUAGE plpgsql; -SELECT echo_me('red'::rainbow); --- --- Concrete function should override generic one --- -CREATE FUNCTION echo_me(rainbow) RETURNS text AS $$ -BEGIN -RETURN $1::text || 'wtf'; -END -$$ LANGUAGE plpgsql; -SELECT echo_me('red'::rainbow); --- --- If we drop the original generic one, we don't have to qualify the type --- anymore, since there's only one match --- -DROP FUNCTION echo_me(anyenum); -SELECT echo_me('red'); -DROP FUNCTION echo_me(rainbow); - --- --- RI triggers on enum types --- -CREATE TABLE enumtest_parent (id rainbow PRIMARY KEY); -CREATE TABLE enumtest_child (parent rainbow REFERENCES enumtest_parent); -INSERT INTO enumtest_parent VALUES ('red'); -INSERT INTO enumtest_child VALUES ('red'); -INSERT INTO enumtest_child VALUES ('blue'); -- fail -DELETE FROM enumtest_parent; -- fail --- --- cross-type RI should fail --- -CREATE TYPE bogus AS ENUM('good', 'bad', 'ugly'); -CREATE TABLE enumtest_bogus_child(parent bogus REFERENCES enumtest_parent); -DROP TYPE bogus; - --- check renaming a value -ALTER TYPE rainbow RENAME VALUE 'red' TO 'crimson'; -SELECT enumlabel, enumsortorder -FROM pg_enum -WHERE enumtypid = 'rainbow'::regtype -ORDER BY 2; --- check that renaming a non-existent value fails -ALTER TYPE rainbow RENAME VALUE 'red' TO 'crimson'; --- check that renaming to an existent value fails -ALTER TYPE rainbow RENAME VALUE 'blue' TO 'green'; - --- --- check transactional behaviour of ALTER TYPE ... ADD VALUE --- -CREATE TYPE bogus AS ENUM('good'); - --- check that we can add new values to existing enums in a transaction --- but we can't use them -BEGIN; -ALTER TYPE bogus ADD VALUE 'new'; -SAVEPOINT x; -SELECT 'new'::bogus; -- unsafe -ROLLBACK TO x; -SELECT enum_first(null::bogus); -- safe -SELECT enum_last(null::bogus); -- unsafe -ROLLBACK TO x; -SELECT enum_range(null::bogus); -- unsafe -ROLLBACK TO x; -COMMIT; -SELECT 'new'::bogus; -- now safe -SELECT enumlabel, enumsortorder -FROM pg_enum -WHERE enumtypid = 'bogus'::regtype -ORDER BY 2; - --- check that we recognize the case where the enum already existed but was --- modified in the current txn; this should not be considered safe -BEGIN; -ALTER TYPE bogus RENAME TO bogon; -ALTER TYPE bogon ADD VALUE 'bad'; -SELECT 'bad'::bogon; -ROLLBACK; - --- but a renamed value is safe to use later in same transaction -BEGIN; -ALTER TYPE bogus RENAME VALUE 'good' to 'bad'; -SELECT 'bad'::bogus; -ROLLBACK; - -DROP TYPE bogus; - --- check that values created during CREATE TYPE can be used in any case -BEGIN; -CREATE TYPE bogus AS ENUM('good','bad','ugly'); -ALTER TYPE bogus RENAME TO bogon; -select enum_range(null::bogon); -ROLLBACK; - --- ideally, we'd allow this usage; but it requires keeping track of whether --- the enum type was created in the current transaction, which is expensive -BEGIN; -CREATE TYPE bogus AS ENUM('good'); -ALTER TYPE bogus RENAME TO bogon; -ALTER TYPE bogon ADD VALUE 'bad'; -ALTER TYPE bogon ADD VALUE 'ugly'; -select enum_range(null::bogon); -- fails -ROLLBACK; - --- --- Cleanup --- -DROP TABLE enumtest_child; -DROP TABLE enumtest_parent; -DROP TABLE enumtest; -DROP TYPE rainbow; - --- --- Verify properly cleaned up --- -SELECT COUNT(*) FROM pg_type WHERE typname = 'rainbow'; -SELECT * FROM pg_enum WHERE NOT EXISTS - (SELECT 1 FROM pg_type WHERE pg_type.oid = enumtypid); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fevent_trigger.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fevent_trigger.sql deleted file mode 100644 index 5e45e3f190..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fevent_trigger.sql +++ /dev/null @@ -1,468 +0,0 @@ --- should fail, return type mismatch -create event trigger regress_event_trigger - on ddl_command_start - execute procedure pg_backend_pid(); - --- OK -create function test_event_trigger() returns event_trigger as $$ -BEGIN - RAISE NOTICE 'test_event_trigger: % %', tg_event, tg_tag; -END -$$ language plpgsql; - --- should fail, can't call it as a plain function -SELECT test_event_trigger(); - --- should fail, event triggers cannot have declared arguments -create function test_event_trigger_arg(name text) -returns event_trigger as $$ BEGIN RETURN 1; END $$ language plpgsql; - --- should fail, SQL functions cannot be event triggers -create function test_event_trigger_sql() returns event_trigger as $$ -SELECT 1 $$ language sql; - --- should fail, no elephant_bootstrap entry point -create event trigger regress_event_trigger on elephant_bootstrap - execute procedure test_event_trigger(); - --- OK -create event trigger regress_event_trigger on ddl_command_start - execute procedure test_event_trigger(); - --- OK -create event trigger regress_event_trigger_end on ddl_command_end - execute function test_event_trigger(); - --- should fail, food is not a valid filter variable -create event trigger regress_event_trigger2 on ddl_command_start - when food in ('sandwich') - execute procedure test_event_trigger(); - --- should fail, sandwich is not a valid command tag -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('sandwich') - execute procedure test_event_trigger(); - --- should fail, create skunkcabbage is not a valid command tag -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('create table', 'create skunkcabbage') - execute procedure test_event_trigger(); - --- should fail, can't have event triggers on event triggers -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('DROP EVENT TRIGGER') - execute procedure test_event_trigger(); - --- should fail, can't have event triggers on global objects -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('CREATE ROLE') - execute procedure test_event_trigger(); - --- should fail, can't have event triggers on global objects -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('CREATE DATABASE') - execute procedure test_event_trigger(); - --- should fail, can't have event triggers on global objects -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('CREATE TABLESPACE') - execute procedure test_event_trigger(); - --- should fail, can't have same filter variable twice -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('create table') and tag in ('CREATE FUNCTION') - execute procedure test_event_trigger(); - --- should fail, can't have arguments -create event trigger regress_event_trigger2 on ddl_command_start - execute procedure test_event_trigger('argument not allowed'); - --- OK -create event trigger regress_event_trigger2 on ddl_command_start - when tag in ('create table', 'CREATE FUNCTION') - execute procedure test_event_trigger(); - --- OK -comment on event trigger regress_event_trigger is 'test comment'; - --- drop as non-superuser should fail -create role regress_evt_user; -set role regress_evt_user; -create event trigger regress_event_trigger_noperms on ddl_command_start - execute procedure test_event_trigger(); -reset role; - --- test enabling and disabling -alter event trigger regress_event_trigger disable; --- fires _trigger2 and _trigger_end should fire, but not _trigger -create table event_trigger_fire1 (a int); -alter event trigger regress_event_trigger enable; -set session_replication_role = replica; --- fires nothing -create table event_trigger_fire2 (a int); -alter event trigger regress_event_trigger enable replica; --- fires only _trigger -create table event_trigger_fire3 (a int); -alter event trigger regress_event_trigger enable always; --- fires only _trigger -create table event_trigger_fire4 (a int); -reset session_replication_role; --- fires all three -create table event_trigger_fire5 (a int); --- non-top-level command -create function f1() returns int -language plpgsql -as $$ -begin - create table event_trigger_fire6 (a int); - return 0; -end $$; -select f1(); --- non-top-level command -create procedure p1() -language plpgsql -as $$ -begin - create table event_trigger_fire7 (a int); -end $$; -call p1(); - --- clean up -alter event trigger regress_event_trigger disable; -drop table event_trigger_fire2, event_trigger_fire3, event_trigger_fire4, event_trigger_fire5, event_trigger_fire6, event_trigger_fire7; -drop routine f1(), p1(); - --- regress_event_trigger_end should fire on these commands -grant all on table event_trigger_fire1 to public; -comment on table event_trigger_fire1 is 'here is a comment'; -revoke all on table event_trigger_fire1 from public; -drop table event_trigger_fire1; -create foreign data wrapper useless; -create server useless_server foreign data wrapper useless; -create user mapping for regress_evt_user server useless_server; -alter default privileges for role regress_evt_user - revoke delete on tables from regress_evt_user; - --- alter owner to non-superuser should fail -alter event trigger regress_event_trigger owner to regress_evt_user; - --- alter owner to superuser should work -alter role regress_evt_user superuser; -alter event trigger regress_event_trigger owner to regress_evt_user; - --- should fail, name collision -alter event trigger regress_event_trigger rename to regress_event_trigger2; - --- OK -alter event trigger regress_event_trigger rename to regress_event_trigger3; - --- should fail, doesn't exist any more -drop event trigger regress_event_trigger; - --- should fail, regress_evt_user owns some objects -drop role regress_evt_user; - --- cleanup before next test --- these are all OK; the second one should emit a NOTICE -drop event trigger if exists regress_event_trigger2; -drop event trigger if exists regress_event_trigger2; -drop event trigger regress_event_trigger3; -drop event trigger regress_event_trigger_end; - --- test support for dropped objects -CREATE SCHEMA schema_one authorization regress_evt_user; -CREATE SCHEMA schema_two authorization regress_evt_user; -CREATE SCHEMA audit_tbls authorization regress_evt_user; -CREATE TEMP TABLE a_temp_tbl (); -SET SESSION AUTHORIZATION regress_evt_user; - -CREATE TABLE schema_one.table_one(a int); -CREATE TABLE schema_one."table two"(a int); -CREATE TABLE schema_one.table_three(a int); -CREATE TABLE audit_tbls.schema_one_table_two(the_value text); - -CREATE TABLE schema_two.table_two(a int); -CREATE TABLE schema_two.table_three(a int, b text); -CREATE TABLE audit_tbls.schema_two_table_three(the_value text); - -CREATE OR REPLACE FUNCTION schema_two.add(int, int) RETURNS int LANGUAGE plpgsql - CALLED ON NULL INPUT - AS $$ BEGIN RETURN coalesce($1,0) + coalesce($2,0); END; $$; -CREATE AGGREGATE schema_two.newton - (BASETYPE = int, SFUNC = schema_two.add, STYPE = int); - -RESET SESSION AUTHORIZATION; - -CREATE TABLE undroppable_objs ( - object_type text, - object_identity text -); -INSERT INTO undroppable_objs VALUES -('table', 'schema_one.table_three'), -('table', 'audit_tbls.schema_two_table_three'); - -CREATE TABLE dropped_objects ( - type text, - schema text, - object text -); - --- This tests errors raised within event triggers; the one in audit_tbls --- uses 2nd-level recursive invocation via test_evtrig_dropped_objects(). -CREATE OR REPLACE FUNCTION undroppable() RETURNS event_trigger -LANGUAGE plpgsql AS $$ -DECLARE - obj record; -BEGIN - PERFORM 1 FROM pg_tables WHERE tablename = 'undroppable_objs'; - IF NOT FOUND THEN - RAISE NOTICE 'table undroppable_objs not found, skipping'; - RETURN; - END IF; - FOR obj IN - SELECT * FROM pg_event_trigger_dropped_objects() JOIN - undroppable_objs USING (object_type, object_identity) - LOOP - RAISE EXCEPTION 'object % of type % cannot be dropped', - obj.object_identity, obj.object_type; - END LOOP; -END; -$$; - -CREATE EVENT TRIGGER undroppable ON sql_drop - EXECUTE PROCEDURE undroppable(); - -CREATE OR REPLACE FUNCTION test_evtrig_dropped_objects() RETURNS event_trigger -LANGUAGE plpgsql AS $$ -DECLARE - obj record; -BEGIN - FOR obj IN SELECT * FROM pg_event_trigger_dropped_objects() - LOOP - IF obj.object_type = 'table' THEN - EXECUTE format('DROP TABLE IF EXISTS audit_tbls.%I', - format('%s_%s', obj.schema_name, obj.object_name)); - END IF; - - INSERT INTO dropped_objects - (type, schema, object) VALUES - (obj.object_type, obj.schema_name, obj.object_identity); - END LOOP; -END -$$; - -CREATE EVENT TRIGGER regress_event_trigger_drop_objects ON sql_drop - WHEN TAG IN ('drop table', 'drop function', 'drop view', - 'drop owned', 'drop schema', 'alter table') - EXECUTE PROCEDURE test_evtrig_dropped_objects(); - -ALTER TABLE schema_one.table_one DROP COLUMN a; -DROP SCHEMA schema_one, schema_two CASCADE; -DELETE FROM undroppable_objs WHERE object_identity = 'audit_tbls.schema_two_table_three'; -DROP SCHEMA schema_one, schema_two CASCADE; -DELETE FROM undroppable_objs WHERE object_identity = 'schema_one.table_three'; -DROP SCHEMA schema_one, schema_two CASCADE; - -SELECT * FROM dropped_objects WHERE schema IS NULL OR schema <> 'pg_toast'; - -DROP OWNED BY regress_evt_user; -SELECT * FROM dropped_objects WHERE type = 'schema'; - -DROP ROLE regress_evt_user; - -DROP EVENT TRIGGER regress_event_trigger_drop_objects; -DROP EVENT TRIGGER undroppable; - --- Event triggers on relations. -CREATE OR REPLACE FUNCTION event_trigger_report_dropped() - RETURNS event_trigger - LANGUAGE plpgsql -AS $$ -DECLARE r record; -BEGIN - FOR r IN SELECT * from pg_event_trigger_dropped_objects() - LOOP - IF NOT r.normal AND NOT r.original THEN - CONTINUE; - END IF; - RAISE NOTICE 'NORMAL: orig=% normal=% istemp=% type=% identity=% name=% args=%', - r.original, r.normal, r.is_temporary, r.object_type, - r.object_identity, r.address_names, r.address_args; - END LOOP; -END; $$; -CREATE EVENT TRIGGER regress_event_trigger_report_dropped ON sql_drop - EXECUTE PROCEDURE event_trigger_report_dropped(); -CREATE OR REPLACE FUNCTION event_trigger_report_end() - RETURNS event_trigger - LANGUAGE plpgsql -AS $$ -DECLARE r RECORD; -BEGIN - FOR r IN SELECT * FROM pg_event_trigger_ddl_commands() - LOOP - RAISE NOTICE 'END: command_tag=% type=% identity=%', - r.command_tag, r.object_type, r.object_identity; - END LOOP; -END; $$; -CREATE EVENT TRIGGER regress_event_trigger_report_end ON ddl_command_end - EXECUTE PROCEDURE event_trigger_report_end(); - -CREATE SCHEMA evttrig - CREATE TABLE one (col_a SERIAL PRIMARY KEY, col_b text DEFAULT 'forty two', col_c SERIAL) - CREATE INDEX one_idx ON one (col_b) - CREATE TABLE two (col_c INTEGER CHECK (col_c > 0) REFERENCES one DEFAULT 42) - CREATE TABLE id (col_d int NOT NULL GENERATED ALWAYS AS IDENTITY); - --- Partitioned tables with a partitioned index -CREATE TABLE evttrig.parted ( - id int PRIMARY KEY) - PARTITION BY RANGE (id); -CREATE TABLE evttrig.part_1_10 PARTITION OF evttrig.parted (id) - FOR VALUES FROM (1) TO (10); -CREATE TABLE evttrig.part_10_20 PARTITION OF evttrig.parted (id) - FOR VALUES FROM (10) TO (20) PARTITION BY RANGE (id); -CREATE TABLE evttrig.part_10_15 PARTITION OF evttrig.part_10_20 (id) - FOR VALUES FROM (10) TO (15); -CREATE TABLE evttrig.part_15_20 PARTITION OF evttrig.part_10_20 (id) - FOR VALUES FROM (15) TO (20); - -ALTER TABLE evttrig.two DROP COLUMN col_c; -ALTER TABLE evttrig.one ALTER COLUMN col_b DROP DEFAULT; -ALTER TABLE evttrig.one DROP CONSTRAINT one_pkey; -ALTER TABLE evttrig.one DROP COLUMN col_c; -ALTER TABLE evttrig.id ALTER COLUMN col_d SET DATA TYPE bigint; -ALTER TABLE evttrig.id ALTER COLUMN col_d DROP IDENTITY, - ALTER COLUMN col_d SET DATA TYPE int; -DROP INDEX evttrig.one_idx; -DROP SCHEMA evttrig CASCADE; -DROP TABLE a_temp_tbl; - --- CREATE OPERATOR CLASS without FAMILY clause should report --- both CREATE OPERATOR FAMILY and CREATE OPERATOR CLASS -CREATE OPERATOR CLASS evttrigopclass FOR TYPE int USING btree AS STORAGE int; - -DROP EVENT TRIGGER regress_event_trigger_report_dropped; -DROP EVENT TRIGGER regress_event_trigger_report_end; - --- only allowed from within an event trigger function, should fail -select pg_event_trigger_table_rewrite_oid(); - --- test Table Rewrite Event Trigger -CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger -LANGUAGE plpgsql AS $$ -BEGIN - RAISE EXCEPTION 'rewrites not allowed'; -END; -$$; - -create event trigger no_rewrite_allowed on table_rewrite - execute procedure test_evtrig_no_rewrite(); - -create table rewriteme (id serial primary key, foo float, bar timestamptz); -insert into rewriteme - select x * 1.001 from generate_series(1, 500) as t(x); -alter table rewriteme alter column foo type numeric; -alter table rewriteme add column baz int default 0; - --- test with more than one reason to rewrite a single table -CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger -LANGUAGE plpgsql AS $$ -BEGIN - RAISE NOTICE 'Table ''%'' is being rewritten (reason = %)', - pg_event_trigger_table_rewrite_oid()::regclass, - pg_event_trigger_table_rewrite_reason(); -END; -$$; - -alter table rewriteme - add column onemore int default 0, - add column another int default -1, - alter column foo type numeric(10,4); - --- shouldn't trigger a table_rewrite event -alter table rewriteme alter column foo type numeric(12,4); -begin; -set timezone to 'UTC'; -alter table rewriteme alter column bar type timestamp; -set timezone to '0'; -alter table rewriteme alter column bar type timestamptz; -set timezone to 'Europe/London'; -alter table rewriteme alter column bar type timestamp; -- does rewrite -rollback; - --- typed tables are rewritten when their type changes. Don't emit table --- name, because firing order is not stable. -CREATE OR REPLACE FUNCTION test_evtrig_no_rewrite() RETURNS event_trigger -LANGUAGE plpgsql AS $$ -BEGIN - RAISE NOTICE 'Table is being rewritten (reason = %)', - pg_event_trigger_table_rewrite_reason(); -END; -$$; - -create type rewritetype as (a int); -create table rewritemetoo1 of rewritetype; -create table rewritemetoo2 of rewritetype; -alter type rewritetype alter attribute a type text cascade; - --- but this doesn't work -create table rewritemetoo3 (a rewritetype); -alter type rewritetype alter attribute a type varchar cascade; - -drop table rewriteme; -drop event trigger no_rewrite_allowed; -drop function test_evtrig_no_rewrite(); - --- test Row Security Event Trigger -RESET SESSION AUTHORIZATION; -CREATE TABLE event_trigger_test (a integer, b text); - -CREATE OR REPLACE FUNCTION start_command() -RETURNS event_trigger AS $$ -BEGIN -RAISE NOTICE '% - ddl_command_start', tg_tag; -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION end_command() -RETURNS event_trigger AS $$ -BEGIN -RAISE NOTICE '% - ddl_command_end', tg_tag; -END; -$$ LANGUAGE plpgsql; - -CREATE OR REPLACE FUNCTION drop_sql_command() -RETURNS event_trigger AS $$ -BEGIN -RAISE NOTICE '% - sql_drop', tg_tag; -END; -$$ LANGUAGE plpgsql; - -CREATE EVENT TRIGGER start_rls_command ON ddl_command_start - WHEN TAG IN ('CREATE POLICY', 'ALTER POLICY', 'DROP POLICY') EXECUTE PROCEDURE start_command(); - -CREATE EVENT TRIGGER end_rls_command ON ddl_command_end - WHEN TAG IN ('CREATE POLICY', 'ALTER POLICY', 'DROP POLICY') EXECUTE PROCEDURE end_command(); - -CREATE EVENT TRIGGER sql_drop_command ON sql_drop - WHEN TAG IN ('DROP POLICY') EXECUTE PROCEDURE drop_sql_command(); - -CREATE POLICY p1 ON event_trigger_test USING (FALSE); -ALTER POLICY p1 ON event_trigger_test USING (TRUE); -ALTER POLICY p1 ON event_trigger_test RENAME TO p2; -DROP POLICY p2 ON event_trigger_test; - --- Check the object addresses of all the event triggers. -SELECT - e.evtname, - pg_describe_object('pg_event_trigger'::regclass, e.oid, 0) as descr, - b.type, b.object_names, b.object_args, - pg_identify_object(a.classid, a.objid, a.objsubid) as ident - FROM pg_event_trigger as e, - LATERAL pg_identify_object_as_address('pg_event_trigger'::regclass, e.oid, 0) as b, - LATERAL pg_get_object_address(b.type, b.object_names, b.object_args) as a - ORDER BY e.evtname; - -DROP EVENT TRIGGER start_rls_command; -DROP EVENT TRIGGER end_rls_command; -DROP EVENT TRIGGER sql_drop_command; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fexplain.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fexplain.sql deleted file mode 100644 index ae3f7a308d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fexplain.sql +++ /dev/null @@ -1,130 +0,0 @@ --- --- EXPLAIN --- --- There are many test cases elsewhere that use EXPLAIN as a vehicle for --- checking something else (usually planner behavior). This file is --- concerned with testing EXPLAIN in its own right. --- - --- To produce stable regression test output, it's usually necessary to --- ignore details such as exact costs or row counts. These filter --- functions replace changeable output details with fixed strings. - -create function explain_filter(text) returns setof text -language plpgsql as -$$ -declare - ln text; -begin - for ln in execute $1 - loop - -- Replace any numeric word with just 'N' - ln := regexp_replace(ln, '-?\m\d+\M', 'N', 'g'); - -- In sort output, the above won't match units-suffixed numbers - ln := regexp_replace(ln, '\m\d+kB', 'NkB', 'g'); - -- Ignore text-mode buffers output because it varies depending - -- on the system state - CONTINUE WHEN (ln ~ ' +Buffers: .*'); - -- Ignore text-mode "Planning:" line because whether it's output - -- varies depending on the system state - CONTINUE WHEN (ln = 'Planning:'); - return next ln; - end loop; -end; -$$; - --- To produce valid JSON output, replace numbers with "0" or "0.0" not "N" -create function explain_filter_to_json(text) returns jsonb -language plpgsql as -$$ -declare - data text := ''; - ln text; -begin - for ln in execute $1 - loop - -- Replace any numeric word with just '0' - ln := regexp_replace(ln, '\m\d+\M', '0', 'g'); - data := data || ln; - end loop; - return data::jsonb; -end; -$$; - --- Disable JIT, or we'll get different output on machines where that's been --- forced on -set jit = off; - --- Similarly, disable track_io_timing, to avoid output differences when --- enabled. -set track_io_timing = off; - --- Simple cases - -select explain_filter('explain select * from int8_tbl i8'); -select explain_filter('explain (analyze) select * from int8_tbl i8'); -select explain_filter('explain (analyze, verbose) select * from int8_tbl i8'); -select explain_filter('explain (analyze, buffers, format text) select * from int8_tbl i8'); -select explain_filter('explain (analyze, buffers, format xml) select * from int8_tbl i8'); -select explain_filter('explain (analyze, buffers, format yaml) select * from int8_tbl i8'); -select explain_filter('explain (buffers, format text) select * from int8_tbl i8'); -select explain_filter('explain (buffers, format json) select * from int8_tbl i8'); - --- Check output including I/O timings. These fields are conditional --- but always set in JSON format, so check them only in this case. -set track_io_timing = on; -select explain_filter('explain (analyze, buffers, format json) select * from int8_tbl i8'); -set track_io_timing = off; - --- SETTINGS option --- We have to ignore other settings that might be imposed by the environment, --- so printing the whole Settings field unfortunately won't do. - -begin; -set local plan_cache_mode = force_generic_plan; -select true as "OK" - from explain_filter('explain (settings) select * from int8_tbl i8') ln - where ln ~ '^ *Settings: .*plan_cache_mode = ''force_generic_plan'''; -select explain_filter_to_json('explain (settings, format json) select * from int8_tbl i8') #> '{0,Settings,plan_cache_mode}'; -rollback; - --- --- Test production of per-worker data --- --- Unfortunately, because we don't know how many worker processes we'll --- actually get (maybe none at all), we can't examine the "Workers" output --- in any detail. We can check that it parses correctly as JSON, and then --- remove it from the displayed results. - -begin; --- encourage use of parallel plans -set parallel_setup_cost=0; -set parallel_tuple_cost=0; -set min_parallel_table_scan_size=0; -set max_parallel_workers_per_gather=4; - -select jsonb_pretty( - explain_filter_to_json('explain (analyze, verbose, buffers, format json) - select * from tenk1 order by tenthous') - -- remove "Workers" node of the Seq Scan plan node - #- '{0,Plan,Plans,0,Plans,0,Workers}' - -- remove "Workers" node of the Sort plan node - #- '{0,Plan,Plans,0,Workers}' - -- Also remove its sort-type fields, as those aren't 100% stable - #- '{0,Plan,Plans,0,Sort Method}' - #- '{0,Plan,Plans,0,Sort Space Type}' -); - -rollback; - --- Test display of temporary objects -create temp table t1(f1 float8); - -create function pg_temp.mysin(float8) returns float8 language plpgsql -as 'begin return sin($1); end'; - -select explain_filter('explain (verbose) select * from t1 where pg_temp.mysin(f1) < 0.5'); - --- Test compute_query_id -set compute_query_id = on; -select explain_filter('explain (verbose) select * from int8_tbl i8'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fexpressions.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fexpressions.sql deleted file mode 100644 index 0e163cc0d7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fexpressions.sql +++ /dev/null @@ -1,206 +0,0 @@ --- --- expression evaluation tests that don't fit into a more specific file --- - --- --- Tests for SQLValueFunction --- - - --- current_date (always matches because of transactional behaviour) -SELECT date(now())::text = current_date::text; - - --- current_time / localtime -SELECT now()::timetz::text = current_time::text; -SELECT now()::timetz(4)::text = current_time(4)::text; -SELECT now()::time::text = localtime::text; -SELECT now()::time(3)::text = localtime(3)::text; - --- current_timestamp / localtimestamp (always matches because of transactional behaviour) -SELECT current_timestamp = NOW(); --- precision -SELECT length(current_timestamp::text) >= length(current_timestamp(0)::text); --- localtimestamp -SELECT now()::timestamp::text = localtimestamp::text; - --- current_role/user/user is tested in rolnames.sql - --- current database / catalog -SELECT current_catalog = current_database(); - --- current_schema -SELECT current_schema; -SET search_path = 'notme'; -SELECT current_schema; -SET search_path = 'pg_catalog'; -SELECT current_schema; -RESET search_path; - - --- --- Test parsing of a no-op cast to a type with unspecified typmod --- -begin; - -create table numeric_tbl (f1 numeric(18,3), f2 numeric); - -create view numeric_view as - select - f1, f1::numeric(16,4) as f1164, f1::numeric as f1n, - f2, f2::numeric(16,4) as f2164, f2::numeric as f2n - from numeric_tbl; - -\d+ numeric_view - -explain (verbose, costs off) select * from numeric_view; - --- bpchar, lacking planner support for its length coercion function, --- could behave differently - -create table bpchar_tbl (f1 character(16) unique, f2 bpchar); - -create view bpchar_view as - select - f1, f1::character(14) as f114, f1::bpchar as f1n, - f2, f2::character(14) as f214, f2::bpchar as f2n - from bpchar_tbl; - -\d+ bpchar_view - -explain (verbose, costs off) select * from bpchar_view - where f1::bpchar = 'foo'; - -rollback; - - --- --- Ordinarily, IN/NOT IN can be converted to a ScalarArrayOpExpr --- with a suitably-chosen array type. --- -explain (verbose, costs off) -select random() IN (1, 4, 8.0); -explain (verbose, costs off) -select random()::int IN (1, 4, 8.0); --- However, if there's not a common supertype for the IN elements, --- we should instead try to produce "x = v1 OR x = v2 OR ...". --- In most cases that'll fail for lack of all the requisite = operators, --- but it can succeed sometimes. So this should complain about lack of --- an = operator, not about cast failure. -select '(0,0)'::point in ('(0,0,0,0)'::box, point(0,0)); - - --- --- Tests for ScalarArrayOpExpr with a hashfn --- - --- create a stable function so that the tests below are not --- evaluated using the planner's constant folding. -begin; - -create function return_int_input(int) returns int as $$ -begin - return $1; -end; -$$ language plpgsql stable; - -create function return_text_input(text) returns text as $$ -begin - return $1; -end; -$$ language plpgsql stable; - -select return_int_input(1) in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1); -select return_int_input(1) in (10, 9, 2, 8, 3, 7, 4, 6, 5, null); -select return_int_input(1) in (null, null, null, null, null, null, null, null, null, null, null); -select return_int_input(1) in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1, null); -select return_int_input(null::int) in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1); -select return_int_input(null::int) in (10, 9, 2, 8, 3, 7, 4, 6, 5, null); -select return_text_input('a') in ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); --- NOT IN -select return_int_input(1) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1); -select return_int_input(1) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, 0); -select return_int_input(1) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, 2, null); -select return_int_input(1) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1, null); -select return_int_input(1) not in (null, null, null, null, null, null, null, null, null, null, null); -select return_int_input(null::int) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1); -select return_int_input(null::int) not in (10, 9, 2, 8, 3, 7, 4, 6, 5, null); -select return_text_input('a') not in ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'); - -rollback; - --- Test with non-strict equality function. --- We need to create our own type for this. - -begin; - -create type myint; -create function myintin(cstring) returns myint strict immutable language - internal as 'int4in'; -create function myintout(myint) returns cstring strict immutable language - internal as 'int4out'; -create function myinthash(myint) returns integer strict immutable language - internal as 'hashint4'; - -create type myint (input = myintin, output = myintout, like = int4); - -create cast (int4 as myint) without function; -create cast (myint as int4) without function; - -create function myinteq(myint, myint) returns bool as $$ -begin - if $1 is null and $2 is null then - return true; - else - return $1::int = $2::int; - end if; -end; -$$ language plpgsql immutable; - -create function myintne(myint, myint) returns bool as $$ -begin - return not myinteq($1, $2); -end; -$$ language plpgsql immutable; - -create operator = ( - leftarg = myint, - rightarg = myint, - commutator = =, - negator = <>, - procedure = myinteq, - restrict = eqsel, - join = eqjoinsel, - merges -); - -create operator <> ( - leftarg = myint, - rightarg = myint, - commutator = <>, - negator = =, - procedure = myintne, - restrict = eqsel, - join = eqjoinsel, - merges -); - -create operator class myint_ops -default for type myint using hash as - operator 1 = (myint, myint), - function 1 myinthash(myint); - -create table inttest (a myint); -insert into inttest values(1::myint),(null); - --- try an array with enough elements to cause hashing -select * from inttest where a in (1::myint,2::myint,3::myint,4::myint,5::myint,6::myint,7::myint,8::myint,9::myint, null); -select * from inttest where a not in (1::myint,2::myint,3::myint,4::myint,5::myint,6::myint,7::myint,8::myint,9::myint, null); -select * from inttest where a not in (0::myint,2::myint,3::myint,4::myint,5::myint,6::myint,7::myint,8::myint,9::myint, null); --- ensure the result matched with the non-hashed version. We simply remove --- some array elements so that we don't reach the hashing threshold. -select * from inttest where a in (1::myint,2::myint,3::myint,4::myint,5::myint, null); -select * from inttest where a not in (1::myint,2::myint,3::myint,4::myint,5::myint, null); -select * from inttest where a not in (0::myint,2::myint,3::myint,4::myint,5::myint, null); - -rollback; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ffast_default.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ffast_default.sql deleted file mode 100644 index 16a3b7ca51..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ffast_default.sql +++ /dev/null @@ -1,562 +0,0 @@ --- --- ALTER TABLE ADD COLUMN DEFAULT test --- - -SET search_path = fast_default; -CREATE SCHEMA fast_default; -CREATE TABLE m(id OID); -INSERT INTO m VALUES (NULL::OID); - -CREATE FUNCTION set(tabname name) RETURNS VOID -AS $$ -BEGIN - UPDATE m - SET id = (SELECT c.relfilenode - FROM pg_class AS c, pg_namespace AS s - WHERE c.relname = tabname - AND c.relnamespace = s.oid - AND s.nspname = 'fast_default'); -END; -$$ LANGUAGE 'plpgsql'; - -CREATE FUNCTION comp() RETURNS TEXT -AS $$ -BEGIN - RETURN (SELECT CASE - WHEN m.id = c.relfilenode THEN 'Unchanged' - ELSE 'Rewritten' - END - FROM m, pg_class AS c, pg_namespace AS s - WHERE c.relname = 't' - AND c.relnamespace = s.oid - AND s.nspname = 'fast_default'); -END; -$$ LANGUAGE 'plpgsql'; - -CREATE FUNCTION log_rewrite() RETURNS event_trigger -LANGUAGE plpgsql as -$func$ - -declare - this_schema text; -begin - select into this_schema relnamespace::regnamespace::text - from pg_class - where oid = pg_event_trigger_table_rewrite_oid(); - if this_schema = 'fast_default' - then - RAISE NOTICE 'rewriting table % for reason %', - pg_event_trigger_table_rewrite_oid()::regclass, - pg_event_trigger_table_rewrite_reason(); - end if; -end; -$func$; - -CREATE TABLE has_volatile AS -SELECT * FROM generate_series(1,10) id; - - -CREATE EVENT TRIGGER has_volatile_rewrite - ON table_rewrite - EXECUTE PROCEDURE log_rewrite(); - --- only the last of these should trigger a rewrite -ALTER TABLE has_volatile ADD col1 int; -ALTER TABLE has_volatile ADD col2 int DEFAULT 1; -ALTER TABLE has_volatile ADD col3 timestamptz DEFAULT current_timestamp; -ALTER TABLE has_volatile ADD col4 int DEFAULT (random() * 10000)::int; - - - --- Test a large sample of different datatypes -CREATE TABLE T(pk INT NOT NULL PRIMARY KEY, c_int INT DEFAULT 1); - -SELECT set('t'); - -INSERT INTO T VALUES (1), (2); - -ALTER TABLE T ADD COLUMN c_bpchar BPCHAR(5) DEFAULT 'hello', - ALTER COLUMN c_int SET DEFAULT 2; - -INSERT INTO T VALUES (3), (4); - - -ALTER TABLE T ADD COLUMN c_text TEXT DEFAULT 'world', - ALTER COLUMN c_bpchar SET DEFAULT 'dog'; - -INSERT INTO T VALUES (5), (6); - -ALTER TABLE T ADD COLUMN c_date DATE DEFAULT '2016-06-02', - ALTER COLUMN c_text SET DEFAULT 'cat'; - -INSERT INTO T VALUES (7), (8); - -ALTER TABLE T ADD COLUMN c_timestamp TIMESTAMP DEFAULT '2016-09-01 12:00:00', - ADD COLUMN c_timestamp_null TIMESTAMP, - ALTER COLUMN c_date SET DEFAULT '2010-01-01'; - -INSERT INTO T VALUES (9), (10); - -ALTER TABLE T ADD COLUMN c_array TEXT[] - DEFAULT '{"This", "is", "the", "real", "world"}', - ALTER COLUMN c_timestamp SET DEFAULT '1970-12-31 11:12:13', - ALTER COLUMN c_timestamp_null SET DEFAULT '2016-09-29 12:00:00'; - -INSERT INTO T VALUES (11), (12); - -ALTER TABLE T ADD COLUMN c_small SMALLINT DEFAULT -5, - ADD COLUMN c_small_null SMALLINT, - ALTER COLUMN c_array - SET DEFAULT '{"This", "is", "no", "fantasy"}'; - -INSERT INTO T VALUES (13), (14); - -ALTER TABLE T ADD COLUMN c_big BIGINT DEFAULT 180000000000018, - ALTER COLUMN c_small SET DEFAULT 9, - ALTER COLUMN c_small_null SET DEFAULT 13; - -INSERT INTO T VALUES (15), (16); - -ALTER TABLE T ADD COLUMN c_num NUMERIC DEFAULT 1.00000000001, - ALTER COLUMN c_big SET DEFAULT -9999999999999999; - -INSERT INTO T VALUES (17), (18); - -ALTER TABLE T ADD COLUMN c_time TIME DEFAULT '12:00:00', - ALTER COLUMN c_num SET DEFAULT 2.000000000000002; - -INSERT INTO T VALUES (19), (20); - -ALTER TABLE T ADD COLUMN c_interval INTERVAL DEFAULT '1 day', - ALTER COLUMN c_time SET DEFAULT '23:59:59'; - -INSERT INTO T VALUES (21), (22); - -ALTER TABLE T ADD COLUMN c_hugetext TEXT DEFAULT repeat('abcdefg',1000), - ALTER COLUMN c_interval SET DEFAULT '3 hours'; - -INSERT INTO T VALUES (23), (24); - -ALTER TABLE T ALTER COLUMN c_interval DROP DEFAULT, - ALTER COLUMN c_hugetext SET DEFAULT repeat('poiuyt', 1000); - -INSERT INTO T VALUES (25), (26); - -ALTER TABLE T ALTER COLUMN c_bpchar DROP DEFAULT, - ALTER COLUMN c_date DROP DEFAULT, - ALTER COLUMN c_text DROP DEFAULT, - ALTER COLUMN c_timestamp DROP DEFAULT, - ALTER COLUMN c_array DROP DEFAULT, - ALTER COLUMN c_small DROP DEFAULT, - ALTER COLUMN c_big DROP DEFAULT, - ALTER COLUMN c_num DROP DEFAULT, - ALTER COLUMN c_time DROP DEFAULT, - ALTER COLUMN c_hugetext DROP DEFAULT; - -INSERT INTO T VALUES (27), (28); - -SELECT pk, c_int, c_bpchar, c_text, c_date, c_timestamp, - c_timestamp_null, c_array, c_small, c_small_null, - c_big, c_num, c_time, c_interval, - c_hugetext = repeat('abcdefg',1000) as c_hugetext_origdef, - c_hugetext = repeat('poiuyt', 1000) as c_hugetext_newdef -FROM T ORDER BY pk; - -SELECT comp(); - -DROP TABLE T; - --- Test expressions in the defaults -CREATE OR REPLACE FUNCTION foo(a INT) RETURNS TEXT AS $$ -DECLARE res TEXT := ''; - i INT; -BEGIN - i := 0; - WHILE (i < a) LOOP - res := res || chr(ascii('a') + i); - i := i + 1; - END LOOP; - RETURN res; -END; $$ LANGUAGE PLPGSQL STABLE; - -CREATE TABLE T(pk INT NOT NULL PRIMARY KEY, c_int INT DEFAULT LENGTH(foo(6))); - -SELECT set('t'); - -INSERT INTO T VALUES (1), (2); - -ALTER TABLE T ADD COLUMN c_bpchar BPCHAR(5) DEFAULT foo(4), - ALTER COLUMN c_int SET DEFAULT LENGTH(foo(8)); - -INSERT INTO T VALUES (3), (4); - -ALTER TABLE T ADD COLUMN c_text TEXT DEFAULT foo(6), - ALTER COLUMN c_bpchar SET DEFAULT foo(3); - -INSERT INTO T VALUES (5), (6); - -ALTER TABLE T ADD COLUMN c_date DATE - DEFAULT '2016-06-02'::DATE + LENGTH(foo(10)), - ALTER COLUMN c_text SET DEFAULT foo(12); - -INSERT INTO T VALUES (7), (8); - -ALTER TABLE T ADD COLUMN c_timestamp TIMESTAMP - DEFAULT '2016-09-01'::DATE + LENGTH(foo(10)), - ALTER COLUMN c_date - SET DEFAULT '2010-01-01'::DATE - LENGTH(foo(4)); - -INSERT INTO T VALUES (9), (10); - -ALTER TABLE T ADD COLUMN c_array TEXT[] - DEFAULT ('{"This", "is", "' || foo(4) || - '","the", "real", "world"}')::TEXT[], - ALTER COLUMN c_timestamp - SET DEFAULT '1970-12-31'::DATE + LENGTH(foo(30)); - -INSERT INTO T VALUES (11), (12); - -ALTER TABLE T ALTER COLUMN c_int DROP DEFAULT, - ALTER COLUMN c_array - SET DEFAULT ('{"This", "is", "' || foo(1) || - '", "fantasy"}')::text[]; - -INSERT INTO T VALUES (13), (14); - -ALTER TABLE T ALTER COLUMN c_bpchar DROP DEFAULT, - ALTER COLUMN c_date DROP DEFAULT, - ALTER COLUMN c_text DROP DEFAULT, - ALTER COLUMN c_timestamp DROP DEFAULT, - ALTER COLUMN c_array DROP DEFAULT; - -INSERT INTO T VALUES (15), (16); - -SELECT * FROM T; - -SELECT comp(); - -DROP TABLE T; - -DROP FUNCTION foo(INT); - --- Fall back to full rewrite for volatile expressions -CREATE TABLE T(pk INT NOT NULL PRIMARY KEY); - -INSERT INTO T VALUES (1); - -SELECT set('t'); - --- now() is stable, because it returns the transaction timestamp -ALTER TABLE T ADD COLUMN c1 TIMESTAMP DEFAULT now(); - -SELECT comp(); - --- clock_timestamp() is volatile -ALTER TABLE T ADD COLUMN c2 TIMESTAMP DEFAULT clock_timestamp(); - -SELECT comp(); - -DROP TABLE T; - --- Simple querie -CREATE TABLE T (pk INT NOT NULL PRIMARY KEY); - -SELECT set('t'); - -INSERT INTO T SELECT * FROM generate_series(1, 10) a; - -ALTER TABLE T ADD COLUMN c_bigint BIGINT NOT NULL DEFAULT -1; - -INSERT INTO T SELECT b, b - 10 FROM generate_series(11, 20) a(b); - -ALTER TABLE T ADD COLUMN c_text TEXT DEFAULT 'hello'; - -INSERT INTO T SELECT b, b - 10, (b + 10)::text FROM generate_series(21, 30) a(b); - --- WHERE clause -SELECT c_bigint, c_text FROM T WHERE c_bigint = -1 LIMIT 1; - -EXPLAIN (VERBOSE TRUE, COSTS FALSE) -SELECT c_bigint, c_text FROM T WHERE c_bigint = -1 LIMIT 1; - -SELECT c_bigint, c_text FROM T WHERE c_text = 'hello' LIMIT 1; - -EXPLAIN (VERBOSE TRUE, COSTS FALSE) SELECT c_bigint, c_text FROM T WHERE c_text = 'hello' LIMIT 1; - - --- COALESCE -SELECT COALESCE(c_bigint, pk), COALESCE(c_text, pk::text) -FROM T -ORDER BY pk LIMIT 10; - --- Aggregate function -SELECT SUM(c_bigint), MAX(c_text COLLATE "C" ), MIN(c_text COLLATE "C") FROM T; - --- ORDER BY -SELECT * FROM T ORDER BY c_bigint, c_text, pk LIMIT 10; - -EXPLAIN (VERBOSE TRUE, COSTS FALSE) -SELECT * FROM T ORDER BY c_bigint, c_text, pk LIMIT 10; - --- LIMIT -SELECT * FROM T WHERE c_bigint > -1 ORDER BY c_bigint, c_text, pk LIMIT 10; - -EXPLAIN (VERBOSE TRUE, COSTS FALSE) -SELECT * FROM T WHERE c_bigint > -1 ORDER BY c_bigint, c_text, pk LIMIT 10; - --- DELETE with RETURNING -DELETE FROM T WHERE pk BETWEEN 10 AND 20 RETURNING *; -EXPLAIN (VERBOSE TRUE, COSTS FALSE) -DELETE FROM T WHERE pk BETWEEN 10 AND 20 RETURNING *; - --- UPDATE -UPDATE T SET c_text = '"' || c_text || '"' WHERE pk < 10; -SELECT * FROM T WHERE c_text LIKE '"%"' ORDER BY PK; - -SELECT comp(); - -DROP TABLE T; - - --- Combine with other DDL -CREATE TABLE T(pk INT NOT NULL PRIMARY KEY); - -SELECT set('t'); - -INSERT INTO T VALUES (1), (2); - -ALTER TABLE T ADD COLUMN c_int INT NOT NULL DEFAULT -1; - -INSERT INTO T VALUES (3), (4); - -ALTER TABLE T ADD COLUMN c_text TEXT DEFAULT 'Hello'; - -INSERT INTO T VALUES (5), (6); - -ALTER TABLE T ALTER COLUMN c_text SET DEFAULT 'world', - ALTER COLUMN c_int SET DEFAULT 1; - -INSERT INTO T VALUES (7), (8); - -SELECT * FROM T ORDER BY pk; - --- Add an index -CREATE INDEX i ON T(c_int, c_text); - -SELECT c_text FROM T WHERE c_int = -1; - -SELECT comp(); - --- query to exercise expand_tuple function -CREATE TABLE t1 AS -SELECT 1::int AS a , 2::int AS b -FROM generate_series(1,20) q; - -ALTER TABLE t1 ADD COLUMN c text; - -SELECT a, - stddev(cast((SELECT sum(1) FROM generate_series(1,20) x) AS float4)) - OVER (PARTITION BY a,b,c ORDER BY b) - AS z -FROM t1; - -DROP TABLE T; - --- test that we account for missing columns without defaults correctly --- in expand_tuple, and that rows are correctly expanded for triggers - -CREATE FUNCTION test_trigger() -RETURNS trigger -LANGUAGE plpgsql -AS $$ - -begin - raise notice 'old tuple: %', to_json(OLD)::text; - if TG_OP = 'DELETE' - then - return OLD; - else - return NEW; - end if; -end; - -$$; - --- 2 new columns, both have defaults -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,3); -ALTER TABLE t ADD COLUMN x int NOT NULL DEFAULT 4; -ALTER TABLE t ADD COLUMN y int NOT NULL DEFAULT 5; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- 2 new columns, first has default -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,3); -ALTER TABLE t ADD COLUMN x int NOT NULL DEFAULT 4; -ALTER TABLE t ADD COLUMN y int; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- 2 new columns, second has default -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,3); -ALTER TABLE t ADD COLUMN x int; -ALTER TABLE t ADD COLUMN y int NOT NULL DEFAULT 5; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- 2 new columns, neither has default -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,3); -ALTER TABLE t ADD COLUMN x int; -ALTER TABLE t ADD COLUMN y int; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- same as last 4 tests but here the last original column has a NULL value --- 2 new columns, both have defaults -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,NULL); -ALTER TABLE t ADD COLUMN x int NOT NULL DEFAULT 4; -ALTER TABLE t ADD COLUMN y int NOT NULL DEFAULT 5; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- 2 new columns, first has default -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,NULL); -ALTER TABLE t ADD COLUMN x int NOT NULL DEFAULT 4; -ALTER TABLE t ADD COLUMN y int; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- 2 new columns, second has default -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,NULL); -ALTER TABLE t ADD COLUMN x int; -ALTER TABLE t ADD COLUMN y int NOT NULL DEFAULT 5; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- 2 new columns, neither has default -CREATE TABLE t (id serial PRIMARY KEY, a int, b int, c int); -INSERT INTO t (a,b,c) VALUES (1,2,NULL); -ALTER TABLE t ADD COLUMN x int; -ALTER TABLE t ADD COLUMN y int; -CREATE TRIGGER a BEFORE UPDATE ON t FOR EACH ROW EXECUTE PROCEDURE test_trigger(); -SELECT * FROM t; -UPDATE t SET y = 2; -SELECT * FROM t; -DROP TABLE t; - --- make sure expanded tuple has correct self pointer --- it will be required by the RI trigger doing the cascading delete - -CREATE TABLE leader (a int PRIMARY KEY, b int); -CREATE TABLE follower (a int REFERENCES leader ON DELETE CASCADE, b int); -INSERT INTO leader VALUES (1, 1), (2, 2); -ALTER TABLE leader ADD c int; -ALTER TABLE leader DROP c; -DELETE FROM leader; - --- check that ALTER TABLE ... ALTER TYPE does the right thing - -CREATE TABLE vtype( a integer); -INSERT INTO vtype VALUES (1); -ALTER TABLE vtype ADD COLUMN b DOUBLE PRECISION DEFAULT 0.2; -ALTER TABLE vtype ADD COLUMN c BOOLEAN DEFAULT true; -SELECT * FROM vtype; -ALTER TABLE vtype - ALTER b TYPE text USING b::text, - ALTER c TYPE text USING c::text; -SELECT * FROM vtype; - --- also check the case that doesn't rewrite the table - -CREATE TABLE vtype2 (a int); -INSERT INTO vtype2 VALUES (1); -ALTER TABLE vtype2 ADD COLUMN b varchar(10) DEFAULT 'xxx'; -ALTER TABLE vtype2 ALTER COLUMN b SET DEFAULT 'yyy'; -INSERT INTO vtype2 VALUES (2); - -ALTER TABLE vtype2 ALTER COLUMN b TYPE varchar(20) USING b::varchar(20); -SELECT * FROM vtype2; - - --- Ensure that defaults are checked when evaluating whether HOT update --- is possible, this was broken for a while: --- https://postgr.es/m/20190202133521.ylauh3ckqa7colzj%40alap3.anarazel.de -BEGIN; -CREATE TABLE t(); -INSERT INTO t DEFAULT VALUES; -ALTER TABLE t ADD COLUMN a int DEFAULT 1; -CREATE INDEX ON t(a); --- set column with a default 1 to NULL, due to a bug that wasn't --- noticed has heap_getattr buggily returned NULL for default columns -UPDATE t SET a = NULL; - --- verify that index and non-index scans show the same result -SET LOCAL enable_seqscan = true; -SELECT * FROM t WHERE a IS NULL; -SET LOCAL enable_seqscan = false; -SELECT * FROM t WHERE a IS NULL; -ROLLBACK; - --- verify that a default set on a non-plain table doesn't set a missing --- value on the attribute -CREATE FOREIGN DATA WRAPPER dummy; -CREATE SERVER s0 FOREIGN DATA WRAPPER dummy; -CREATE FOREIGN TABLE ft1 (c1 integer NOT NULL) SERVER s0; -ALTER FOREIGN TABLE ft1 ADD COLUMN c8 integer DEFAULT 0; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE char(10); -SELECT count(*) - FROM pg_attribute - WHERE attrelid = 'ft1'::regclass AND - (attmissingval IS NOT NULL OR atthasmissing); - --- cleanup -DROP FOREIGN TABLE ft1; -DROP SERVER s0; -DROP FOREIGN DATA WRAPPER dummy; -DROP TABLE vtype; -DROP TABLE vtype2; -DROP TABLE follower; -DROP TABLE leader; -DROP FUNCTION test_trigger(); -DROP TABLE t1; -DROP FUNCTION set(name); -DROP FUNCTION comp(); -DROP TABLE m; -DROP TABLE has_volatile; -DROP EVENT TRIGGER has_volatile_rewrite; -DROP FUNCTION log_rewrite; -DROP SCHEMA fast_default; - --- Leave a table with an active fast default in place, for pg_upgrade testing -set search_path = public; -create table has_fast_default(f1 int); -insert into has_fast_default values(1); -alter table has_fast_default add column f2 int default 42; -table has_fast_default; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fforeign_data.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fforeign_data.sql deleted file mode 100644 index eefb860adc..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fforeign_data.sql +++ /dev/null @@ -1,866 +0,0 @@ --- --- Test foreign-data wrapper and server management. --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - -CREATE FUNCTION test_fdw_handler() - RETURNS fdw_handler - AS :'regresslib', 'test_fdw_handler' - LANGUAGE C; - --- Clean up in case a prior regression run failed - --- Suppress NOTICE messages when roles don't exist -SET client_min_messages TO 'warning'; - -DROP ROLE IF EXISTS regress_foreign_data_user, regress_test_role, regress_test_role2, regress_test_role_super, regress_test_indirect, regress_unprivileged_role; - -RESET client_min_messages; - -CREATE ROLE regress_foreign_data_user LOGIN SUPERUSER; -SET SESSION AUTHORIZATION 'regress_foreign_data_user'; - -CREATE ROLE regress_test_role; -CREATE ROLE regress_test_role2; -CREATE ROLE regress_test_role_super SUPERUSER; -CREATE ROLE regress_test_indirect; -CREATE ROLE regress_unprivileged_role; - -CREATE FOREIGN DATA WRAPPER dummy; -COMMENT ON FOREIGN DATA WRAPPER dummy IS 'useless'; -CREATE FOREIGN DATA WRAPPER postgresql VALIDATOR postgresql_fdw_validator; - --- At this point we should have 2 built-in wrappers and no servers. -SELECT fdwname, fdwhandler::regproc, fdwvalidator::regproc, fdwoptions FROM pg_foreign_data_wrapper ORDER BY 1, 2, 3; -SELECT srvname, srvoptions FROM pg_foreign_server; -SELECT * FROM pg_user_mapping; - --- CREATE FOREIGN DATA WRAPPER -CREATE FOREIGN DATA WRAPPER foo VALIDATOR bar; -- ERROR -CREATE FOREIGN DATA WRAPPER foo; -\dew - -CREATE FOREIGN DATA WRAPPER foo; -- duplicate -DROP FOREIGN DATA WRAPPER foo; -CREATE FOREIGN DATA WRAPPER foo OPTIONS (testing '1'); -\dew+ - -DROP FOREIGN DATA WRAPPER foo; -CREATE FOREIGN DATA WRAPPER foo OPTIONS (testing '1', testing '2'); -- ERROR -CREATE FOREIGN DATA WRAPPER foo OPTIONS (testing '1', another '2'); -\dew+ - -DROP FOREIGN DATA WRAPPER foo; -SET ROLE regress_test_role; -CREATE FOREIGN DATA WRAPPER foo; -- ERROR -RESET ROLE; -CREATE FOREIGN DATA WRAPPER foo VALIDATOR postgresql_fdw_validator; -\dew+ - --- HANDLER related checks -CREATE FUNCTION invalid_fdw_handler() RETURNS int LANGUAGE SQL AS 'SELECT 1;'; -CREATE FOREIGN DATA WRAPPER test_fdw HANDLER invalid_fdw_handler; -- ERROR -CREATE FOREIGN DATA WRAPPER test_fdw HANDLER test_fdw_handler HANDLER invalid_fdw_handler; -- ERROR -CREATE FOREIGN DATA WRAPPER test_fdw HANDLER test_fdw_handler; -DROP FOREIGN DATA WRAPPER test_fdw; - --- ALTER FOREIGN DATA WRAPPER -ALTER FOREIGN DATA WRAPPER foo OPTIONS (nonexistent 'fdw'); -- ERROR - -ALTER FOREIGN DATA WRAPPER foo; -- ERROR -ALTER FOREIGN DATA WRAPPER foo VALIDATOR bar; -- ERROR -ALTER FOREIGN DATA WRAPPER foo NO VALIDATOR; -\dew+ - -ALTER FOREIGN DATA WRAPPER foo OPTIONS (a '1', b '2'); -ALTER FOREIGN DATA WRAPPER foo OPTIONS (SET c '4'); -- ERROR -ALTER FOREIGN DATA WRAPPER foo OPTIONS (DROP c); -- ERROR -ALTER FOREIGN DATA WRAPPER foo OPTIONS (ADD x '1', DROP x); -\dew+ - -ALTER FOREIGN DATA WRAPPER foo OPTIONS (DROP a, SET b '3', ADD c '4'); -\dew+ - -ALTER FOREIGN DATA WRAPPER foo OPTIONS (a '2'); -ALTER FOREIGN DATA WRAPPER foo OPTIONS (b '4'); -- ERROR -\dew+ - -SET ROLE regress_test_role; -ALTER FOREIGN DATA WRAPPER foo OPTIONS (ADD d '5'); -- ERROR -SET ROLE regress_test_role_super; -ALTER FOREIGN DATA WRAPPER foo OPTIONS (ADD d '5'); -\dew+ - -ALTER FOREIGN DATA WRAPPER foo OWNER TO regress_test_role; -- ERROR -ALTER FOREIGN DATA WRAPPER foo OWNER TO regress_test_role_super; -ALTER ROLE regress_test_role_super NOSUPERUSER; -SET ROLE regress_test_role_super; -ALTER FOREIGN DATA WRAPPER foo OPTIONS (ADD e '6'); -- ERROR -RESET ROLE; -\dew+ - -ALTER FOREIGN DATA WRAPPER foo RENAME TO foo1; -\dew+ -ALTER FOREIGN DATA WRAPPER foo1 RENAME TO foo; - --- HANDLER related checks -ALTER FOREIGN DATA WRAPPER foo HANDLER invalid_fdw_handler; -- ERROR -ALTER FOREIGN DATA WRAPPER foo HANDLER test_fdw_handler HANDLER anything; -- ERROR -ALTER FOREIGN DATA WRAPPER foo HANDLER test_fdw_handler; -DROP FUNCTION invalid_fdw_handler(); - --- DROP FOREIGN DATA WRAPPER -DROP FOREIGN DATA WRAPPER nonexistent; -- ERROR -DROP FOREIGN DATA WRAPPER IF EXISTS nonexistent; -\dew+ - -DROP ROLE regress_test_role_super; -- ERROR -SET ROLE regress_test_role_super; -DROP FOREIGN DATA WRAPPER foo; -RESET ROLE; -DROP ROLE regress_test_role_super; -\dew+ - -CREATE FOREIGN DATA WRAPPER foo; -CREATE SERVER s1 FOREIGN DATA WRAPPER foo; -COMMENT ON SERVER s1 IS 'foreign server'; -CREATE USER MAPPING FOR current_user SERVER s1; -CREATE USER MAPPING FOR current_user SERVER s1; -- ERROR -CREATE USER MAPPING IF NOT EXISTS FOR current_user SERVER s1; -- NOTICE -\dew+ -\des+ -\deu+ -DROP FOREIGN DATA WRAPPER foo; -- ERROR -SET ROLE regress_test_role; -DROP FOREIGN DATA WRAPPER foo CASCADE; -- ERROR -RESET ROLE; -DROP FOREIGN DATA WRAPPER foo CASCADE; -\dew+ -\des+ -\deu+ - --- exercise CREATE SERVER -CREATE SERVER s1 FOREIGN DATA WRAPPER foo; -- ERROR -CREATE FOREIGN DATA WRAPPER foo OPTIONS ("test wrapper" 'true'); -CREATE SERVER s1 FOREIGN DATA WRAPPER foo; -CREATE SERVER s1 FOREIGN DATA WRAPPER foo; -- ERROR -CREATE SERVER IF NOT EXISTS s1 FOREIGN DATA WRAPPER foo; -- No ERROR, just NOTICE -CREATE SERVER s2 FOREIGN DATA WRAPPER foo OPTIONS (host 'a', dbname 'b'); -CREATE SERVER s3 TYPE 'oracle' FOREIGN DATA WRAPPER foo; -CREATE SERVER s4 TYPE 'oracle' FOREIGN DATA WRAPPER foo OPTIONS (host 'a', dbname 'b'); -CREATE SERVER s5 VERSION '15.0' FOREIGN DATA WRAPPER foo; -CREATE SERVER s6 VERSION '16.0' FOREIGN DATA WRAPPER foo OPTIONS (host 'a', dbname 'b'); -CREATE SERVER s7 TYPE 'oracle' VERSION '17.0' FOREIGN DATA WRAPPER foo OPTIONS (host 'a', dbname 'b'); -CREATE SERVER s8 FOREIGN DATA WRAPPER postgresql OPTIONS (foo '1'); -- ERROR -CREATE SERVER s8 FOREIGN DATA WRAPPER postgresql OPTIONS (host 'localhost', dbname 's8db'); -\des+ -SET ROLE regress_test_role; -CREATE SERVER t1 FOREIGN DATA WRAPPER foo; -- ERROR: no usage on FDW -RESET ROLE; -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_role; -SET ROLE regress_test_role; -CREATE SERVER t1 FOREIGN DATA WRAPPER foo; -RESET ROLE; -\des+ - -REVOKE USAGE ON FOREIGN DATA WRAPPER foo FROM regress_test_role; -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_indirect; -SET ROLE regress_test_role; -CREATE SERVER t2 FOREIGN DATA WRAPPER foo; -- ERROR -RESET ROLE; -GRANT regress_test_indirect TO regress_test_role; -SET ROLE regress_test_role; -CREATE SERVER t2 FOREIGN DATA WRAPPER foo; -\des+ -RESET ROLE; -REVOKE regress_test_indirect FROM regress_test_role; - --- ALTER SERVER -ALTER SERVER s0; -- ERROR -ALTER SERVER s0 OPTIONS (a '1'); -- ERROR -ALTER SERVER s1 VERSION '1.0' OPTIONS (servername 's1'); -ALTER SERVER s2 VERSION '1.1'; -ALTER SERVER s3 OPTIONS ("tns name" 'orcl', port '1521'); -GRANT USAGE ON FOREIGN SERVER s1 TO regress_test_role; -GRANT USAGE ON FOREIGN SERVER s6 TO regress_test_role2 WITH GRANT OPTION; -\des+ -SET ROLE regress_test_role; -ALTER SERVER s1 VERSION '1.1'; -- ERROR -ALTER SERVER s1 OWNER TO regress_test_role; -- ERROR -RESET ROLE; -ALTER SERVER s1 OWNER TO regress_test_role; -GRANT regress_test_role2 TO regress_test_role; -SET ROLE regress_test_role; -ALTER SERVER s1 VERSION '1.1'; -ALTER SERVER s1 OWNER TO regress_test_role2; -- ERROR -RESET ROLE; -ALTER SERVER s8 OPTIONS (foo '1'); -- ERROR option validation -ALTER SERVER s8 OPTIONS (connect_timeout '30', SET dbname 'db1', DROP host); -SET ROLE regress_test_role; -ALTER SERVER s1 OWNER TO regress_test_indirect; -- ERROR -RESET ROLE; -GRANT regress_test_indirect TO regress_test_role; -SET ROLE regress_test_role; -ALTER SERVER s1 OWNER TO regress_test_indirect; -RESET ROLE; -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_indirect; -SET ROLE regress_test_role; -ALTER SERVER s1 OWNER TO regress_test_indirect; -RESET ROLE; -DROP ROLE regress_test_indirect; -- ERROR -\des+ - -ALTER SERVER s8 RENAME to s8new; -\des+ -ALTER SERVER s8new RENAME to s8; - --- DROP SERVER -DROP SERVER nonexistent; -- ERROR -DROP SERVER IF EXISTS nonexistent; -\des -SET ROLE regress_test_role; -DROP SERVER s2; -- ERROR -DROP SERVER s1; -RESET ROLE; -\des -ALTER SERVER s2 OWNER TO regress_test_role; -SET ROLE regress_test_role; -DROP SERVER s2; -RESET ROLE; -\des -CREATE USER MAPPING FOR current_user SERVER s3; -\deu -DROP SERVER s3; -- ERROR -DROP SERVER s3 CASCADE; -\des -\deu - --- CREATE USER MAPPING -CREATE USER MAPPING FOR regress_test_missing_role SERVER s1; -- ERROR -CREATE USER MAPPING FOR current_user SERVER s1; -- ERROR -CREATE USER MAPPING FOR current_user SERVER s4; -CREATE USER MAPPING FOR user SERVER s4; -- ERROR duplicate -CREATE USER MAPPING FOR public SERVER s4 OPTIONS ("this mapping" 'is public'); -CREATE USER MAPPING FOR user SERVER s8 OPTIONS (username 'test', password 'secret'); -- ERROR -CREATE USER MAPPING FOR user SERVER s8 OPTIONS (user 'test', password 'secret'); -ALTER SERVER s5 OWNER TO regress_test_role; -ALTER SERVER s6 OWNER TO regress_test_indirect; -SET ROLE regress_test_role; -CREATE USER MAPPING FOR current_user SERVER s5; -CREATE USER MAPPING FOR current_user SERVER s6 OPTIONS (username 'test'); -CREATE USER MAPPING FOR current_user SERVER s7; -- ERROR -CREATE USER MAPPING FOR public SERVER s8; -- ERROR -RESET ROLE; - -ALTER SERVER t1 OWNER TO regress_test_indirect; -SET ROLE regress_test_role; -CREATE USER MAPPING FOR current_user SERVER t1 OPTIONS (username 'bob', password 'boo'); -CREATE USER MAPPING FOR public SERVER t1; -RESET ROLE; -\deu - --- ALTER USER MAPPING -ALTER USER MAPPING FOR regress_test_missing_role SERVER s4 OPTIONS (gotcha 'true'); -- ERROR -ALTER USER MAPPING FOR user SERVER ss4 OPTIONS (gotcha 'true'); -- ERROR -ALTER USER MAPPING FOR public SERVER s5 OPTIONS (gotcha 'true'); -- ERROR -ALTER USER MAPPING FOR current_user SERVER s8 OPTIONS (username 'test'); -- ERROR -ALTER USER MAPPING FOR current_user SERVER s8 OPTIONS (DROP user, SET password 'public'); -SET ROLE regress_test_role; -ALTER USER MAPPING FOR current_user SERVER s5 OPTIONS (ADD modified '1'); -ALTER USER MAPPING FOR public SERVER s4 OPTIONS (ADD modified '1'); -- ERROR -ALTER USER MAPPING FOR public SERVER t1 OPTIONS (ADD modified '1'); -RESET ROLE; -\deu+ - --- DROP USER MAPPING -DROP USER MAPPING FOR regress_test_missing_role SERVER s4; -- ERROR -DROP USER MAPPING FOR user SERVER ss4; -DROP USER MAPPING FOR public SERVER s7; -- ERROR -DROP USER MAPPING IF EXISTS FOR regress_test_missing_role SERVER s4; -DROP USER MAPPING IF EXISTS FOR user SERVER ss4; -DROP USER MAPPING IF EXISTS FOR public SERVER s7; -CREATE USER MAPPING FOR public SERVER s8; -SET ROLE regress_test_role; -DROP USER MAPPING FOR public SERVER s8; -- ERROR -RESET ROLE; -DROP SERVER s7; -\deu - --- CREATE FOREIGN TABLE -CREATE SCHEMA foreign_schema; -CREATE SERVER s0 FOREIGN DATA WRAPPER dummy; -CREATE FOREIGN TABLE ft1 (); -- ERROR -CREATE FOREIGN TABLE ft1 () SERVER no_server; -- ERROR -CREATE FOREIGN TABLE ft1 ( - c1 integer OPTIONS ("param 1" 'val1') PRIMARY KEY, - c2 text OPTIONS (param2 'val2', param3 'val3'), - c3 date -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -- ERROR -CREATE TABLE ref_table (id integer PRIMARY KEY); -CREATE FOREIGN TABLE ft1 ( - c1 integer OPTIONS ("param 1" 'val1') REFERENCES ref_table (id), - c2 text OPTIONS (param2 'val2', param3 'val3'), - c3 date -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -- ERROR -DROP TABLE ref_table; -CREATE FOREIGN TABLE ft1 ( - c1 integer OPTIONS ("param 1" 'val1') NOT NULL, - c2 text OPTIONS (param2 'val2', param3 'val3'), - c3 date, - UNIQUE (c3) -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -- ERROR -CREATE FOREIGN TABLE ft1 ( - c1 integer OPTIONS ("param 1" 'val1') NOT NULL, - c2 text OPTIONS (param2 'val2', param3 'val3') CHECK (c2 <> ''), - c3 date, - CHECK (c3 BETWEEN '1994-01-01'::date AND '1994-01-31'::date) -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -COMMENT ON FOREIGN TABLE ft1 IS 'ft1'; -COMMENT ON COLUMN ft1.c1 IS 'ft1.c1'; -\d+ ft1 -\det+ -CREATE INDEX id_ft1_c2 ON ft1 (c2); -- ERROR -SELECT * FROM ft1; -- ERROR -EXPLAIN SELECT * FROM ft1; -- ERROR - -CREATE TABLE lt1 (a INT) PARTITION BY RANGE (a); -CREATE FOREIGN TABLE ft_part1 - PARTITION OF lt1 FOR VALUES FROM (0) TO (1000) SERVER s0; -CREATE INDEX ON lt1 (a); -- skips partition -CREATE UNIQUE INDEX ON lt1 (a); -- ERROR -ALTER TABLE lt1 ADD PRIMARY KEY (a); -- ERROR -DROP TABLE lt1; - -CREATE TABLE lt1 (a INT) PARTITION BY RANGE (a); -CREATE INDEX ON lt1 (a); -CREATE FOREIGN TABLE ft_part1 - PARTITION OF lt1 FOR VALUES FROM (0) TO (1000) SERVER s0; -CREATE FOREIGN TABLE ft_part2 (a INT) SERVER s0; -ALTER TABLE lt1 ATTACH PARTITION ft_part2 FOR VALUES FROM (1000) TO (2000); -DROP FOREIGN TABLE ft_part1, ft_part2; -CREATE UNIQUE INDEX ON lt1 (a); -ALTER TABLE lt1 ADD PRIMARY KEY (a); -CREATE FOREIGN TABLE ft_part1 - PARTITION OF lt1 FOR VALUES FROM (0) TO (1000) SERVER s0; -- ERROR -CREATE FOREIGN TABLE ft_part2 (a INT NOT NULL) SERVER s0; -ALTER TABLE lt1 ATTACH PARTITION ft_part2 - FOR VALUES FROM (1000) TO (2000); -- ERROR -DROP TABLE lt1; -DROP FOREIGN TABLE ft_part2; - -CREATE TABLE lt1 (a INT) PARTITION BY RANGE (a); -CREATE INDEX ON lt1 (a); -CREATE TABLE lt1_part1 - PARTITION OF lt1 FOR VALUES FROM (0) TO (1000) - PARTITION BY RANGE (a); -CREATE FOREIGN TABLE ft_part_1_1 - PARTITION OF lt1_part1 FOR VALUES FROM (0) TO (100) SERVER s0; -CREATE FOREIGN TABLE ft_part_1_2 (a INT) SERVER s0; -ALTER TABLE lt1_part1 ATTACH PARTITION ft_part_1_2 FOR VALUES FROM (100) TO (200); -CREATE UNIQUE INDEX ON lt1 (a); -ALTER TABLE lt1 ADD PRIMARY KEY (a); -DROP FOREIGN TABLE ft_part_1_1, ft_part_1_2; -CREATE UNIQUE INDEX ON lt1 (a); -ALTER TABLE lt1 ADD PRIMARY KEY (a); -CREATE FOREIGN TABLE ft_part_1_1 - PARTITION OF lt1_part1 FOR VALUES FROM (0) TO (100) SERVER s0; -CREATE FOREIGN TABLE ft_part_1_2 (a INT NOT NULL) SERVER s0; -ALTER TABLE lt1_part1 ATTACH PARTITION ft_part_1_2 FOR VALUES FROM (100) TO (200); -DROP TABLE lt1; -DROP FOREIGN TABLE ft_part_1_2; - --- ALTER FOREIGN TABLE -COMMENT ON FOREIGN TABLE ft1 IS 'foreign table'; -COMMENT ON FOREIGN TABLE ft1 IS NULL; -COMMENT ON COLUMN ft1.c1 IS 'foreign column'; -COMMENT ON COLUMN ft1.c1 IS NULL; - -ALTER FOREIGN TABLE ft1 ADD COLUMN c4 integer; -ALTER FOREIGN TABLE ft1 ADD COLUMN c5 integer DEFAULT 0; -ALTER FOREIGN TABLE ft1 ADD COLUMN c6 integer; -ALTER FOREIGN TABLE ft1 ADD COLUMN c7 integer NOT NULL; -ALTER FOREIGN TABLE ft1 ADD COLUMN c8 integer; -ALTER FOREIGN TABLE ft1 ADD COLUMN c9 integer; -ALTER FOREIGN TABLE ft1 ADD COLUMN c10 integer OPTIONS (p1 'v1'); - -ALTER FOREIGN TABLE ft1 ALTER COLUMN c4 SET DEFAULT 0; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c5 DROP DEFAULT; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c6 SET NOT NULL; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c7 DROP NOT NULL; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE char(10) USING '0'; -- ERROR -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 TYPE char(10); -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 SET DATA TYPE text; -ALTER FOREIGN TABLE ft1 ALTER COLUMN xmin OPTIONS (ADD p1 'v1'); -- ERROR -ALTER FOREIGN TABLE ft1 ALTER COLUMN c7 OPTIONS (ADD p1 'v1', ADD p2 'v2'), - ALTER COLUMN c8 OPTIONS (ADD p1 'v1', ADD p2 'v2'); -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 OPTIONS (SET p2 'V2', DROP p1); -ALTER FOREIGN TABLE ft1 ALTER COLUMN c1 SET STATISTICS 10000; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c1 SET (n_distinct = 100); -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 SET STATISTICS -1; -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 SET STORAGE PLAIN; -\d+ ft1 --- can't change the column type if it's used elsewhere -CREATE TABLE use_ft1_column_type (x ft1); -ALTER FOREIGN TABLE ft1 ALTER COLUMN c8 SET DATA TYPE integer; -- ERROR -DROP TABLE use_ft1_column_type; -ALTER FOREIGN TABLE ft1 ADD PRIMARY KEY (c7); -- ERROR -ALTER FOREIGN TABLE ft1 ADD CONSTRAINT ft1_c9_check CHECK (c9 < 0) NOT VALID; -ALTER FOREIGN TABLE ft1 ALTER CONSTRAINT ft1_c9_check DEFERRABLE; -- ERROR -ALTER FOREIGN TABLE ft1 DROP CONSTRAINT ft1_c9_check; -ALTER FOREIGN TABLE ft1 DROP CONSTRAINT no_const; -- ERROR -ALTER FOREIGN TABLE ft1 DROP CONSTRAINT IF EXISTS no_const; -ALTER FOREIGN TABLE ft1 OWNER TO regress_test_role; -ALTER FOREIGN TABLE ft1 OPTIONS (DROP delimiter, SET quote '~', ADD escape '@'); -ALTER FOREIGN TABLE ft1 DROP COLUMN no_column; -- ERROR -ALTER FOREIGN TABLE ft1 DROP COLUMN IF EXISTS no_column; -ALTER FOREIGN TABLE ft1 DROP COLUMN c9; -ALTER FOREIGN TABLE ft1 SET SCHEMA foreign_schema; -ALTER FOREIGN TABLE ft1 SET TABLESPACE ts; -- ERROR -ALTER FOREIGN TABLE foreign_schema.ft1 RENAME c1 TO foreign_column_1; -ALTER FOREIGN TABLE foreign_schema.ft1 RENAME TO foreign_table_1; -\d foreign_schema.foreign_table_1 - --- alter noexisting table -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ADD COLUMN c4 integer; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ADD COLUMN c6 integer; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ADD COLUMN c7 integer NOT NULL; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ADD COLUMN c8 integer; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ADD COLUMN c9 integer; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ADD COLUMN c10 integer OPTIONS (p1 'v1'); - -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ALTER COLUMN c6 SET NOT NULL; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ALTER COLUMN c7 DROP NOT NULL; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ALTER COLUMN c8 TYPE char(10); -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ALTER COLUMN c8 SET DATA TYPE text; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ALTER COLUMN c7 OPTIONS (ADD p1 'v1', ADD p2 'v2'), - ALTER COLUMN c8 OPTIONS (ADD p1 'v1', ADD p2 'v2'); -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 ALTER COLUMN c8 OPTIONS (SET p2 'V2', DROP p1); - -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 DROP CONSTRAINT IF EXISTS no_const; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 DROP CONSTRAINT ft1_c1_check; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 OWNER TO regress_test_role; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 OPTIONS (DROP delimiter, SET quote '~', ADD escape '@'); -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 DROP COLUMN IF EXISTS no_column; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 DROP COLUMN c9; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 SET SCHEMA foreign_schema; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 RENAME c1 TO foreign_column_1; -ALTER FOREIGN TABLE IF EXISTS doesnt_exist_ft1 RENAME TO foreign_table_1; - --- Information schema - -SELECT * FROM information_schema.foreign_data_wrappers ORDER BY 1, 2; -SELECT * FROM information_schema.foreign_data_wrapper_options ORDER BY 1, 2, 3; -SELECT * FROM information_schema.foreign_servers ORDER BY 1, 2; -SELECT * FROM information_schema.foreign_server_options ORDER BY 1, 2, 3; -SELECT * FROM information_schema.user_mappings ORDER BY lower(authorization_identifier), 2, 3; -SELECT * FROM information_schema.user_mapping_options ORDER BY lower(authorization_identifier), 2, 3, 4; -SELECT * FROM information_schema.usage_privileges WHERE object_type LIKE 'FOREIGN%' AND object_name IN ('s6', 'foo') ORDER BY 1, 2, 3, 4, 5; -SELECT * FROM information_schema.role_usage_grants WHERE object_type LIKE 'FOREIGN%' AND object_name IN ('s6', 'foo') ORDER BY 1, 2, 3, 4, 5; -SELECT * FROM information_schema.foreign_tables ORDER BY 1, 2, 3; -SELECT * FROM information_schema.foreign_table_options ORDER BY 1, 2, 3, 4; -SET ROLE regress_test_role; -SELECT * FROM information_schema.user_mapping_options ORDER BY 1, 2, 3, 4; -SELECT * FROM information_schema.usage_privileges WHERE object_type LIKE 'FOREIGN%' AND object_name IN ('s6', 'foo') ORDER BY 1, 2, 3, 4, 5; -SELECT * FROM information_schema.role_usage_grants WHERE object_type LIKE 'FOREIGN%' AND object_name IN ('s6', 'foo') ORDER BY 1, 2, 3, 4, 5; -DROP USER MAPPING FOR current_user SERVER t1; -SET ROLE regress_test_role2; -SELECT * FROM information_schema.user_mapping_options ORDER BY 1, 2, 3, 4; -RESET ROLE; - - --- has_foreign_data_wrapper_privilege -SELECT has_foreign_data_wrapper_privilege('regress_test_role', - (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE'); -SELECT has_foreign_data_wrapper_privilege('regress_test_role', 'foo', 'USAGE'); -SELECT has_foreign_data_wrapper_privilege( - (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), - (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE'); -SELECT has_foreign_data_wrapper_privilege( - (SELECT oid FROM pg_foreign_data_wrapper WHERE fdwname='foo'), 'USAGE'); -SELECT has_foreign_data_wrapper_privilege( - (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), 'foo', 'USAGE'); -SELECT has_foreign_data_wrapper_privilege('foo', 'USAGE'); -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_role; -SELECT has_foreign_data_wrapper_privilege('regress_test_role', 'foo', 'USAGE'); - --- has_server_privilege -SELECT has_server_privilege('regress_test_role', - (SELECT oid FROM pg_foreign_server WHERE srvname='s8'), 'USAGE'); -SELECT has_server_privilege('regress_test_role', 's8', 'USAGE'); -SELECT has_server_privilege( - (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), - (SELECT oid FROM pg_foreign_server WHERE srvname='s8'), 'USAGE'); -SELECT has_server_privilege( - (SELECT oid FROM pg_foreign_server WHERE srvname='s8'), 'USAGE'); -SELECT has_server_privilege( - (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), 's8', 'USAGE'); -SELECT has_server_privilege('s8', 'USAGE'); -GRANT USAGE ON FOREIGN SERVER s8 TO regress_test_role; -SELECT has_server_privilege('regress_test_role', 's8', 'USAGE'); -REVOKE USAGE ON FOREIGN SERVER s8 FROM regress_test_role; - -GRANT USAGE ON FOREIGN SERVER s4 TO regress_test_role; -DROP USER MAPPING FOR public SERVER s4; -ALTER SERVER s6 OPTIONS (DROP host, DROP dbname); -ALTER USER MAPPING FOR regress_test_role SERVER s6 OPTIONS (DROP username); -ALTER FOREIGN DATA WRAPPER foo VALIDATOR postgresql_fdw_validator; - --- Privileges -SET ROLE regress_unprivileged_role; -CREATE FOREIGN DATA WRAPPER foobar; -- ERROR -ALTER FOREIGN DATA WRAPPER foo OPTIONS (gotcha 'true'); -- ERROR -ALTER FOREIGN DATA WRAPPER foo OWNER TO regress_unprivileged_role; -- ERROR -DROP FOREIGN DATA WRAPPER foo; -- ERROR -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_role; -- ERROR -CREATE SERVER s9 FOREIGN DATA WRAPPER foo; -- ERROR -ALTER SERVER s4 VERSION '0.5'; -- ERROR -ALTER SERVER s4 OWNER TO regress_unprivileged_role; -- ERROR -DROP SERVER s4; -- ERROR -GRANT USAGE ON FOREIGN SERVER s4 TO regress_test_role; -- ERROR -CREATE USER MAPPING FOR public SERVER s4; -- ERROR -ALTER USER MAPPING FOR regress_test_role SERVER s6 OPTIONS (gotcha 'true'); -- ERROR -DROP USER MAPPING FOR regress_test_role SERVER s6; -- ERROR -RESET ROLE; - -GRANT USAGE ON FOREIGN DATA WRAPPER postgresql TO regress_unprivileged_role; -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_unprivileged_role WITH GRANT OPTION; -SET ROLE regress_unprivileged_role; -CREATE FOREIGN DATA WRAPPER foobar; -- ERROR -ALTER FOREIGN DATA WRAPPER foo OPTIONS (gotcha 'true'); -- ERROR -DROP FOREIGN DATA WRAPPER foo; -- ERROR -GRANT USAGE ON FOREIGN DATA WRAPPER postgresql TO regress_test_role; -- WARNING -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_role; -CREATE SERVER s9 FOREIGN DATA WRAPPER postgresql; -ALTER SERVER s6 VERSION '0.5'; -- ERROR -DROP SERVER s6; -- ERROR -GRANT USAGE ON FOREIGN SERVER s6 TO regress_test_role; -- ERROR -GRANT USAGE ON FOREIGN SERVER s9 TO regress_test_role; -CREATE USER MAPPING FOR public SERVER s6; -- ERROR -CREATE USER MAPPING FOR public SERVER s9; -ALTER USER MAPPING FOR regress_test_role SERVER s6 OPTIONS (gotcha 'true'); -- ERROR -DROP USER MAPPING FOR regress_test_role SERVER s6; -- ERROR -RESET ROLE; - -REVOKE USAGE ON FOREIGN DATA WRAPPER foo FROM regress_unprivileged_role; -- ERROR -REVOKE USAGE ON FOREIGN DATA WRAPPER foo FROM regress_unprivileged_role CASCADE; -SET ROLE regress_unprivileged_role; -GRANT USAGE ON FOREIGN DATA WRAPPER foo TO regress_test_role; -- ERROR -CREATE SERVER s10 FOREIGN DATA WRAPPER foo; -- ERROR -ALTER SERVER s9 VERSION '1.1'; -GRANT USAGE ON FOREIGN SERVER s9 TO regress_test_role; -CREATE USER MAPPING FOR current_user SERVER s9; -DROP SERVER s9 CASCADE; -RESET ROLE; -CREATE SERVER s9 FOREIGN DATA WRAPPER foo; -GRANT USAGE ON FOREIGN SERVER s9 TO regress_unprivileged_role; -SET ROLE regress_unprivileged_role; -ALTER SERVER s9 VERSION '1.2'; -- ERROR -GRANT USAGE ON FOREIGN SERVER s9 TO regress_test_role; -- WARNING -CREATE USER MAPPING FOR current_user SERVER s9; -DROP SERVER s9 CASCADE; -- ERROR - --- Check visibility of user mapping data -SET ROLE regress_test_role; -CREATE SERVER s10 FOREIGN DATA WRAPPER foo; -CREATE USER MAPPING FOR public SERVER s10 OPTIONS (user 'secret'); -CREATE USER MAPPING FOR regress_unprivileged_role SERVER s10 OPTIONS (user 'secret'); --- owner of server can see some option fields -\deu+ -RESET ROLE; --- superuser can see all option fields -\deu+ --- unprivileged user cannot see any option field -SET ROLE regress_unprivileged_role; -\deu+ -RESET ROLE; -DROP SERVER s10 CASCADE; - --- Triggers -CREATE FUNCTION dummy_trigger() RETURNS TRIGGER AS $$ - BEGIN - RETURN NULL; - END -$$ language plpgsql; - -CREATE TRIGGER trigtest_before_stmt BEFORE INSERT OR UPDATE OR DELETE -ON foreign_schema.foreign_table_1 -FOR EACH STATEMENT -EXECUTE PROCEDURE dummy_trigger(); - -CREATE TRIGGER trigtest_after_stmt AFTER INSERT OR UPDATE OR DELETE -ON foreign_schema.foreign_table_1 -FOR EACH STATEMENT -EXECUTE PROCEDURE dummy_trigger(); - -CREATE TRIGGER trigtest_after_stmt_tt AFTER INSERT OR UPDATE OR DELETE -- ERROR -ON foreign_schema.foreign_table_1 -REFERENCING NEW TABLE AS new_table -FOR EACH STATEMENT -EXECUTE PROCEDURE dummy_trigger(); - -CREATE TRIGGER trigtest_before_row BEFORE INSERT OR UPDATE OR DELETE -ON foreign_schema.foreign_table_1 -FOR EACH ROW -EXECUTE PROCEDURE dummy_trigger(); - -CREATE TRIGGER trigtest_after_row AFTER INSERT OR UPDATE OR DELETE -ON foreign_schema.foreign_table_1 -FOR EACH ROW -EXECUTE PROCEDURE dummy_trigger(); - -CREATE CONSTRAINT TRIGGER trigtest_constraint AFTER INSERT OR UPDATE OR DELETE -ON foreign_schema.foreign_table_1 -FOR EACH ROW -EXECUTE PROCEDURE dummy_trigger(); - -ALTER FOREIGN TABLE foreign_schema.foreign_table_1 - DISABLE TRIGGER trigtest_before_stmt; -ALTER FOREIGN TABLE foreign_schema.foreign_table_1 - ENABLE TRIGGER trigtest_before_stmt; - -DROP TRIGGER trigtest_before_stmt ON foreign_schema.foreign_table_1; -DROP TRIGGER trigtest_before_row ON foreign_schema.foreign_table_1; -DROP TRIGGER trigtest_after_stmt ON foreign_schema.foreign_table_1; -DROP TRIGGER trigtest_after_row ON foreign_schema.foreign_table_1; - -DROP FUNCTION dummy_trigger(); - --- Table inheritance -CREATE TABLE fd_pt1 ( - c1 integer NOT NULL, - c2 text, - c3 date -); -CREATE FOREIGN TABLE ft2 () INHERITS (fd_pt1) - SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -\d+ fd_pt1 -\d+ ft2 -DROP FOREIGN TABLE ft2; -\d+ fd_pt1 -CREATE FOREIGN TABLE ft2 ( - c1 integer NOT NULL, - c2 text, - c3 date -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -\d+ ft2 -ALTER FOREIGN TABLE ft2 INHERIT fd_pt1; -\d+ fd_pt1 -\d+ ft2 -CREATE TABLE ct3() INHERITS(ft2); -CREATE FOREIGN TABLE ft3 ( - c1 integer NOT NULL, - c2 text, - c3 date -) INHERITS(ft2) - SERVER s0; -\d+ ft2 -\d+ ct3 -\d+ ft3 - --- add attributes recursively -ALTER TABLE fd_pt1 ADD COLUMN c4 integer; -ALTER TABLE fd_pt1 ADD COLUMN c5 integer DEFAULT 0; -ALTER TABLE fd_pt1 ADD COLUMN c6 integer; -ALTER TABLE fd_pt1 ADD COLUMN c7 integer NOT NULL; -ALTER TABLE fd_pt1 ADD COLUMN c8 integer; -\d+ fd_pt1 -\d+ ft2 -\d+ ct3 -\d+ ft3 - --- alter attributes recursively -ALTER TABLE fd_pt1 ALTER COLUMN c4 SET DEFAULT 0; -ALTER TABLE fd_pt1 ALTER COLUMN c5 DROP DEFAULT; -ALTER TABLE fd_pt1 ALTER COLUMN c6 SET NOT NULL; -ALTER TABLE fd_pt1 ALTER COLUMN c7 DROP NOT NULL; -ALTER TABLE fd_pt1 ALTER COLUMN c8 TYPE char(10) USING '0'; -- ERROR -ALTER TABLE fd_pt1 ALTER COLUMN c8 TYPE char(10); -ALTER TABLE fd_pt1 ALTER COLUMN c8 SET DATA TYPE text; -ALTER TABLE fd_pt1 ALTER COLUMN c1 SET STATISTICS 10000; -ALTER TABLE fd_pt1 ALTER COLUMN c1 SET (n_distinct = 100); -ALTER TABLE fd_pt1 ALTER COLUMN c8 SET STATISTICS -1; -ALTER TABLE fd_pt1 ALTER COLUMN c8 SET STORAGE EXTERNAL; -\d+ fd_pt1 -\d+ ft2 - --- drop attributes recursively -ALTER TABLE fd_pt1 DROP COLUMN c4; -ALTER TABLE fd_pt1 DROP COLUMN c5; -ALTER TABLE fd_pt1 DROP COLUMN c6; -ALTER TABLE fd_pt1 DROP COLUMN c7; -ALTER TABLE fd_pt1 DROP COLUMN c8; -\d+ fd_pt1 -\d+ ft2 - --- add constraints recursively -ALTER TABLE fd_pt1 ADD CONSTRAINT fd_pt1chk1 CHECK (c1 > 0) NO INHERIT; -ALTER TABLE fd_pt1 ADD CONSTRAINT fd_pt1chk2 CHECK (c2 <> ''); --- connoinherit should be true for NO INHERIT constraint -SELECT relname, conname, contype, conislocal, coninhcount, connoinherit - FROM pg_class AS pc JOIN pg_constraint AS pgc ON (conrelid = pc.oid) - WHERE pc.relname = 'fd_pt1' - ORDER BY 1,2; --- child does not inherit NO INHERIT constraints -\d+ fd_pt1 -\d+ ft2 -DROP FOREIGN TABLE ft2; -- ERROR -DROP FOREIGN TABLE ft2 CASCADE; -CREATE FOREIGN TABLE ft2 ( - c1 integer NOT NULL, - c2 text, - c3 date -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); --- child must have parent's INHERIT constraints -ALTER FOREIGN TABLE ft2 INHERIT fd_pt1; -- ERROR -ALTER FOREIGN TABLE ft2 ADD CONSTRAINT fd_pt1chk2 CHECK (c2 <> ''); -ALTER FOREIGN TABLE ft2 INHERIT fd_pt1; --- child does not inherit NO INHERIT constraints -\d+ fd_pt1 -\d+ ft2 - --- drop constraints recursively -ALTER TABLE fd_pt1 DROP CONSTRAINT fd_pt1chk1 CASCADE; -ALTER TABLE fd_pt1 DROP CONSTRAINT fd_pt1chk2 CASCADE; - --- NOT VALID case -INSERT INTO fd_pt1 VALUES (1, 'fd_pt1'::text, '1994-01-01'::date); -ALTER TABLE fd_pt1 ADD CONSTRAINT fd_pt1chk3 CHECK (c2 <> '') NOT VALID; -\d+ fd_pt1 -\d+ ft2 --- VALIDATE CONSTRAINT need do nothing on foreign tables -ALTER TABLE fd_pt1 VALIDATE CONSTRAINT fd_pt1chk3; -\d+ fd_pt1 -\d+ ft2 - --- changes name of an attribute recursively -ALTER TABLE fd_pt1 RENAME COLUMN c1 TO f1; -ALTER TABLE fd_pt1 RENAME COLUMN c2 TO f2; -ALTER TABLE fd_pt1 RENAME COLUMN c3 TO f3; --- changes name of a constraint recursively -ALTER TABLE fd_pt1 RENAME CONSTRAINT fd_pt1chk3 TO f2_check; -\d+ fd_pt1 -\d+ ft2 - -DROP TABLE fd_pt1 CASCADE; - --- IMPORT FOREIGN SCHEMA -IMPORT FOREIGN SCHEMA s1 FROM SERVER s9 INTO public; -- ERROR -IMPORT FOREIGN SCHEMA s1 LIMIT TO (t1) FROM SERVER s9 INTO public; --ERROR -IMPORT FOREIGN SCHEMA s1 EXCEPT (t1) FROM SERVER s9 INTO public; -- ERROR -IMPORT FOREIGN SCHEMA s1 EXCEPT (t1, t2) FROM SERVER s9 INTO public -OPTIONS (option1 'value1', option2 'value2'); -- ERROR - --- DROP FOREIGN TABLE -DROP FOREIGN TABLE no_table; -- ERROR -DROP FOREIGN TABLE IF EXISTS no_table; -DROP FOREIGN TABLE foreign_schema.foreign_table_1; - --- REASSIGN OWNED/DROP OWNED of foreign objects -REASSIGN OWNED BY regress_test_role TO regress_test_role2; -DROP OWNED BY regress_test_role2; -DROP OWNED BY regress_test_role2 CASCADE; - --- Foreign partition DDL stuff -CREATE TABLE fd_pt2 ( - c1 integer NOT NULL, - c2 text, - c3 date -) PARTITION BY LIST (c1); -CREATE FOREIGN TABLE fd_pt2_1 PARTITION OF fd_pt2 FOR VALUES IN (1) - SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -\d+ fd_pt2 -\d+ fd_pt2_1 - --- partition cannot have additional columns -DROP FOREIGN TABLE fd_pt2_1; -CREATE FOREIGN TABLE fd_pt2_1 ( - c1 integer NOT NULL, - c2 text, - c3 date, - c4 char -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -\d+ fd_pt2_1 -ALTER TABLE fd_pt2 ATTACH PARTITION fd_pt2_1 FOR VALUES IN (1); -- ERROR - -DROP FOREIGN TABLE fd_pt2_1; -\d+ fd_pt2 -CREATE FOREIGN TABLE fd_pt2_1 ( - c1 integer NOT NULL, - c2 text, - c3 date -) SERVER s0 OPTIONS (delimiter ',', quote '"', "be quoted" 'value'); -\d+ fd_pt2_1 --- no attach partition validation occurs for foreign tables -ALTER TABLE fd_pt2 ATTACH PARTITION fd_pt2_1 FOR VALUES IN (1); -\d+ fd_pt2 -\d+ fd_pt2_1 - --- cannot add column to a partition -ALTER TABLE fd_pt2_1 ADD c4 char; - --- ok to have a partition's own constraints though -ALTER TABLE fd_pt2_1 ALTER c3 SET NOT NULL; -ALTER TABLE fd_pt2_1 ADD CONSTRAINT p21chk CHECK (c2 <> ''); -\d+ fd_pt2 -\d+ fd_pt2_1 - --- cannot drop inherited NOT NULL constraint from a partition -ALTER TABLE fd_pt2_1 ALTER c1 DROP NOT NULL; - --- partition must have parent's constraints -ALTER TABLE fd_pt2 DETACH PARTITION fd_pt2_1; -ALTER TABLE fd_pt2 ALTER c2 SET NOT NULL; -\d+ fd_pt2 -\d+ fd_pt2_1 -ALTER TABLE fd_pt2 ATTACH PARTITION fd_pt2_1 FOR VALUES IN (1); -- ERROR -ALTER FOREIGN TABLE fd_pt2_1 ALTER c2 SET NOT NULL; -ALTER TABLE fd_pt2 ATTACH PARTITION fd_pt2_1 FOR VALUES IN (1); - -ALTER TABLE fd_pt2 DETACH PARTITION fd_pt2_1; -ALTER TABLE fd_pt2 ADD CONSTRAINT fd_pt2chk1 CHECK (c1 > 0); -\d+ fd_pt2 -\d+ fd_pt2_1 -ALTER TABLE fd_pt2 ATTACH PARTITION fd_pt2_1 FOR VALUES IN (1); -- ERROR -ALTER FOREIGN TABLE fd_pt2_1 ADD CONSTRAINT fd_pt2chk1 CHECK (c1 > 0); -ALTER TABLE fd_pt2 ATTACH PARTITION fd_pt2_1 FOR VALUES IN (1); - -DROP FOREIGN TABLE fd_pt2_1; -DROP TABLE fd_pt2; - --- foreign table cannot be part of partition tree made of temporary --- relations. -CREATE TEMP TABLE temp_parted (a int) PARTITION BY LIST (a); -CREATE FOREIGN TABLE foreign_part PARTITION OF temp_parted DEFAULT - SERVER s0; -- ERROR -CREATE FOREIGN TABLE foreign_part (a int) SERVER s0; -ALTER TABLE temp_parted ATTACH PARTITION foreign_part DEFAULT; -- ERROR -DROP FOREIGN TABLE foreign_part; -DROP TABLE temp_parted; - --- Cleanup -DROP SCHEMA foreign_schema CASCADE; -DROP ROLE regress_test_role; -- ERROR -DROP SERVER t1 CASCADE; -DROP USER MAPPING FOR regress_test_role SERVER s6; -DROP FOREIGN DATA WRAPPER foo CASCADE; -DROP SERVER s8 CASCADE; -DROP ROLE regress_test_indirect; -DROP ROLE regress_test_role; -DROP ROLE regress_unprivileged_role; -- ERROR -REVOKE ALL ON FOREIGN DATA WRAPPER postgresql FROM regress_unprivileged_role; -DROP ROLE regress_unprivileged_role; -DROP ROLE regress_test_role2; -DROP FOREIGN DATA WRAPPER postgresql CASCADE; -DROP FOREIGN DATA WRAPPER dummy CASCADE; -\c -DROP ROLE regress_foreign_data_user; - --- At this point we should have no wrappers, no servers, and no mappings. -SELECT fdwname, fdwhandler, fdwvalidator, fdwoptions FROM pg_foreign_data_wrapper; -SELECT srvname, srvoptions FROM pg_foreign_server; -SELECT * FROM pg_user_mapping; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fforeign_key.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fforeign_key.sql deleted file mode 100644 index 725a59a525..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fforeign_key.sql +++ /dev/null @@ -1,2015 +0,0 @@ --- --- FOREIGN KEY --- - --- MATCH FULL --- --- First test, check and cascade --- -CREATE TABLE PKTABLE ( ptest1 int PRIMARY KEY, ptest2 text ); -CREATE TABLE FKTABLE ( ftest1 int REFERENCES PKTABLE MATCH FULL ON DELETE CASCADE ON UPDATE CASCADE, ftest2 int ); - --- Insert test data into PKTABLE -INSERT INTO PKTABLE VALUES (1, 'Test1'); -INSERT INTO PKTABLE VALUES (2, 'Test2'); -INSERT INTO PKTABLE VALUES (3, 'Test3'); -INSERT INTO PKTABLE VALUES (4, 'Test4'); -INSERT INTO PKTABLE VALUES (5, 'Test5'); - --- Insert successful rows into FK TABLE -INSERT INTO FKTABLE VALUES (1, 2); -INSERT INTO FKTABLE VALUES (2, 3); -INSERT INTO FKTABLE VALUES (3, 4); -INSERT INTO FKTABLE VALUES (NULL, 1); - --- Insert a failed row into FK TABLE -INSERT INTO FKTABLE VALUES (100, 2); - --- Check FKTABLE -SELECT * FROM FKTABLE; - --- Delete a row from PK TABLE -DELETE FROM PKTABLE WHERE ptest1=1; - --- Check FKTABLE for removal of matched row -SELECT * FROM FKTABLE; - --- Update a row from PK TABLE -UPDATE PKTABLE SET ptest1=1 WHERE ptest1=2; - --- Check FKTABLE for update of matched row -SELECT * FROM FKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- --- check set NULL and table constraint on multiple columns --- -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 text, PRIMARY KEY(ptest1, ptest2) ); -CREATE TABLE FKTABLE ( ftest1 int, ftest2 int, ftest3 int, CONSTRAINT constrname FOREIGN KEY(ftest1, ftest2) - REFERENCES PKTABLE MATCH FULL ON DELETE SET NULL ON UPDATE SET NULL); - --- Test comments -COMMENT ON CONSTRAINT constrname_wrong ON FKTABLE IS 'fk constraint comment'; -COMMENT ON CONSTRAINT constrname ON FKTABLE IS 'fk constraint comment'; -COMMENT ON CONSTRAINT constrname ON FKTABLE IS NULL; - --- Insert test data into PKTABLE -INSERT INTO PKTABLE VALUES (1, 2, 'Test1'); -INSERT INTO PKTABLE VALUES (1, 3, 'Test1-2'); -INSERT INTO PKTABLE VALUES (2, 4, 'Test2'); -INSERT INTO PKTABLE VALUES (3, 6, 'Test3'); -INSERT INTO PKTABLE VALUES (4, 8, 'Test4'); -INSERT INTO PKTABLE VALUES (5, 10, 'Test5'); - --- Insert successful rows into FK TABLE -INSERT INTO FKTABLE VALUES (1, 2, 4); -INSERT INTO FKTABLE VALUES (1, 3, 5); -INSERT INTO FKTABLE VALUES (2, 4, 8); -INSERT INTO FKTABLE VALUES (3, 6, 12); -INSERT INTO FKTABLE VALUES (NULL, NULL, 0); - --- Insert failed rows into FK TABLE -INSERT INTO FKTABLE VALUES (100, 2, 4); -INSERT INTO FKTABLE VALUES (2, 2, 4); -INSERT INTO FKTABLE VALUES (NULL, 2, 4); -INSERT INTO FKTABLE VALUES (1, NULL, 4); - --- Check FKTABLE -SELECT * FROM FKTABLE; - --- Delete a row from PK TABLE -DELETE FROM PKTABLE WHERE ptest1=1 and ptest2=2; - --- Check FKTABLE for removal of matched row -SELECT * FROM FKTABLE; - --- Delete another row from PK TABLE -DELETE FROM PKTABLE WHERE ptest1=5 and ptest2=10; - --- Check FKTABLE (should be no change) -SELECT * FROM FKTABLE; - --- Update a row from PK TABLE -UPDATE PKTABLE SET ptest1=1 WHERE ptest1=2; - --- Check FKTABLE for update of matched row -SELECT * FROM FKTABLE; - --- Check update with part of key null -UPDATE FKTABLE SET ftest1 = NULL WHERE ftest1 = 1; - --- Check update with old and new key values equal -UPDATE FKTABLE SET ftest1 = 1 WHERE ftest1 = 1; - --- Try altering the column type where foreign keys are involved -ALTER TABLE PKTABLE ALTER COLUMN ptest1 TYPE bigint; -ALTER TABLE FKTABLE ALTER COLUMN ftest1 TYPE bigint; -SELECT * FROM PKTABLE; -SELECT * FROM FKTABLE; - -DROP TABLE PKTABLE CASCADE; -DROP TABLE FKTABLE; - --- --- check set default and table constraint on multiple columns --- -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 text, PRIMARY KEY(ptest1, ptest2) ); -CREATE TABLE FKTABLE ( ftest1 int DEFAULT -1, ftest2 int DEFAULT -2, ftest3 int, CONSTRAINT constrname2 FOREIGN KEY(ftest1, ftest2) - REFERENCES PKTABLE MATCH FULL ON DELETE SET DEFAULT ON UPDATE SET DEFAULT); - --- Insert a value in PKTABLE for default -INSERT INTO PKTABLE VALUES (-1, -2, 'The Default!'); - --- Insert test data into PKTABLE -INSERT INTO PKTABLE VALUES (1, 2, 'Test1'); -INSERT INTO PKTABLE VALUES (1, 3, 'Test1-2'); -INSERT INTO PKTABLE VALUES (2, 4, 'Test2'); -INSERT INTO PKTABLE VALUES (3, 6, 'Test3'); -INSERT INTO PKTABLE VALUES (4, 8, 'Test4'); -INSERT INTO PKTABLE VALUES (5, 10, 'Test5'); - --- Insert successful rows into FK TABLE -INSERT INTO FKTABLE VALUES (1, 2, 4); -INSERT INTO FKTABLE VALUES (1, 3, 5); -INSERT INTO FKTABLE VALUES (2, 4, 8); -INSERT INTO FKTABLE VALUES (3, 6, 12); -INSERT INTO FKTABLE VALUES (NULL, NULL, 0); - --- Insert failed rows into FK TABLE -INSERT INTO FKTABLE VALUES (100, 2, 4); -INSERT INTO FKTABLE VALUES (2, 2, 4); -INSERT INTO FKTABLE VALUES (NULL, 2, 4); -INSERT INTO FKTABLE VALUES (1, NULL, 4); - --- Check FKTABLE -SELECT * FROM FKTABLE; - --- Delete a row from PK TABLE -DELETE FROM PKTABLE WHERE ptest1=1 and ptest2=2; - --- Check FKTABLE to check for removal -SELECT * FROM FKTABLE; - --- Delete another row from PK TABLE -DELETE FROM PKTABLE WHERE ptest1=5 and ptest2=10; - --- Check FKTABLE (should be no change) -SELECT * FROM FKTABLE; - --- Update a row from PK TABLE -UPDATE PKTABLE SET ptest1=1 WHERE ptest1=2; - --- Check FKTABLE for update of matched row -SELECT * FROM FKTABLE; - --- this should fail for lack of CASCADE -DROP TABLE PKTABLE; -DROP TABLE PKTABLE CASCADE; -DROP TABLE FKTABLE; - - --- --- First test, check with no on delete or on update --- -CREATE TABLE PKTABLE ( ptest1 int PRIMARY KEY, ptest2 text ); -CREATE TABLE FKTABLE ( ftest1 int REFERENCES PKTABLE MATCH FULL, ftest2 int ); - --- Insert test data into PKTABLE -INSERT INTO PKTABLE VALUES (1, 'Test1'); -INSERT INTO PKTABLE VALUES (2, 'Test2'); -INSERT INTO PKTABLE VALUES (3, 'Test3'); -INSERT INTO PKTABLE VALUES (4, 'Test4'); -INSERT INTO PKTABLE VALUES (5, 'Test5'); - --- Insert successful rows into FK TABLE -INSERT INTO FKTABLE VALUES (1, 2); -INSERT INTO FKTABLE VALUES (2, 3); -INSERT INTO FKTABLE VALUES (3, 4); -INSERT INTO FKTABLE VALUES (NULL, 1); - --- Insert a failed row into FK TABLE -INSERT INTO FKTABLE VALUES (100, 2); - --- Check FKTABLE -SELECT * FROM FKTABLE; - --- Check PKTABLE -SELECT * FROM PKTABLE; - --- Delete a row from PK TABLE (should fail) -DELETE FROM PKTABLE WHERE ptest1=1; - --- Delete a row from PK TABLE (should succeed) -DELETE FROM PKTABLE WHERE ptest1=5; - --- Check PKTABLE for deletes -SELECT * FROM PKTABLE; - --- Update a row from PK TABLE (should fail) -UPDATE PKTABLE SET ptest1=0 WHERE ptest1=2; - --- Update a row from PK TABLE (should succeed) -UPDATE PKTABLE SET ptest1=0 WHERE ptest1=4; - --- Check PKTABLE for updates -SELECT * FROM PKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- --- Check initial check upon ALTER TABLE --- -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, PRIMARY KEY(ptest1, ptest2) ); -CREATE TABLE FKTABLE ( ftest1 int, ftest2 int ); - -INSERT INTO PKTABLE VALUES (1, 2); -INSERT INTO FKTABLE VALUES (1, NULL); - -ALTER TABLE FKTABLE ADD FOREIGN KEY(ftest1, ftest2) REFERENCES PKTABLE MATCH FULL; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - - --- MATCH SIMPLE - --- Base test restricting update/delete -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 int, ptest4 text, PRIMARY KEY(ptest1, ptest2, ptest3) ); -CREATE TABLE FKTABLE ( ftest1 int, ftest2 int, ftest3 int, ftest4 int, CONSTRAINT constrname3 - FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE); - --- Insert Primary Key values -INSERT INTO PKTABLE VALUES (1, 2, 3, 'test1'); -INSERT INTO PKTABLE VALUES (1, 3, 3, 'test2'); -INSERT INTO PKTABLE VALUES (2, 3, 4, 'test3'); -INSERT INTO PKTABLE VALUES (2, 4, 5, 'test4'); - --- Insert Foreign Key values -INSERT INTO FKTABLE VALUES (1, 2, 3, 1); -INSERT INTO FKTABLE VALUES (NULL, 2, 3, 2); -INSERT INTO FKTABLE VALUES (2, NULL, 3, 3); -INSERT INTO FKTABLE VALUES (NULL, 2, 7, 4); -INSERT INTO FKTABLE VALUES (NULL, 3, 4, 5); - --- Insert a failed values -INSERT INTO FKTABLE VALUES (1, 2, 7, 6); - --- Show FKTABLE -SELECT * from FKTABLE; - --- Try to update something that should fail -UPDATE PKTABLE set ptest2=5 where ptest2=2; - --- Try to update something that should succeed -UPDATE PKTABLE set ptest1=1 WHERE ptest2=3; - --- Try to delete something that should fail -DELETE FROM PKTABLE where ptest1=1 and ptest2=2 and ptest3=3; - --- Try to delete something that should work -DELETE FROM PKTABLE where ptest1=2; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; - -SELECT * from FKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- restrict with null values -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 int, ptest4 text, UNIQUE(ptest1, ptest2, ptest3) ); -CREATE TABLE FKTABLE ( ftest1 int, ftest2 int, ftest3 int, ftest4 int, CONSTRAINT constrname3 - FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE (ptest1, ptest2, ptest3)); - -INSERT INTO PKTABLE VALUES (1, 2, 3, 'test1'); -INSERT INTO PKTABLE VALUES (1, 3, NULL, 'test2'); -INSERT INTO PKTABLE VALUES (2, NULL, 4, 'test3'); - -INSERT INTO FKTABLE VALUES (1, 2, 3, 1); - -DELETE FROM PKTABLE WHERE ptest1 = 2; - -SELECT * FROM PKTABLE; -SELECT * FROM FKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- cascade update/delete -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 int, ptest4 text, PRIMARY KEY(ptest1, ptest2, ptest3) ); -CREATE TABLE FKTABLE ( ftest1 int, ftest2 int, ftest3 int, ftest4 int, CONSTRAINT constrname3 - FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE - ON DELETE CASCADE ON UPDATE CASCADE); - --- Insert Primary Key values -INSERT INTO PKTABLE VALUES (1, 2, 3, 'test1'); -INSERT INTO PKTABLE VALUES (1, 3, 3, 'test2'); -INSERT INTO PKTABLE VALUES (2, 3, 4, 'test3'); -INSERT INTO PKTABLE VALUES (2, 4, 5, 'test4'); - --- Insert Foreign Key values -INSERT INTO FKTABLE VALUES (1, 2, 3, 1); -INSERT INTO FKTABLE VALUES (NULL, 2, 3, 2); -INSERT INTO FKTABLE VALUES (2, NULL, 3, 3); -INSERT INTO FKTABLE VALUES (NULL, 2, 7, 4); -INSERT INTO FKTABLE VALUES (NULL, 3, 4, 5); - --- Insert a failed values -INSERT INTO FKTABLE VALUES (1, 2, 7, 6); - --- Show FKTABLE -SELECT * from FKTABLE; - --- Try to update something that will cascade -UPDATE PKTABLE set ptest2=5 where ptest2=2; - --- Try to update something that should not cascade -UPDATE PKTABLE set ptest1=1 WHERE ptest2=3; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - --- Try to delete something that should cascade -DELETE FROM PKTABLE where ptest1=1 and ptest2=5 and ptest3=3; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - --- Try to delete something that should not have a cascade -DELETE FROM PKTABLE where ptest1=2; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- set null update / set default delete -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 int, ptest4 text, PRIMARY KEY(ptest1, ptest2, ptest3) ); -CREATE TABLE FKTABLE ( ftest1 int DEFAULT 0, ftest2 int, ftest3 int, ftest4 int, CONSTRAINT constrname3 - FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE - ON DELETE SET DEFAULT ON UPDATE SET NULL); - --- Insert Primary Key values -INSERT INTO PKTABLE VALUES (1, 2, 3, 'test1'); -INSERT INTO PKTABLE VALUES (1, 3, 3, 'test2'); -INSERT INTO PKTABLE VALUES (2, 3, 4, 'test3'); -INSERT INTO PKTABLE VALUES (2, 4, 5, 'test4'); - --- Insert Foreign Key values -INSERT INTO FKTABLE VALUES (1, 2, 3, 1); -INSERT INTO FKTABLE VALUES (2, 3, 4, 1); -INSERT INTO FKTABLE VALUES (NULL, 2, 3, 2); -INSERT INTO FKTABLE VALUES (2, NULL, 3, 3); -INSERT INTO FKTABLE VALUES (NULL, 2, 7, 4); -INSERT INTO FKTABLE VALUES (NULL, 3, 4, 5); - --- Insert a failed values -INSERT INTO FKTABLE VALUES (1, 2, 7, 6); - --- Show FKTABLE -SELECT * from FKTABLE; - --- Try to update something that will set null -UPDATE PKTABLE set ptest2=5 where ptest2=2; - --- Try to update something that should not set null -UPDATE PKTABLE set ptest2=2 WHERE ptest2=3 and ptest1=1; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - --- Try to delete something that should set default -DELETE FROM PKTABLE where ptest1=2 and ptest2=3 and ptest3=4; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - --- Try to delete something that should not set default -DELETE FROM PKTABLE where ptest2=5; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- set default update / set null delete -CREATE TABLE PKTABLE ( ptest1 int, ptest2 int, ptest3 int, ptest4 text, PRIMARY KEY(ptest1, ptest2, ptest3) ); -CREATE TABLE FKTABLE ( ftest1 int DEFAULT 0, ftest2 int DEFAULT -1, ftest3 int DEFAULT -2, ftest4 int, CONSTRAINT constrname3 - FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE - ON DELETE SET NULL ON UPDATE SET DEFAULT); - --- Insert Primary Key values -INSERT INTO PKTABLE VALUES (1, 2, 3, 'test1'); -INSERT INTO PKTABLE VALUES (1, 3, 3, 'test2'); -INSERT INTO PKTABLE VALUES (2, 3, 4, 'test3'); -INSERT INTO PKTABLE VALUES (2, 4, 5, 'test4'); -INSERT INTO PKTABLE VALUES (2, -1, 5, 'test5'); - --- Insert Foreign Key values -INSERT INTO FKTABLE VALUES (1, 2, 3, 1); -INSERT INTO FKTABLE VALUES (2, 3, 4, 1); -INSERT INTO FKTABLE VALUES (2, 4, 5, 1); -INSERT INTO FKTABLE VALUES (NULL, 2, 3, 2); -INSERT INTO FKTABLE VALUES (2, NULL, 3, 3); -INSERT INTO FKTABLE VALUES (NULL, 2, 7, 4); -INSERT INTO FKTABLE VALUES (NULL, 3, 4, 5); - --- Insert a failed values -INSERT INTO FKTABLE VALUES (1, 2, 7, 6); - --- Show FKTABLE -SELECT * from FKTABLE; - --- Try to update something that will fail -UPDATE PKTABLE set ptest2=5 where ptest2=2; - --- Try to update something that will set default -UPDATE PKTABLE set ptest1=0, ptest2=-1, ptest3=-2 where ptest2=2; -UPDATE PKTABLE set ptest2=10 where ptest2=4; - --- Try to update something that should not set default -UPDATE PKTABLE set ptest2=2 WHERE ptest2=3 and ptest1=1; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - --- Try to delete something that should set null -DELETE FROM PKTABLE where ptest1=2 and ptest2=3 and ptest3=4; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - --- Try to delete something that should not set null -DELETE FROM PKTABLE where ptest2=-1 and ptest3=5; - --- Show PKTABLE and FKTABLE -SELECT * from PKTABLE; -SELECT * from FKTABLE; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- Test for ON DELETE SET NULL/DEFAULT (column_list); -CREATE TABLE PKTABLE (tid int, id int, PRIMARY KEY (tid, id)); -CREATE TABLE FKTABLE (tid int, id int, foo int, FOREIGN KEY (tid, id) REFERENCES PKTABLE ON DELETE SET NULL (bar)); -CREATE TABLE FKTABLE (tid int, id int, foo int, FOREIGN KEY (tid, id) REFERENCES PKTABLE ON DELETE SET NULL (foo)); -CREATE TABLE FKTABLE (tid int, id int, foo int, FOREIGN KEY (tid, foo) REFERENCES PKTABLE ON UPDATE SET NULL (foo)); -CREATE TABLE FKTABLE ( - tid int, id int, - fk_id_del_set_null int, - fk_id_del_set_default int DEFAULT 0, - FOREIGN KEY (tid, fk_id_del_set_null) REFERENCES PKTABLE ON DELETE SET NULL (fk_id_del_set_null), - FOREIGN KEY (tid, fk_id_del_set_default) REFERENCES PKTABLE ON DELETE SET DEFAULT (fk_id_del_set_default) -); - -SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid = 'fktable'::regclass::oid ORDER BY oid; - -INSERT INTO PKTABLE VALUES (1, 0), (1, 1), (1, 2); -INSERT INTO FKTABLE VALUES - (1, 1, 1, NULL), - (1, 2, NULL, 2); - -DELETE FROM PKTABLE WHERE id = 1 OR id = 2; - -SELECT * FROM FKTABLE ORDER BY id; - -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - -CREATE TABLE PKTABLE (ptest1 int PRIMARY KEY); -CREATE TABLE FKTABLE_FAIL1 ( ftest1 int, CONSTRAINT fkfail1 FOREIGN KEY (ftest2) REFERENCES PKTABLE); -CREATE TABLE FKTABLE_FAIL2 ( ftest1 int, CONSTRAINT fkfail1 FOREIGN KEY (ftest1) REFERENCES PKTABLE(ptest2)); - -DROP TABLE FKTABLE_FAIL1; -DROP TABLE FKTABLE_FAIL2; -DROP TABLE PKTABLE; - --- Test for referencing column number smaller than referenced constraint -CREATE TABLE PKTABLE (ptest1 int, ptest2 int, UNIQUE(ptest1, ptest2)); -CREATE TABLE FKTABLE_FAIL1 (ftest1 int REFERENCES pktable(ptest1)); - -DROP TABLE FKTABLE_FAIL1; -DROP TABLE PKTABLE; - --- --- Tests for mismatched types --- --- Basic one column, two table setup -CREATE TABLE PKTABLE (ptest1 int PRIMARY KEY); -INSERT INTO PKTABLE VALUES(42); --- This next should fail, because int=inet does not exist -CREATE TABLE FKTABLE (ftest1 inet REFERENCES pktable); --- This should also fail for the same reason, but here we --- give the column name -CREATE TABLE FKTABLE (ftest1 inet REFERENCES pktable(ptest1)); --- This should succeed, even though they are different types, --- because int=int8 exists and is a member of the integer opfamily -CREATE TABLE FKTABLE (ftest1 int8 REFERENCES pktable); --- Check it actually works -INSERT INTO FKTABLE VALUES(42); -- should succeed -INSERT INTO FKTABLE VALUES(43); -- should fail -UPDATE FKTABLE SET ftest1 = ftest1; -- should succeed -UPDATE FKTABLE SET ftest1 = ftest1 + 1; -- should fail -DROP TABLE FKTABLE; --- This should fail, because we'd have to cast numeric to int which is --- not an implicit coercion (or use numeric=numeric, but that's not part --- of the integer opfamily) -CREATE TABLE FKTABLE (ftest1 numeric REFERENCES pktable); -DROP TABLE PKTABLE; --- On the other hand, this should work because int implicitly promotes to --- numeric, and we allow promotion on the FK side -CREATE TABLE PKTABLE (ptest1 numeric PRIMARY KEY); -INSERT INTO PKTABLE VALUES(42); -CREATE TABLE FKTABLE (ftest1 int REFERENCES pktable); --- Check it actually works -INSERT INTO FKTABLE VALUES(42); -- should succeed -INSERT INTO FKTABLE VALUES(43); -- should fail -UPDATE FKTABLE SET ftest1 = ftest1; -- should succeed -UPDATE FKTABLE SET ftest1 = ftest1 + 1; -- should fail -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- Two columns, two tables -CREATE TABLE PKTABLE (ptest1 int, ptest2 inet, PRIMARY KEY(ptest1, ptest2)); --- This should fail, because we just chose really odd types -CREATE TABLE FKTABLE (ftest1 cidr, ftest2 timestamp, FOREIGN KEY(ftest1, ftest2) REFERENCES pktable); --- Again, so should this... -CREATE TABLE FKTABLE (ftest1 cidr, ftest2 timestamp, FOREIGN KEY(ftest1, ftest2) REFERENCES pktable(ptest1, ptest2)); --- This fails because we mixed up the column ordering -CREATE TABLE FKTABLE (ftest1 int, ftest2 inet, FOREIGN KEY(ftest2, ftest1) REFERENCES pktable); --- As does this... -CREATE TABLE FKTABLE (ftest1 int, ftest2 inet, FOREIGN KEY(ftest2, ftest1) REFERENCES pktable(ptest1, ptest2)); --- And again.. -CREATE TABLE FKTABLE (ftest1 int, ftest2 inet, FOREIGN KEY(ftest1, ftest2) REFERENCES pktable(ptest2, ptest1)); --- This works... -CREATE TABLE FKTABLE (ftest1 int, ftest2 inet, FOREIGN KEY(ftest2, ftest1) REFERENCES pktable(ptest2, ptest1)); -DROP TABLE FKTABLE; --- As does this -CREATE TABLE FKTABLE (ftest1 int, ftest2 inet, FOREIGN KEY(ftest1, ftest2) REFERENCES pktable(ptest1, ptest2)); -DROP TABLE FKTABLE; -DROP TABLE PKTABLE; - --- Two columns, same table --- Make sure this still works... -CREATE TABLE PKTABLE (ptest1 int, ptest2 inet, ptest3 int, ptest4 inet, PRIMARY KEY(ptest1, ptest2), FOREIGN KEY(ptest3, -ptest4) REFERENCES pktable(ptest1, ptest2)); -DROP TABLE PKTABLE; --- And this, -CREATE TABLE PKTABLE (ptest1 int, ptest2 inet, ptest3 int, ptest4 inet, PRIMARY KEY(ptest1, ptest2), FOREIGN KEY(ptest3, -ptest4) REFERENCES pktable); -DROP TABLE PKTABLE; --- This shouldn't (mixed up columns) -CREATE TABLE PKTABLE (ptest1 int, ptest2 inet, ptest3 int, ptest4 inet, PRIMARY KEY(ptest1, ptest2), FOREIGN KEY(ptest3, -ptest4) REFERENCES pktable(ptest2, ptest1)); --- Nor should this... (same reason, we have 4,3 referencing 1,2 which mismatches types -CREATE TABLE PKTABLE (ptest1 int, ptest2 inet, ptest3 int, ptest4 inet, PRIMARY KEY(ptest1, ptest2), FOREIGN KEY(ptest4, -ptest3) REFERENCES pktable(ptest1, ptest2)); --- Not this one either... Same as the last one except we didn't defined the columns being referenced. -CREATE TABLE PKTABLE (ptest1 int, ptest2 inet, ptest3 int, ptest4 inet, PRIMARY KEY(ptest1, ptest2), FOREIGN KEY(ptest4, -ptest3) REFERENCES pktable); - --- --- Now some cases with inheritance --- Basic 2 table case: 1 column of matching types. -create table pktable_base (base1 int not null); -create table pktable (ptest1 int, primary key(base1), unique(base1, ptest1)) inherits (pktable_base); -create table fktable (ftest1 int references pktable(base1)); --- now some ins, upd, del -insert into pktable(base1) values (1); -insert into pktable(base1) values (2); --- let's insert a non-existent fktable value -insert into fktable(ftest1) values (3); --- let's make a valid row for that -insert into pktable(base1) values (3); -insert into fktable(ftest1) values (3); --- let's try removing a row that should fail from pktable -delete from pktable where base1>2; --- okay, let's try updating all of the base1 values to *4 --- which should fail. -update pktable set base1=base1*4; --- okay, let's try an update that should work. -update pktable set base1=base1*4 where base1<3; --- and a delete that should work -delete from pktable where base1>3; --- cleanup -drop table fktable; -delete from pktable; - --- Now 2 columns 2 tables, matching types -create table fktable (ftest1 int, ftest2 int, foreign key(ftest1, ftest2) references pktable(base1, ptest1)); --- now some ins, upd, del -insert into pktable(base1, ptest1) values (1, 1); -insert into pktable(base1, ptest1) values (2, 2); --- let's insert a non-existent fktable value -insert into fktable(ftest1, ftest2) values (3, 1); --- let's make a valid row for that -insert into pktable(base1,ptest1) values (3, 1); -insert into fktable(ftest1, ftest2) values (3, 1); --- let's try removing a row that should fail from pktable -delete from pktable where base1>2; --- okay, let's try updating all of the base1 values to *4 --- which should fail. -update pktable set base1=base1*4; --- okay, let's try an update that should work. -update pktable set base1=base1*4 where base1<3; --- and a delete that should work -delete from pktable where base1>3; --- cleanup -drop table fktable; -drop table pktable; -drop table pktable_base; - --- Now we'll do one all in 1 table with 2 columns of matching types -create table pktable_base(base1 int not null, base2 int); -create table pktable(ptest1 int, ptest2 int, primary key(base1, ptest1), foreign key(base2, ptest2) references - pktable(base1, ptest1)) inherits (pktable_base); -insert into pktable (base1, ptest1, base2, ptest2) values (1, 1, 1, 1); -insert into pktable (base1, ptest1, base2, ptest2) values (2, 1, 1, 1); -insert into pktable (base1, ptest1, base2, ptest2) values (2, 2, 2, 1); -insert into pktable (base1, ptest1, base2, ptest2) values (1, 3, 2, 2); --- fails (3,2) isn't in base1, ptest1 -insert into pktable (base1, ptest1, base2, ptest2) values (2, 3, 3, 2); --- fails (2,2) is being referenced -delete from pktable where base1=2; --- fails (1,1) is being referenced (twice) -update pktable set base1=3 where base1=1; --- this sequence of two deletes will work, since after the first there will be no (2,*) references -delete from pktable where base2=2; -delete from pktable where base1=2; -drop table pktable; -drop table pktable_base; - --- 2 columns (2 tables), mismatched types -create table pktable_base(base1 int not null); -create table pktable(ptest1 inet, primary key(base1, ptest1)) inherits (pktable_base); --- just generally bad types (with and without column references on the referenced table) -create table fktable(ftest1 cidr, ftest2 int[], foreign key (ftest1, ftest2) references pktable); -create table fktable(ftest1 cidr, ftest2 int[], foreign key (ftest1, ftest2) references pktable(base1, ptest1)); --- let's mix up which columns reference which -create table fktable(ftest1 int, ftest2 inet, foreign key(ftest2, ftest1) references pktable); -create table fktable(ftest1 int, ftest2 inet, foreign key(ftest2, ftest1) references pktable(base1, ptest1)); -create table fktable(ftest1 int, ftest2 inet, foreign key(ftest1, ftest2) references pktable(ptest1, base1)); -drop table pktable; -drop table pktable_base; - --- 2 columns (1 table), mismatched types -create table pktable_base(base1 int not null, base2 int); -create table pktable(ptest1 inet, ptest2 inet[], primary key(base1, ptest1), foreign key(base2, ptest2) references - pktable(base1, ptest1)) inherits (pktable_base); -create table pktable(ptest1 inet, ptest2 inet, primary key(base1, ptest1), foreign key(base2, ptest2) references - pktable(ptest1, base1)) inherits (pktable_base); -create table pktable(ptest1 inet, ptest2 inet, primary key(base1, ptest1), foreign key(ptest2, base2) references - pktable(base1, ptest1)) inherits (pktable_base); -create table pktable(ptest1 inet, ptest2 inet, primary key(base1, ptest1), foreign key(ptest2, base2) references - pktable(base1, ptest1)) inherits (pktable_base); -drop table pktable; -drop table pktable_base; - --- --- Deferrable constraints --- - --- deferrable, explicitly deferred -CREATE TABLE pktable ( - id INT4 PRIMARY KEY, - other INT4 -); - -CREATE TABLE fktable ( - id INT4 PRIMARY KEY, - fk INT4 REFERENCES pktable DEFERRABLE -); - --- default to immediate: should fail -INSERT INTO fktable VALUES (5, 10); - --- explicitly defer the constraint -BEGIN; - -SET CONSTRAINTS ALL DEFERRED; - -INSERT INTO fktable VALUES (10, 15); -INSERT INTO pktable VALUES (15, 0); -- make the FK insert valid - -COMMIT; - -DROP TABLE fktable, pktable; - --- deferrable, initially deferred -CREATE TABLE pktable ( - id INT4 PRIMARY KEY, - other INT4 -); - -CREATE TABLE fktable ( - id INT4 PRIMARY KEY, - fk INT4 REFERENCES pktable DEFERRABLE INITIALLY DEFERRED -); - --- default to deferred, should succeed -BEGIN; - -INSERT INTO fktable VALUES (100, 200); -INSERT INTO pktable VALUES (200, 500); -- make the FK insert valid - -COMMIT; - --- default to deferred, explicitly make immediate -BEGIN; - -SET CONSTRAINTS ALL IMMEDIATE; - --- should fail -INSERT INTO fktable VALUES (500, 1000); - -COMMIT; - -DROP TABLE fktable, pktable; - --- tricky behavior: according to SQL99, if a deferred constraint is set --- to 'immediate' mode, it should be checked for validity *immediately*, --- not when the current transaction commits (i.e. the mode change applies --- retroactively) -CREATE TABLE pktable ( - id INT4 PRIMARY KEY, - other INT4 -); - -CREATE TABLE fktable ( - id INT4 PRIMARY KEY, - fk INT4 REFERENCES pktable DEFERRABLE -); - -BEGIN; - -SET CONSTRAINTS ALL DEFERRED; - --- should succeed, for now -INSERT INTO fktable VALUES (1000, 2000); - --- should cause transaction abort, due to preceding error -SET CONSTRAINTS ALL IMMEDIATE; - -INSERT INTO pktable VALUES (2000, 3); -- too late - -COMMIT; - -DROP TABLE fktable, pktable; - --- deferrable, initially deferred -CREATE TABLE pktable ( - id INT4 PRIMARY KEY, - other INT4 -); - -CREATE TABLE fktable ( - id INT4 PRIMARY KEY, - fk INT4 REFERENCES pktable DEFERRABLE INITIALLY DEFERRED -); - -BEGIN; - --- no error here -INSERT INTO fktable VALUES (100, 200); - --- error here on commit -COMMIT; - -DROP TABLE pktable, fktable; - --- test notice about expensive referential integrity checks, --- where the index cannot be used because of type incompatibilities. - -CREATE TEMP TABLE pktable ( - id1 INT4 PRIMARY KEY, - id2 VARCHAR(4) UNIQUE, - id3 REAL UNIQUE, - UNIQUE(id1, id2, id3) -); - -CREATE TEMP TABLE fktable ( - x1 INT4 REFERENCES pktable(id1), - x2 VARCHAR(4) REFERENCES pktable(id2), - x3 REAL REFERENCES pktable(id3), - x4 TEXT, - x5 INT2 -); - --- check individual constraints with alter table. - --- should fail - --- varchar does not promote to real -ALTER TABLE fktable ADD CONSTRAINT fk_2_3 -FOREIGN KEY (x2) REFERENCES pktable(id3); - --- nor to int4 -ALTER TABLE fktable ADD CONSTRAINT fk_2_1 -FOREIGN KEY (x2) REFERENCES pktable(id1); - --- real does not promote to int4 -ALTER TABLE fktable ADD CONSTRAINT fk_3_1 -FOREIGN KEY (x3) REFERENCES pktable(id1); - --- int4 does not promote to text -ALTER TABLE fktable ADD CONSTRAINT fk_1_2 -FOREIGN KEY (x1) REFERENCES pktable(id2); - --- should succeed - --- int4 promotes to real -ALTER TABLE fktable ADD CONSTRAINT fk_1_3 -FOREIGN KEY (x1) REFERENCES pktable(id3); - --- text is compatible with varchar -ALTER TABLE fktable ADD CONSTRAINT fk_4_2 -FOREIGN KEY (x4) REFERENCES pktable(id2); - --- int2 is part of integer opfamily as of 8.0 -ALTER TABLE fktable ADD CONSTRAINT fk_5_1 -FOREIGN KEY (x5) REFERENCES pktable(id1); - --- check multikey cases, especially out-of-order column lists - --- these should work - -ALTER TABLE fktable ADD CONSTRAINT fk_123_123 -FOREIGN KEY (x1,x2,x3) REFERENCES pktable(id1,id2,id3); - -ALTER TABLE fktable ADD CONSTRAINT fk_213_213 -FOREIGN KEY (x2,x1,x3) REFERENCES pktable(id2,id1,id3); - -ALTER TABLE fktable ADD CONSTRAINT fk_253_213 -FOREIGN KEY (x2,x5,x3) REFERENCES pktable(id2,id1,id3); - --- these should fail - -ALTER TABLE fktable ADD CONSTRAINT fk_123_231 -FOREIGN KEY (x1,x2,x3) REFERENCES pktable(id2,id3,id1); - -ALTER TABLE fktable ADD CONSTRAINT fk_241_132 -FOREIGN KEY (x2,x4,x1) REFERENCES pktable(id1,id3,id2); - -DROP TABLE pktable, fktable; - --- test a tricky case: we can elide firing the FK check trigger during --- an UPDATE if the UPDATE did not change the foreign key --- field. However, we can't do this if our transaction was the one that --- created the updated row and the trigger is deferred, since our UPDATE --- will have invalidated the original newly-inserted tuple, and therefore --- cause the on-INSERT RI trigger not to be fired. - -CREATE TEMP TABLE pktable ( - id int primary key, - other int -); - -CREATE TEMP TABLE fktable ( - id int primary key, - fk int references pktable deferrable initially deferred -); - -INSERT INTO pktable VALUES (5, 10); - -BEGIN; - --- doesn't match PK, but no error yet -INSERT INTO fktable VALUES (0, 20); - --- don't change FK -UPDATE fktable SET id = id + 1; - --- should catch error from initial INSERT -COMMIT; - --- check same case when insert is in a different subtransaction than update - -BEGIN; - --- doesn't match PK, but no error yet -INSERT INTO fktable VALUES (0, 20); - --- UPDATE will be in a subxact -SAVEPOINT savept1; - --- don't change FK -UPDATE fktable SET id = id + 1; - --- should catch error from initial INSERT -COMMIT; - -BEGIN; - --- INSERT will be in a subxact -SAVEPOINT savept1; - --- doesn't match PK, but no error yet -INSERT INTO fktable VALUES (0, 20); - -RELEASE SAVEPOINT savept1; - --- don't change FK -UPDATE fktable SET id = id + 1; - --- should catch error from initial INSERT -COMMIT; - -BEGIN; - --- doesn't match PK, but no error yet -INSERT INTO fktable VALUES (0, 20); - --- UPDATE will be in a subxact -SAVEPOINT savept1; - --- don't change FK -UPDATE fktable SET id = id + 1; - --- Roll back the UPDATE -ROLLBACK TO savept1; - --- should catch error from initial INSERT -COMMIT; - --- --- check ALTER CONSTRAINT --- - -INSERT INTO fktable VALUES (1, 5); - -ALTER TABLE fktable ALTER CONSTRAINT fktable_fk_fkey DEFERRABLE INITIALLY IMMEDIATE; - -BEGIN; - --- doesn't match FK, should throw error now -UPDATE pktable SET id = 10 WHERE id = 5; - -COMMIT; - -BEGIN; - --- doesn't match PK, should throw error now -INSERT INTO fktable VALUES (0, 20); - -COMMIT; - --- try additional syntax -ALTER TABLE fktable ALTER CONSTRAINT fktable_fk_fkey NOT DEFERRABLE; --- illegal option -ALTER TABLE fktable ALTER CONSTRAINT fktable_fk_fkey NOT DEFERRABLE INITIALLY DEFERRED; - --- test order of firing of FK triggers when several RI-induced changes need to --- be made to the same row. This was broken by subtransaction-related --- changes in 8.0. - -CREATE TEMP TABLE users ( - id INT PRIMARY KEY, - name VARCHAR NOT NULL -); - -INSERT INTO users VALUES (1, 'Jozko'); -INSERT INTO users VALUES (2, 'Ferko'); -INSERT INTO users VALUES (3, 'Samko'); - -CREATE TEMP TABLE tasks ( - id INT PRIMARY KEY, - owner INT REFERENCES users ON UPDATE CASCADE ON DELETE SET NULL, - worker INT REFERENCES users ON UPDATE CASCADE ON DELETE SET NULL, - checked_by INT REFERENCES users ON UPDATE CASCADE ON DELETE SET NULL -); - -INSERT INTO tasks VALUES (1,1,NULL,NULL); -INSERT INTO tasks VALUES (2,2,2,NULL); -INSERT INTO tasks VALUES (3,3,3,3); - -SELECT * FROM tasks; - -UPDATE users SET id = 4 WHERE id = 3; - -SELECT * FROM tasks; - -DELETE FROM users WHERE id = 4; - -SELECT * FROM tasks; - --- could fail with only 2 changes to make, if row was already updated -BEGIN; -UPDATE tasks set id=id WHERE id=2; -SELECT * FROM tasks; -DELETE FROM users WHERE id = 2; -SELECT * FROM tasks; -COMMIT; - --- --- Test self-referential FK with CASCADE (bug #6268) --- -create temp table selfref ( - a int primary key, - b int, - foreign key (b) references selfref (a) - on update cascade on delete cascade -); - -insert into selfref (a, b) -values - (0, 0), - (1, 1); - -begin; - update selfref set a = 123 where a = 0; - select a, b from selfref; - update selfref set a = 456 where a = 123; - select a, b from selfref; -commit; - --- --- Test that SET DEFAULT actions recognize updates to default values --- -create temp table defp (f1 int primary key); -create temp table defc (f1 int default 0 - references defp on delete set default); -insert into defp values (0), (1), (2); -insert into defc values (2); -select * from defc; -delete from defp where f1 = 2; -select * from defc; -delete from defp where f1 = 0; -- fail -alter table defc alter column f1 set default 1; -delete from defp where f1 = 0; -select * from defc; -delete from defp where f1 = 1; -- fail - --- --- Test the difference between NO ACTION and RESTRICT --- -create temp table pp (f1 int primary key); -create temp table cc (f1 int references pp on update no action on delete no action); -insert into pp values(12); -insert into pp values(11); -update pp set f1=f1+1; -insert into cc values(13); -update pp set f1=f1+1; -update pp set f1=f1+1; -- fail -delete from pp where f1 = 13; -- fail -drop table pp, cc; - -create temp table pp (f1 int primary key); -create temp table cc (f1 int references pp on update restrict on delete restrict); -insert into pp values(12); -insert into pp values(11); -update pp set f1=f1+1; -insert into cc values(13); -update pp set f1=f1+1; -- fail -delete from pp where f1 = 13; -- fail -drop table pp, cc; - --- --- Test interaction of foreign-key optimization with rules (bug #14219) --- -create temp table t1 (a integer primary key, b text); -create temp table t2 (a integer primary key, b integer references t1); -create rule r1 as on delete to t1 do delete from t2 where t2.b = old.a; - -explain (costs off) delete from t1 where a = 1; -delete from t1 where a = 1; - --- Test a primary key with attributes located in later attnum positions --- compared to the fk attributes. -create table pktable2 (a int, b int, c int, d int, e int, primary key (d, e)); -create table fktable2 (d int, e int, foreign key (d, e) references pktable2); -insert into pktable2 values (1, 2, 3, 4, 5); -insert into fktable2 values (4, 5); -delete from pktable2; -update pktable2 set d = 5; -drop table pktable2, fktable2; - --- Test truncation of long foreign key names -create table pktable1 (a int primary key); -create table pktable2 (a int, b int, primary key (a, b)); -create table fktable2 ( - a int, - b int, - very_very_long_column_name_to_exceed_63_characters int, - foreign key (very_very_long_column_name_to_exceed_63_characters) references pktable1, - foreign key (a, very_very_long_column_name_to_exceed_63_characters) references pktable2, - foreign key (a, very_very_long_column_name_to_exceed_63_characters) references pktable2 -); -select conname from pg_constraint where conrelid = 'fktable2'::regclass order by conname; -drop table pktable1, pktable2, fktable2; - --- --- Test deferred FK check on a tuple deleted by a rolled-back subtransaction --- -create table pktable2(f1 int primary key); -create table fktable2(f1 int references pktable2 deferrable initially deferred); -insert into pktable2 values(1); - -begin; -insert into fktable2 values(1); -savepoint x; -delete from fktable2; -rollback to x; -commit; - -begin; -insert into fktable2 values(2); -savepoint x; -delete from fktable2; -rollback to x; -commit; -- fail - --- --- Test that we prevent dropping FK constraint with pending trigger events --- -begin; -insert into fktable2 values(2); -alter table fktable2 drop constraint fktable2_f1_fkey; -commit; - -begin; -delete from pktable2 where f1 = 1; -alter table fktable2 drop constraint fktable2_f1_fkey; -commit; - -drop table pktable2, fktable2; - --- --- Test keys that "look" different but compare as equal --- -create table pktable2 (a float8, b float8, primary key (a, b)); -create table fktable2 (x float8, y float8, foreign key (x, y) references pktable2 (a, b) on update cascade); - -insert into pktable2 values ('-0', '-0'); -insert into fktable2 values ('-0', '-0'); - -select * from pktable2; -select * from fktable2; - -update pktable2 set a = '0' where a = '-0'; - -select * from pktable2; --- should have updated fktable2.x -select * from fktable2; - -drop table pktable2, fktable2; - - --- --- Foreign keys and partitioned tables --- - --- Creation of a partitioned hierarchy with irregular definitions -CREATE TABLE fk_notpartitioned_pk (fdrop1 int, a int, fdrop2 int, b int, - PRIMARY KEY (a, b)); -ALTER TABLE fk_notpartitioned_pk DROP COLUMN fdrop1, DROP COLUMN fdrop2; -CREATE TABLE fk_partitioned_fk (b int, fdrop1 int, a int) PARTITION BY RANGE (a, b); -ALTER TABLE fk_partitioned_fk DROP COLUMN fdrop1; -CREATE TABLE fk_partitioned_fk_1 (fdrop1 int, fdrop2 int, a int, fdrop3 int, b int); -ALTER TABLE fk_partitioned_fk_1 DROP COLUMN fdrop1, DROP COLUMN fdrop2, DROP COLUMN fdrop3; -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_1 FOR VALUES FROM (0,0) TO (1000,1000); -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk; -CREATE TABLE fk_partitioned_fk_2 (b int, fdrop1 int, fdrop2 int, a int); -ALTER TABLE fk_partitioned_fk_2 DROP COLUMN fdrop1, DROP COLUMN fdrop2; -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_2 FOR VALUES FROM (1000,1000) TO (2000,2000); - -CREATE TABLE fk_partitioned_fk_3 (fdrop1 int, fdrop2 int, fdrop3 int, fdrop4 int, b int, a int) - PARTITION BY HASH (a); -ALTER TABLE fk_partitioned_fk_3 DROP COLUMN fdrop1, DROP COLUMN fdrop2, - DROP COLUMN fdrop3, DROP COLUMN fdrop4; -CREATE TABLE fk_partitioned_fk_3_0 PARTITION OF fk_partitioned_fk_3 FOR VALUES WITH (MODULUS 5, REMAINDER 0); -CREATE TABLE fk_partitioned_fk_3_1 PARTITION OF fk_partitioned_fk_3 FOR VALUES WITH (MODULUS 5, REMAINDER 1); -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_3 - FOR VALUES FROM (2000,2000) TO (3000,3000); - --- Creating a foreign key with ONLY on a partitioned table referencing --- a non-partitioned table fails. -ALTER TABLE ONLY fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk; --- Adding a NOT VALID foreign key on a partitioned table referencing --- a non-partitioned table fails. -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk NOT VALID; - --- these inserts, targeting both the partition directly as well as the --- partitioned table, should all fail -INSERT INTO fk_partitioned_fk (a,b) VALUES (500, 501); -INSERT INTO fk_partitioned_fk_1 (a,b) VALUES (500, 501); -INSERT INTO fk_partitioned_fk (a,b) VALUES (1500, 1501); -INSERT INTO fk_partitioned_fk_2 (a,b) VALUES (1500, 1501); -INSERT INTO fk_partitioned_fk (a,b) VALUES (2500, 2502); -INSERT INTO fk_partitioned_fk_3 (a,b) VALUES (2500, 2502); -INSERT INTO fk_partitioned_fk (a,b) VALUES (2501, 2503); -INSERT INTO fk_partitioned_fk_3 (a,b) VALUES (2501, 2503); - --- but if we insert the values that make them valid, then they work -INSERT INTO fk_notpartitioned_pk VALUES (500, 501), (1500, 1501), - (2500, 2502), (2501, 2503); -INSERT INTO fk_partitioned_fk (a,b) VALUES (500, 501); -INSERT INTO fk_partitioned_fk (a,b) VALUES (1500, 1501); -INSERT INTO fk_partitioned_fk (a,b) VALUES (2500, 2502); -INSERT INTO fk_partitioned_fk (a,b) VALUES (2501, 2503); - --- this update fails because there is no referenced row -UPDATE fk_partitioned_fk SET a = a + 1 WHERE a = 2501; --- but we can fix it thusly: -INSERT INTO fk_notpartitioned_pk (a,b) VALUES (2502, 2503); -UPDATE fk_partitioned_fk SET a = a + 1 WHERE a = 2501; - --- these updates would leave lingering rows in the referencing table; disallow -UPDATE fk_notpartitioned_pk SET b = 502 WHERE a = 500; -UPDATE fk_notpartitioned_pk SET b = 1502 WHERE a = 1500; -UPDATE fk_notpartitioned_pk SET b = 2504 WHERE a = 2500; --- check psql behavior -\d fk_notpartitioned_pk -ALTER TABLE fk_partitioned_fk DROP CONSTRAINT fk_partitioned_fk_a_b_fkey; --- done. -DROP TABLE fk_notpartitioned_pk, fk_partitioned_fk; - --- Altering a type referenced by a foreign key needs to drop/recreate the FK. --- Ensure that works. -CREATE TABLE fk_notpartitioned_pk (a INT, PRIMARY KEY(a), CHECK (a > 0)); -CREATE TABLE fk_partitioned_fk (a INT REFERENCES fk_notpartitioned_pk(a) PRIMARY KEY) PARTITION BY RANGE(a); -CREATE TABLE fk_partitioned_fk_1 PARTITION OF fk_partitioned_fk FOR VALUES FROM (MINVALUE) TO (MAXVALUE); -INSERT INTO fk_notpartitioned_pk VALUES (1); -INSERT INTO fk_partitioned_fk VALUES (1); -ALTER TABLE fk_notpartitioned_pk ALTER COLUMN a TYPE bigint; -DELETE FROM fk_notpartitioned_pk WHERE a = 1; -DROP TABLE fk_notpartitioned_pk, fk_partitioned_fk; - --- Test some other exotic foreign key features: MATCH SIMPLE, ON UPDATE/DELETE --- actions -CREATE TABLE fk_notpartitioned_pk (a int, b int, primary key (a, b)); -CREATE TABLE fk_partitioned_fk (a int default 2501, b int default 142857) PARTITION BY LIST (a); -CREATE TABLE fk_partitioned_fk_1 PARTITION OF fk_partitioned_fk FOR VALUES IN (NULL,500,501,502); -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk MATCH SIMPLE - ON DELETE SET NULL ON UPDATE SET NULL; -CREATE TABLE fk_partitioned_fk_2 PARTITION OF fk_partitioned_fk FOR VALUES IN (1500,1502); -CREATE TABLE fk_partitioned_fk_3 (a int, b int); -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_3 FOR VALUES IN (2500,2501,2502,2503); - --- this insert fails -INSERT INTO fk_partitioned_fk (a, b) VALUES (2502, 2503); -INSERT INTO fk_partitioned_fk_3 (a, b) VALUES (2502, 2503); --- but since the FK is MATCH SIMPLE, this one doesn't -INSERT INTO fk_partitioned_fk_3 (a, b) VALUES (2502, NULL); --- now create the referenced row ... -INSERT INTO fk_notpartitioned_pk VALUES (2502, 2503); ---- and now the same insert work -INSERT INTO fk_partitioned_fk_3 (a, b) VALUES (2502, 2503); --- this always works -INSERT INTO fk_partitioned_fk (a,b) VALUES (NULL, NULL); - --- MATCH FULL -INSERT INTO fk_notpartitioned_pk VALUES (1, 2); -CREATE TABLE fk_partitioned_fk_full (x int, y int) PARTITION BY RANGE (x); -CREATE TABLE fk_partitioned_fk_full_1 PARTITION OF fk_partitioned_fk_full DEFAULT; -INSERT INTO fk_partitioned_fk_full VALUES (1, NULL); -ALTER TABLE fk_partitioned_fk_full ADD FOREIGN KEY (x, y) REFERENCES fk_notpartitioned_pk MATCH FULL; -- fails -TRUNCATE fk_partitioned_fk_full; -ALTER TABLE fk_partitioned_fk_full ADD FOREIGN KEY (x, y) REFERENCES fk_notpartitioned_pk MATCH FULL; -INSERT INTO fk_partitioned_fk_full VALUES (1, NULL); -- fails -DROP TABLE fk_partitioned_fk_full; - --- ON UPDATE SET NULL -SELECT tableoid::regclass, a, b FROM fk_partitioned_fk WHERE b IS NULL ORDER BY a; -UPDATE fk_notpartitioned_pk SET a = a + 1 WHERE a = 2502; -SELECT tableoid::regclass, a, b FROM fk_partitioned_fk WHERE b IS NULL ORDER BY a; - --- ON DELETE SET NULL -INSERT INTO fk_partitioned_fk VALUES (2503, 2503); -SELECT count(*) FROM fk_partitioned_fk WHERE a IS NULL; -DELETE FROM fk_notpartitioned_pk; -SELECT count(*) FROM fk_partitioned_fk WHERE a IS NULL; - --- ON UPDATE/DELETE SET DEFAULT -ALTER TABLE fk_partitioned_fk DROP CONSTRAINT fk_partitioned_fk_a_b_fkey; -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk - ON DELETE SET DEFAULT ON UPDATE SET DEFAULT; -INSERT INTO fk_notpartitioned_pk VALUES (2502, 2503); -INSERT INTO fk_partitioned_fk_3 (a, b) VALUES (2502, 2503); --- this fails, because the defaults for the referencing table are not present --- in the referenced table: -UPDATE fk_notpartitioned_pk SET a = 1500 WHERE a = 2502; --- but inserting the row we can make it work: -INSERT INTO fk_notpartitioned_pk VALUES (2501, 142857); -UPDATE fk_notpartitioned_pk SET a = 1500 WHERE a = 2502; -SELECT * FROM fk_partitioned_fk WHERE b = 142857; - --- ON DELETE SET NULL column_list -ALTER TABLE fk_partitioned_fk DROP CONSTRAINT fk_partitioned_fk_a_b_fkey; -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk - ON DELETE SET NULL (a); -BEGIN; -DELETE FROM fk_notpartitioned_pk WHERE b = 142857; -SELECT * FROM fk_partitioned_fk WHERE a IS NOT NULL OR b IS NOT NULL ORDER BY a NULLS LAST; -ROLLBACK; - --- ON DELETE SET DEFAULT column_list -ALTER TABLE fk_partitioned_fk DROP CONSTRAINT fk_partitioned_fk_a_b_fkey; -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk - ON DELETE SET DEFAULT (a); -BEGIN; -DELETE FROM fk_partitioned_fk; -DELETE FROM fk_notpartitioned_pk; -INSERT INTO fk_notpartitioned_pk VALUES (500, 100000), (2501, 100000); -INSERT INTO fk_partitioned_fk VALUES (500, 100000); -DELETE FROM fk_notpartitioned_pk WHERE a = 500; -SELECT * FROM fk_partitioned_fk ORDER BY a; -ROLLBACK; - --- ON UPDATE/DELETE CASCADE -ALTER TABLE fk_partitioned_fk DROP CONSTRAINT fk_partitioned_fk_a_b_fkey; -ALTER TABLE fk_partitioned_fk ADD FOREIGN KEY (a, b) - REFERENCES fk_notpartitioned_pk - ON DELETE CASCADE ON UPDATE CASCADE; -UPDATE fk_notpartitioned_pk SET a = 2502 WHERE a = 2501; -SELECT * FROM fk_partitioned_fk WHERE b = 142857; - --- Now you see it ... -SELECT * FROM fk_partitioned_fk WHERE b = 142857; -DELETE FROM fk_notpartitioned_pk WHERE b = 142857; --- now you don't. -SELECT * FROM fk_partitioned_fk WHERE a = 142857; - --- verify that DROP works -DROP TABLE fk_partitioned_fk_2; - --- Test behavior of the constraint together with attaching and detaching --- partitions. -CREATE TABLE fk_partitioned_fk_2 PARTITION OF fk_partitioned_fk FOR VALUES IN (1500,1502); -ALTER TABLE fk_partitioned_fk DETACH PARTITION fk_partitioned_fk_2; -BEGIN; -DROP TABLE fk_partitioned_fk; --- constraint should still be there -\d fk_partitioned_fk_2; -ROLLBACK; -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_2 FOR VALUES IN (1500,1502); -DROP TABLE fk_partitioned_fk_2; -CREATE TABLE fk_partitioned_fk_2 (b int, c text, a int, - FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk ON UPDATE CASCADE ON DELETE CASCADE); -ALTER TABLE fk_partitioned_fk_2 DROP COLUMN c; -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_2 FOR VALUES IN (1500,1502); --- should have only one constraint -\d fk_partitioned_fk_2 -DROP TABLE fk_partitioned_fk_2; - -CREATE TABLE fk_partitioned_fk_4 (a int, b int, FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk(a, b) ON UPDATE CASCADE ON DELETE CASCADE) PARTITION BY RANGE (b, a); -CREATE TABLE fk_partitioned_fk_4_1 PARTITION OF fk_partitioned_fk_4 FOR VALUES FROM (1,1) TO (100,100); -CREATE TABLE fk_partitioned_fk_4_2 (a int, b int, FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk(a, b) ON UPDATE SET NULL); -ALTER TABLE fk_partitioned_fk_4 ATTACH PARTITION fk_partitioned_fk_4_2 FOR VALUES FROM (100,100) TO (1000,1000); -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_4 FOR VALUES IN (3500,3502); -ALTER TABLE fk_partitioned_fk DETACH PARTITION fk_partitioned_fk_4; -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_4 FOR VALUES IN (3500,3502); --- should only have one constraint -\d fk_partitioned_fk_4 -\d fk_partitioned_fk_4_1 --- this one has an FK with mismatched properties -\d fk_partitioned_fk_4_2 - -CREATE TABLE fk_partitioned_fk_5 (a int, b int, - FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk(a, b) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE, - FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk(a, b) MATCH FULL ON UPDATE CASCADE ON DELETE CASCADE) - PARTITION BY RANGE (a); -CREATE TABLE fk_partitioned_fk_5_1 (a int, b int, FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk); -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_5 FOR VALUES IN (4500); -ALTER TABLE fk_partitioned_fk_5 ATTACH PARTITION fk_partitioned_fk_5_1 FOR VALUES FROM (0) TO (10); -ALTER TABLE fk_partitioned_fk DETACH PARTITION fk_partitioned_fk_5; -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_5 FOR VALUES IN (4500); --- this one has two constraints, similar but not quite the one in the parent, --- so it gets a new one -\d fk_partitioned_fk_5 --- verify that it works to reattaching a child with multiple candidate --- constraints -ALTER TABLE fk_partitioned_fk_5 DETACH PARTITION fk_partitioned_fk_5_1; -ALTER TABLE fk_partitioned_fk_5 ATTACH PARTITION fk_partitioned_fk_5_1 FOR VALUES FROM (0) TO (10); -\d fk_partitioned_fk_5_1 - --- verify that attaching a table checks that the existing data satisfies the --- constraint -CREATE TABLE fk_partitioned_fk_2 (a int, b int) PARTITION BY RANGE (b); -CREATE TABLE fk_partitioned_fk_2_1 PARTITION OF fk_partitioned_fk_2 FOR VALUES FROM (0) TO (1000); -CREATE TABLE fk_partitioned_fk_2_2 PARTITION OF fk_partitioned_fk_2 FOR VALUES FROM (1000) TO (2000); -INSERT INTO fk_partitioned_fk_2 VALUES (1600, 601), (1600, 1601); -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_2 - FOR VALUES IN (1600); -INSERT INTO fk_notpartitioned_pk VALUES (1600, 601), (1600, 1601); -ALTER TABLE fk_partitioned_fk ATTACH PARTITION fk_partitioned_fk_2 - FOR VALUES IN (1600); - --- leave these tables around intentionally - --- test the case when the referenced table is owned by a different user -create role regress_other_partitioned_fk_owner; -grant references on fk_notpartitioned_pk to regress_other_partitioned_fk_owner; -set role regress_other_partitioned_fk_owner; -create table other_partitioned_fk(a int, b int) partition by list (a); -create table other_partitioned_fk_1 partition of other_partitioned_fk - for values in (2048); -insert into other_partitioned_fk - select 2048, x from generate_series(1,10) x; --- this should fail -alter table other_partitioned_fk add foreign key (a, b) - references fk_notpartitioned_pk(a, b); --- add the missing keys and retry -reset role; -insert into fk_notpartitioned_pk (a, b) - select 2048, x from generate_series(1,10) x; -set role regress_other_partitioned_fk_owner; -alter table other_partitioned_fk add foreign key (a, b) - references fk_notpartitioned_pk(a, b); --- clean up -drop table other_partitioned_fk; -reset role; -revoke all on fk_notpartitioned_pk from regress_other_partitioned_fk_owner; -drop role regress_other_partitioned_fk_owner; - --- Test creating a constraint at the parent that already exists in partitions. --- There should be no duplicated constraints, and attempts to drop the --- constraint in partitions should raise appropriate errors. -create schema fkpart0 - create table pkey (a int primary key) - create table fk_part (a int) partition by list (a) - create table fk_part_1 partition of fk_part - (foreign key (a) references fkpart0.pkey) for values in (1) - create table fk_part_23 partition of fk_part - (foreign key (a) references fkpart0.pkey) for values in (2, 3) - partition by list (a) - create table fk_part_23_2 partition of fk_part_23 for values in (2); - -alter table fkpart0.fk_part add foreign key (a) references fkpart0.pkey; -\d fkpart0.fk_part_1 \\ -- should have only one FK -alter table fkpart0.fk_part_1 drop constraint fk_part_1_a_fkey; - -\d fkpart0.fk_part_23 \\ -- should have only one FK -\d fkpart0.fk_part_23_2 \\ -- should have only one FK -alter table fkpart0.fk_part_23 drop constraint fk_part_23_a_fkey; -alter table fkpart0.fk_part_23_2 drop constraint fk_part_23_a_fkey; - -create table fkpart0.fk_part_4 partition of fkpart0.fk_part for values in (4); -\d fkpart0.fk_part_4 -alter table fkpart0.fk_part_4 drop constraint fk_part_a_fkey; - -create table fkpart0.fk_part_56 partition of fkpart0.fk_part - for values in (5,6) partition by list (a); -create table fkpart0.fk_part_56_5 partition of fkpart0.fk_part_56 - for values in (5); -\d fkpart0.fk_part_56 -alter table fkpart0.fk_part_56 drop constraint fk_part_a_fkey; -alter table fkpart0.fk_part_56_5 drop constraint fk_part_a_fkey; - --- verify that attaching and detaching partitions maintains the right set of --- triggers -create schema fkpart1 - create table pkey (a int primary key) - create table fk_part (a int) partition by list (a) - create table fk_part_1 partition of fk_part for values in (1) partition by list (a) - create table fk_part_1_1 partition of fk_part_1 for values in (1); -alter table fkpart1.fk_part add foreign key (a) references fkpart1.pkey; -insert into fkpart1.fk_part values (1); -- should fail -insert into fkpart1.pkey values (1); -insert into fkpart1.fk_part values (1); -delete from fkpart1.pkey where a = 1; -- should fail -alter table fkpart1.fk_part detach partition fkpart1.fk_part_1; -create table fkpart1.fk_part_1_2 partition of fkpart1.fk_part_1 for values in (2); -insert into fkpart1.fk_part_1 values (2); -- should fail -delete from fkpart1.pkey where a = 1; - --- verify that attaching and detaching partitions manipulates the inheritance --- properties of their FK constraints correctly -create schema fkpart2 - create table pkey (a int primary key) - create table fk_part (a int, constraint fkey foreign key (a) references fkpart2.pkey) partition by list (a) - create table fk_part_1 partition of fkpart2.fk_part for values in (1) partition by list (a) - create table fk_part_1_1 (a int, constraint my_fkey foreign key (a) references fkpart2.pkey); -alter table fkpart2.fk_part_1 attach partition fkpart2.fk_part_1_1 for values in (1); -alter table fkpart2.fk_part_1 drop constraint fkey; -- should fail -alter table fkpart2.fk_part_1_1 drop constraint my_fkey; -- should fail -alter table fkpart2.fk_part detach partition fkpart2.fk_part_1; -alter table fkpart2.fk_part_1 drop constraint fkey; -- ok -alter table fkpart2.fk_part_1_1 drop constraint my_fkey; -- doesn't exist - --- verify constraint deferrability -create schema fkpart3 - create table pkey (a int primary key) - create table fk_part (a int, constraint fkey foreign key (a) references fkpart3.pkey deferrable initially immediate) partition by list (a) - create table fk_part_1 partition of fkpart3.fk_part for values in (1) partition by list (a) - create table fk_part_1_1 partition of fkpart3.fk_part_1 for values in (1) - create table fk_part_2 partition of fkpart3.fk_part for values in (2); -begin; -set constraints fkpart3.fkey deferred; -insert into fkpart3.fk_part values (1); -insert into fkpart3.pkey values (1); -commit; -begin; -set constraints fkpart3.fkey deferred; -delete from fkpart3.pkey; -delete from fkpart3.fk_part; -commit; - -drop schema fkpart0, fkpart1, fkpart2, fkpart3 cascade; - --- Test a partitioned table as referenced table. - --- Verify basic functionality with a regular partition creation and a partition --- with a different column layout, as well as partitions added (created and --- attached) after creating the foreign key. -CREATE SCHEMA fkpart3; -SET search_path TO fkpart3; - -CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY RANGE (a); -CREATE TABLE pk1 PARTITION OF pk FOR VALUES FROM (0) TO (1000); -CREATE TABLE pk2 (b int, a int); -ALTER TABLE pk2 DROP COLUMN b; -ALTER TABLE pk2 ALTER a SET NOT NULL; -ALTER TABLE pk ATTACH PARTITION pk2 FOR VALUES FROM (1000) TO (2000); - -CREATE TABLE fk (a int) PARTITION BY RANGE (a); -CREATE TABLE fk1 PARTITION OF fk FOR VALUES FROM (0) TO (750); -ALTER TABLE fk ADD FOREIGN KEY (a) REFERENCES pk; -CREATE TABLE fk2 (b int, a int) ; -ALTER TABLE fk2 DROP COLUMN b; -ALTER TABLE fk ATTACH PARTITION fk2 FOR VALUES FROM (750) TO (3500); - -CREATE TABLE pk3 PARTITION OF pk FOR VALUES FROM (2000) TO (3000); -CREATE TABLE pk4 (LIKE pk); -ALTER TABLE pk ATTACH PARTITION pk4 FOR VALUES FROM (3000) TO (4000); - -CREATE TABLE pk5 (c int, b int, a int NOT NULL) PARTITION BY RANGE (a); -ALTER TABLE pk5 DROP COLUMN b, DROP COLUMN c; -CREATE TABLE pk51 PARTITION OF pk5 FOR VALUES FROM (4000) TO (4500); -CREATE TABLE pk52 PARTITION OF pk5 FOR VALUES FROM (4500) TO (5000); -ALTER TABLE pk ATTACH PARTITION pk5 FOR VALUES FROM (4000) TO (5000); - -CREATE TABLE fk3 PARTITION OF fk FOR VALUES FROM (3500) TO (5000); - --- these should fail: referenced value not present -INSERT into fk VALUES (1); -INSERT into fk VALUES (1000); -INSERT into fk VALUES (2000); -INSERT into fk VALUES (3000); -INSERT into fk VALUES (4000); -INSERT into fk VALUES (4500); --- insert into the referenced table, now they should work -INSERT into pk VALUES (1), (1000), (2000), (3000), (4000), (4500); -INSERT into fk VALUES (1), (1000), (2000), (3000), (4000), (4500); - --- should fail: referencing value present -DELETE FROM pk WHERE a = 1; -DELETE FROM pk WHERE a = 1000; -DELETE FROM pk WHERE a = 2000; -DELETE FROM pk WHERE a = 3000; -DELETE FROM pk WHERE a = 4000; -DELETE FROM pk WHERE a = 4500; -UPDATE pk SET a = 2 WHERE a = 1; -UPDATE pk SET a = 1002 WHERE a = 1000; -UPDATE pk SET a = 2002 WHERE a = 2000; -UPDATE pk SET a = 3002 WHERE a = 3000; -UPDATE pk SET a = 4002 WHERE a = 4000; -UPDATE pk SET a = 4502 WHERE a = 4500; --- now they should work -DELETE FROM fk; -UPDATE pk SET a = 2 WHERE a = 1; -DELETE FROM pk WHERE a = 2; -UPDATE pk SET a = 1002 WHERE a = 1000; -DELETE FROM pk WHERE a = 1002; -UPDATE pk SET a = 2002 WHERE a = 2000; -DELETE FROM pk WHERE a = 2002; -UPDATE pk SET a = 3002 WHERE a = 3000; -DELETE FROM pk WHERE a = 3002; -UPDATE pk SET a = 4002 WHERE a = 4000; -DELETE FROM pk WHERE a = 4002; -UPDATE pk SET a = 4502 WHERE a = 4500; -DELETE FROM pk WHERE a = 4502; - -CREATE SCHEMA fkpart4; -SET search_path TO fkpart4; --- dropping/detaching PARTITIONs is prevented if that would break --- a foreign key's existing data -CREATE TABLE droppk (a int PRIMARY KEY) PARTITION BY RANGE (a); -CREATE TABLE droppk1 PARTITION OF droppk FOR VALUES FROM (0) TO (1000); -CREATE TABLE droppk_d PARTITION OF droppk DEFAULT; -CREATE TABLE droppk2 PARTITION OF droppk FOR VALUES FROM (1000) TO (2000) - PARTITION BY RANGE (a); -CREATE TABLE droppk21 PARTITION OF droppk2 FOR VALUES FROM (1000) TO (1400); -CREATE TABLE droppk2_d PARTITION OF droppk2 DEFAULT; -INSERT into droppk VALUES (1), (1000), (1500), (2000); -CREATE TABLE dropfk (a int REFERENCES droppk); -INSERT into dropfk VALUES (1), (1000), (1500), (2000); --- these should all fail -ALTER TABLE droppk DETACH PARTITION droppk_d; -ALTER TABLE droppk2 DETACH PARTITION droppk2_d; -ALTER TABLE droppk DETACH PARTITION droppk1; -ALTER TABLE droppk DETACH PARTITION droppk2; -ALTER TABLE droppk2 DETACH PARTITION droppk21; --- dropping partitions is disallowed -DROP TABLE droppk_d; -DROP TABLE droppk2_d; -DROP TABLE droppk1; -DROP TABLE droppk2; -DROP TABLE droppk21; -DELETE FROM dropfk; --- dropping partitions is disallowed, even when no referencing values -DROP TABLE droppk_d; -DROP TABLE droppk2_d; -DROP TABLE droppk1; --- but DETACH is allowed, and DROP afterwards works -ALTER TABLE droppk2 DETACH PARTITION droppk21; -DROP TABLE droppk2; - --- Verify that initial constraint creation and cloning behave correctly -CREATE SCHEMA fkpart5; -SET search_path TO fkpart5; -CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY LIST (a); -CREATE TABLE pk1 PARTITION OF pk FOR VALUES IN (1) PARTITION BY LIST (a); -CREATE TABLE pk11 PARTITION OF pk1 FOR VALUES IN (1); -CREATE TABLE fk (a int) PARTITION BY LIST (a); -CREATE TABLE fk1 PARTITION OF fk FOR VALUES IN (1) PARTITION BY LIST (a); -CREATE TABLE fk11 PARTITION OF fk1 FOR VALUES IN (1); -ALTER TABLE fk ADD FOREIGN KEY (a) REFERENCES pk; -CREATE TABLE pk2 PARTITION OF pk FOR VALUES IN (2); -CREATE TABLE pk3 (a int NOT NULL) PARTITION BY LIST (a); -CREATE TABLE pk31 PARTITION OF pk3 FOR VALUES IN (31); -CREATE TABLE pk32 (b int, a int NOT NULL); -ALTER TABLE pk32 DROP COLUMN b; -ALTER TABLE pk3 ATTACH PARTITION pk32 FOR VALUES IN (32); -ALTER TABLE pk ATTACH PARTITION pk3 FOR VALUES IN (31, 32); -CREATE TABLE fk2 PARTITION OF fk FOR VALUES IN (2); -CREATE TABLE fk3 (b int, a int); -ALTER TABLE fk3 DROP COLUMN b; -ALTER TABLE fk ATTACH PARTITION fk3 FOR VALUES IN (3); -SELECT pg_describe_object('pg_constraint'::regclass, oid, 0), confrelid::regclass, - CASE WHEN conparentid <> 0 THEN pg_describe_object('pg_constraint'::regclass, conparentid, 0) ELSE 'TOP' END -FROM pg_catalog.pg_constraint -WHERE conrelid IN (SELECT relid FROM pg_partition_tree('fk')) -ORDER BY conrelid::regclass::text, conname; -CREATE TABLE fk4 (LIKE fk); -INSERT INTO fk4 VALUES (50); -ALTER TABLE fk ATTACH PARTITION fk4 FOR VALUES IN (50); - --- Verify constraint deferrability -CREATE SCHEMA fkpart9; -SET search_path TO fkpart9; -CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY LIST (a); -CREATE TABLE pk1 PARTITION OF pk FOR VALUES IN (1, 2) PARTITION BY LIST (a); -CREATE TABLE pk11 PARTITION OF pk1 FOR VALUES IN (1); -CREATE TABLE pk3 PARTITION OF pk FOR VALUES IN (3); -CREATE TABLE fk (a int REFERENCES pk DEFERRABLE INITIALLY IMMEDIATE); -INSERT INTO fk VALUES (1); -- should fail -BEGIN; -SET CONSTRAINTS fk_a_fkey DEFERRED; -INSERT INTO fk VALUES (1); -COMMIT; -- should fail -BEGIN; -SET CONSTRAINTS fk_a_fkey DEFERRED; -INSERT INTO fk VALUES (1); -INSERT INTO pk VALUES (1); -COMMIT; -- OK -BEGIN; -SET CONSTRAINTS fk_a_fkey DEFERRED; -DELETE FROM pk WHERE a = 1; -DELETE FROM fk WHERE a = 1; -COMMIT; -- OK - --- Verify constraint deferrability when changed by ALTER --- Partitioned table at referencing end -CREATE TABLE pt(f1 int, f2 int, f3 int, PRIMARY KEY(f1,f2)); -CREATE TABLE ref(f1 int, f2 int, f3 int) - PARTITION BY list(f1); -CREATE TABLE ref1 PARTITION OF ref FOR VALUES IN (1); -CREATE TABLE ref2 PARTITION OF ref FOR VALUES in (2); -ALTER TABLE ref ADD FOREIGN KEY(f1,f2) REFERENCES pt; -ALTER TABLE ref ALTER CONSTRAINT ref_f1_f2_fkey - DEFERRABLE INITIALLY DEFERRED; -INSERT INTO pt VALUES(1,2,3); -INSERT INTO ref VALUES(1,2,3); -BEGIN; -DELETE FROM pt; -DELETE FROM ref; -ABORT; -DROP TABLE pt, ref; --- Multi-level partitioning at referencing end -CREATE TABLE pt(f1 int, f2 int, f3 int, PRIMARY KEY(f1,f2)); -CREATE TABLE ref(f1 int, f2 int, f3 int) - PARTITION BY list(f1); -CREATE TABLE ref1_2 PARTITION OF ref FOR VALUES IN (1, 2) PARTITION BY list (f2); -CREATE TABLE ref1 PARTITION OF ref1_2 FOR VALUES IN (1); -CREATE TABLE ref2 PARTITION OF ref1_2 FOR VALUES IN (2) PARTITION BY list (f2); -CREATE TABLE ref22 PARTITION OF ref2 FOR VALUES IN (2); -ALTER TABLE ref ADD FOREIGN KEY(f1,f2) REFERENCES pt; -INSERT INTO pt VALUES(1,2,3); -INSERT INTO ref VALUES(1,2,3); -ALTER TABLE ref22 ALTER CONSTRAINT ref_f1_f2_fkey - DEFERRABLE INITIALLY IMMEDIATE; -- fails -ALTER TABLE ref ALTER CONSTRAINT ref_f1_f2_fkey - DEFERRABLE INITIALLY DEFERRED; -BEGIN; -DELETE FROM pt; -DELETE FROM ref; -ABORT; -DROP TABLE pt, ref; - --- Partitioned table at referenced end -CREATE TABLE pt(f1 int, f2 int, f3 int, PRIMARY KEY(f1,f2)) - PARTITION BY LIST(f1); -CREATE TABLE pt1 PARTITION OF pt FOR VALUES IN (1); -CREATE TABLE pt2 PARTITION OF pt FOR VALUES IN (2); -CREATE TABLE ref(f1 int, f2 int, f3 int); -ALTER TABLE ref ADD FOREIGN KEY(f1,f2) REFERENCES pt; -ALTER TABLE ref ALTER CONSTRAINT ref_f1_f2_fkey - DEFERRABLE INITIALLY DEFERRED; -INSERT INTO pt VALUES(1,2,3); -INSERT INTO ref VALUES(1,2,3); -BEGIN; -DELETE FROM pt; -DELETE FROM ref; -ABORT; -DROP TABLE pt, ref; --- Multi-level partitioning at at referenced end -CREATE TABLE pt(f1 int, f2 int, f3 int, PRIMARY KEY(f1,f2)) - PARTITION BY LIST(f1); -CREATE TABLE pt1_2 PARTITION OF pt FOR VALUES IN (1, 2) PARTITION BY LIST (f1); -CREATE TABLE pt1 PARTITION OF pt1_2 FOR VALUES IN (1); -CREATE TABLE pt2 PARTITION OF pt1_2 FOR VALUES IN (2); -CREATE TABLE ref(f1 int, f2 int, f3 int); -ALTER TABLE ref ADD FOREIGN KEY(f1,f2) REFERENCES pt; -ALTER TABLE ref ALTER CONSTRAINT ref_f1_f2_fkey1 - DEFERRABLE INITIALLY DEFERRED; -- fails -ALTER TABLE ref ALTER CONSTRAINT ref_f1_f2_fkey - DEFERRABLE INITIALLY DEFERRED; -INSERT INTO pt VALUES(1,2,3); -INSERT INTO ref VALUES(1,2,3); -BEGIN; -DELETE FROM pt; -DELETE FROM ref; -ABORT; -DROP TABLE pt, ref; - -DROP SCHEMA fkpart9 CASCADE; - --- Verify ON UPDATE/DELETE behavior -CREATE SCHEMA fkpart6; -SET search_path TO fkpart6; -CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY RANGE (a); -CREATE TABLE pk1 PARTITION OF pk FOR VALUES FROM (1) TO (100) PARTITION BY RANGE (a); -CREATE TABLE pk11 PARTITION OF pk1 FOR VALUES FROM (1) TO (50); -CREATE TABLE pk12 PARTITION OF pk1 FOR VALUES FROM (50) TO (100); -CREATE TABLE fk (a int) PARTITION BY RANGE (a); -CREATE TABLE fk1 PARTITION OF fk FOR VALUES FROM (1) TO (100) PARTITION BY RANGE (a); -CREATE TABLE fk11 PARTITION OF fk1 FOR VALUES FROM (1) TO (10); -CREATE TABLE fk12 PARTITION OF fk1 FOR VALUES FROM (10) TO (100); -ALTER TABLE fk ADD FOREIGN KEY (a) REFERENCES pk ON UPDATE CASCADE ON DELETE CASCADE; -CREATE TABLE fk_d PARTITION OF fk DEFAULT; -INSERT INTO pk VALUES (1); -INSERT INTO fk VALUES (1); -UPDATE pk SET a = 20; -SELECT tableoid::regclass, * FROM fk; -DELETE FROM pk WHERE a = 20; -SELECT tableoid::regclass, * FROM fk; -DROP TABLE fk; - -TRUNCATE TABLE pk; -INSERT INTO pk VALUES (20), (50); -CREATE TABLE fk (a int) PARTITION BY RANGE (a); -CREATE TABLE fk1 PARTITION OF fk FOR VALUES FROM (1) TO (100) PARTITION BY RANGE (a); -CREATE TABLE fk11 PARTITION OF fk1 FOR VALUES FROM (1) TO (10); -CREATE TABLE fk12 PARTITION OF fk1 FOR VALUES FROM (10) TO (100); -ALTER TABLE fk ADD FOREIGN KEY (a) REFERENCES pk ON UPDATE SET NULL ON DELETE SET NULL; -CREATE TABLE fk_d PARTITION OF fk DEFAULT; -INSERT INTO fk VALUES (20), (50); -UPDATE pk SET a = 21 WHERE a = 20; -DELETE FROM pk WHERE a = 50; -SELECT tableoid::regclass, * FROM fk; -DROP TABLE fk; - -TRUNCATE TABLE pk; -INSERT INTO pk VALUES (20), (30), (50); -CREATE TABLE fk (id int, a int DEFAULT 50) PARTITION BY RANGE (a); -CREATE TABLE fk1 PARTITION OF fk FOR VALUES FROM (1) TO (100) PARTITION BY RANGE (a); -CREATE TABLE fk11 PARTITION OF fk1 FOR VALUES FROM (1) TO (10); -CREATE TABLE fk12 PARTITION OF fk1 FOR VALUES FROM (10) TO (100); -ALTER TABLE fk ADD FOREIGN KEY (a) REFERENCES pk ON UPDATE SET DEFAULT ON DELETE SET DEFAULT; -CREATE TABLE fk_d PARTITION OF fk DEFAULT; -INSERT INTO fk VALUES (1, 20), (2, 30); -DELETE FROM pk WHERE a = 20 RETURNING *; -UPDATE pk SET a = 90 WHERE a = 30 RETURNING *; -SELECT tableoid::regclass, * FROM fk; -DROP TABLE fk; - -TRUNCATE TABLE pk; -INSERT INTO pk VALUES (20), (30); -CREATE TABLE fk (a int DEFAULT 50) PARTITION BY RANGE (a); -CREATE TABLE fk1 PARTITION OF fk FOR VALUES FROM (1) TO (100) PARTITION BY RANGE (a); -CREATE TABLE fk11 PARTITION OF fk1 FOR VALUES FROM (1) TO (10); -CREATE TABLE fk12 PARTITION OF fk1 FOR VALUES FROM (10) TO (100); -ALTER TABLE fk ADD FOREIGN KEY (a) REFERENCES pk ON UPDATE RESTRICT ON DELETE RESTRICT; -CREATE TABLE fk_d PARTITION OF fk DEFAULT; -INSERT INTO fk VALUES (20), (30); -DELETE FROM pk WHERE a = 20; -UPDATE pk SET a = 90 WHERE a = 30; -SELECT tableoid::regclass, * FROM fk; -DROP TABLE fk; - --- test for reported bug: relispartition not set --- https://postgr.es/m/CA+HiwqHMsRtRYRWYTWavKJ8x14AFsv7bmAV46mYwnfD3vy8goQ@mail.gmail.com -CREATE SCHEMA fkpart7 - CREATE TABLE pkpart (a int) PARTITION BY LIST (a) - CREATE TABLE pkpart1 PARTITION OF pkpart FOR VALUES IN (1); -ALTER TABLE fkpart7.pkpart1 ADD PRIMARY KEY (a); -ALTER TABLE fkpart7.pkpart ADD PRIMARY KEY (a); -CREATE TABLE fkpart7.fk (a int REFERENCES fkpart7.pkpart); -DROP SCHEMA fkpart7 CASCADE; - --- ensure we check partitions are "not used" when dropping constraints -CREATE SCHEMA fkpart8 - CREATE TABLE tbl1(f1 int PRIMARY KEY) - CREATE TABLE tbl2(f1 int REFERENCES tbl1 DEFERRABLE INITIALLY DEFERRED) PARTITION BY RANGE(f1) - CREATE TABLE tbl2_p1 PARTITION OF tbl2 FOR VALUES FROM (minvalue) TO (maxvalue); -INSERT INTO fkpart8.tbl1 VALUES(1); -BEGIN; -INSERT INTO fkpart8.tbl2 VALUES(1); -ALTER TABLE fkpart8.tbl2 DROP CONSTRAINT tbl2_f1_fkey; -COMMIT; -DROP SCHEMA fkpart8 CASCADE; - --- ensure FK referencing a multi-level partitioned table are --- enforce reference to sub-children. -CREATE SCHEMA fkpart9 - CREATE TABLE pk (a INT PRIMARY KEY) PARTITION BY RANGE (a) - CREATE TABLE fk ( - fk_a INT REFERENCES pk(a) ON DELETE CASCADE - ) - CREATE TABLE pk1 PARTITION OF pk FOR VALUES FROM (30) TO (50) PARTITION BY RANGE (a) - CREATE TABLE pk11 PARTITION OF pk1 FOR VALUES FROM (30) TO (40); -INSERT INTO fkpart9.pk VALUES (35); -INSERT INTO fkpart9.fk VALUES (35); -DELETE FROM fkpart9.pk WHERE a=35; -SELECT * FROM fkpart9.pk; -SELECT * FROM fkpart9.fk; -DROP SCHEMA fkpart9 CASCADE; - --- test that ri_Check_Pk_Match() scans the correct partition for a deferred --- ON DELETE/UPDATE NO ACTION constraint -CREATE SCHEMA fkpart10 - CREATE TABLE tbl1(f1 int PRIMARY KEY) PARTITION BY RANGE(f1) - CREATE TABLE tbl1_p1 PARTITION OF tbl1 FOR VALUES FROM (minvalue) TO (1) - CREATE TABLE tbl1_p2 PARTITION OF tbl1 FOR VALUES FROM (1) TO (maxvalue) - CREATE TABLE tbl2(f1 int REFERENCES tbl1 DEFERRABLE INITIALLY DEFERRED) - CREATE TABLE tbl3(f1 int PRIMARY KEY) PARTITION BY RANGE(f1) - CREATE TABLE tbl3_p1 PARTITION OF tbl3 FOR VALUES FROM (minvalue) TO (1) - CREATE TABLE tbl3_p2 PARTITION OF tbl3 FOR VALUES FROM (1) TO (maxvalue) - CREATE TABLE tbl4(f1 int REFERENCES tbl3 DEFERRABLE INITIALLY DEFERRED); -INSERT INTO fkpart10.tbl1 VALUES (0), (1); -INSERT INTO fkpart10.tbl2 VALUES (0), (1); -INSERT INTO fkpart10.tbl3 VALUES (-2), (-1), (0); -INSERT INTO fkpart10.tbl4 VALUES (-2), (-1); -BEGIN; -DELETE FROM fkpart10.tbl1 WHERE f1 = 0; -UPDATE fkpart10.tbl1 SET f1 = 2 WHERE f1 = 1; -INSERT INTO fkpart10.tbl1 VALUES (0), (1); -COMMIT; - --- test that cross-partition updates correctly enforces the foreign key --- restriction (specifically testing INITIAILLY DEFERRED) -BEGIN; -UPDATE fkpart10.tbl1 SET f1 = 3 WHERE f1 = 0; -UPDATE fkpart10.tbl3 SET f1 = f1 * -1; -INSERT INTO fkpart10.tbl1 VALUES (4); -COMMIT; - -BEGIN; -UPDATE fkpart10.tbl3 SET f1 = f1 * -1; -UPDATE fkpart10.tbl3 SET f1 = f1 + 3; -UPDATE fkpart10.tbl1 SET f1 = 3 WHERE f1 = 0; -INSERT INTO fkpart10.tbl1 VALUES (0); -COMMIT; - -BEGIN; -UPDATE fkpart10.tbl3 SET f1 = f1 * -1; -UPDATE fkpart10.tbl1 SET f1 = 3 WHERE f1 = 0; -INSERT INTO fkpart10.tbl1 VALUES (0); -INSERT INTO fkpart10.tbl3 VALUES (-2), (-1); -COMMIT; - --- test where the updated table now has both an IMMEDIATE and a DEFERRED --- constraint pointing into it -CREATE TABLE fkpart10.tbl5(f1 int REFERENCES fkpart10.tbl3); -INSERT INTO fkpart10.tbl5 VALUES (-2), (-1); -BEGIN; -UPDATE fkpart10.tbl3 SET f1 = f1 * -3; -COMMIT; - --- Now test where the row referenced from the table with an IMMEDIATE --- constraint stays in place, while those referenced from the table with a --- DEFERRED constraint don't. -DELETE FROM fkpart10.tbl5; -INSERT INTO fkpart10.tbl5 VALUES (0); -BEGIN; -UPDATE fkpart10.tbl3 SET f1 = f1 * -3; -COMMIT; - -DROP SCHEMA fkpart10 CASCADE; - --- verify foreign keys are enforced during cross-partition updates, --- especially on the PK side -CREATE SCHEMA fkpart11 - CREATE TABLE pk (a INT PRIMARY KEY, b text) PARTITION BY LIST (a) - CREATE TABLE fk ( - a INT, - CONSTRAINT fkey FOREIGN KEY (a) REFERENCES pk(a) ON UPDATE CASCADE ON DELETE CASCADE - ) - CREATE TABLE fk_parted ( - a INT PRIMARY KEY, - CONSTRAINT fkey FOREIGN KEY (a) REFERENCES pk(a) ON UPDATE CASCADE ON DELETE CASCADE - ) PARTITION BY LIST (a) - CREATE TABLE fk_another ( - a INT, - CONSTRAINT fkey FOREIGN KEY (a) REFERENCES fk_parted (a) ON UPDATE CASCADE ON DELETE CASCADE - ) - CREATE TABLE pk1 PARTITION OF pk FOR VALUES IN (1, 2) PARTITION BY LIST (a) - CREATE TABLE pk2 PARTITION OF pk FOR VALUES IN (3) - CREATE TABLE pk3 PARTITION OF pk FOR VALUES IN (4) - CREATE TABLE fk1 PARTITION OF fk_parted FOR VALUES IN (1, 2) - CREATE TABLE fk2 PARTITION OF fk_parted FOR VALUES IN (3) - CREATE TABLE fk3 PARTITION OF fk_parted FOR VALUES IN (4); -CREATE TABLE fkpart11.pk11 (b text, a int NOT NULL); -ALTER TABLE fkpart11.pk1 ATTACH PARTITION fkpart11.pk11 FOR VALUES IN (1); -CREATE TABLE fkpart11.pk12 (b text, c int, a int NOT NULL); -ALTER TABLE fkpart11.pk12 DROP c; -ALTER TABLE fkpart11.pk1 ATTACH PARTITION fkpart11.pk12 FOR VALUES IN (2); -INSERT INTO fkpart11.pk VALUES (1, 'xxx'), (3, 'yyy'); -INSERT INTO fkpart11.fk VALUES (1), (3); -INSERT INTO fkpart11.fk_parted VALUES (1), (3); -INSERT INTO fkpart11.fk_another VALUES (1), (3); --- moves 2 rows from one leaf partition to another, with both updates being --- cascaded to fk and fk_parted. Updates of fk_parted, of which one is --- cross-partition (3 -> 4), are further cascaded to fk_another. -UPDATE fkpart11.pk SET a = a + 1 RETURNING tableoid::pg_catalog.regclass, *; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk_parted; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk_another; - --- let's try with the foreign key pointing at tables in the partition tree --- that are not the same as the query's target table - --- 1. foreign key pointing into a non-root ancestor --- --- A cross-partition update on the root table will fail, because we currently --- can't enforce the foreign keys pointing into a non-leaf partition -ALTER TABLE fkpart11.fk DROP CONSTRAINT fkey; -DELETE FROM fkpart11.fk WHERE a = 4; -ALTER TABLE fkpart11.fk ADD CONSTRAINT fkey FOREIGN KEY (a) REFERENCES fkpart11.pk1 (a) ON UPDATE CASCADE ON DELETE CASCADE; -UPDATE fkpart11.pk SET a = a - 1; --- it's okay though if the non-leaf partition is updated directly -UPDATE fkpart11.pk1 SET a = a - 1; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.pk; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk_parted; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk_another; - --- 2. foreign key pointing into a single leaf partition --- --- A cross-partition update that deletes from the pointed-to leaf partition --- is allowed to succeed -ALTER TABLE fkpart11.fk DROP CONSTRAINT fkey; -ALTER TABLE fkpart11.fk ADD CONSTRAINT fkey FOREIGN KEY (a) REFERENCES fkpart11.pk11 (a) ON UPDATE CASCADE ON DELETE CASCADE; --- will delete (1) from p11 which is cascaded to fk -UPDATE fkpart11.pk SET a = a + 1 WHERE a = 1; -SELECT tableoid::pg_catalog.regclass, * FROM fkpart11.fk; -DROP TABLE fkpart11.fk; - --- check that regular and deferrable AR triggers on the PK tables --- still work as expected -CREATE FUNCTION fkpart11.print_row () RETURNS TRIGGER LANGUAGE plpgsql AS $$ - BEGIN - RAISE NOTICE 'TABLE: %, OP: %, OLD: %, NEW: %', TG_RELNAME, TG_OP, OLD, NEW; - RETURN NULL; - END; -$$; -CREATE TRIGGER trig_upd_pk AFTER UPDATE ON fkpart11.pk FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row(); -CREATE TRIGGER trig_del_pk AFTER DELETE ON fkpart11.pk FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row(); -CREATE TRIGGER trig_ins_pk AFTER INSERT ON fkpart11.pk FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row(); -CREATE CONSTRAINT TRIGGER trig_upd_fk_parted AFTER UPDATE ON fkpart11.fk_parted INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row(); -CREATE CONSTRAINT TRIGGER trig_del_fk_parted AFTER DELETE ON fkpart11.fk_parted INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row(); -CREATE CONSTRAINT TRIGGER trig_ins_fk_parted AFTER INSERT ON fkpart11.fk_parted INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION fkpart11.print_row(); -UPDATE fkpart11.pk SET a = 3 WHERE a = 4; -UPDATE fkpart11.pk SET a = 1 WHERE a = 2; - -DROP SCHEMA fkpart11 CASCADE; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgenerated.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgenerated.sql deleted file mode 100644 index 378297e6ea..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgenerated.sql +++ /dev/null @@ -1,583 +0,0 @@ --- sanity check of system catalog -SELECT attrelid, attname, attgenerated FROM pg_attribute WHERE attgenerated NOT IN ('', 's'); - - -CREATE TABLE gtest0 (a int PRIMARY KEY, b int GENERATED ALWAYS AS (55) STORED); -CREATE TABLE gtest1 (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED); - -SELECT table_name, column_name, column_default, is_nullable, is_generated, generation_expression FROM information_schema.columns WHERE table_name LIKE 'gtest_' ORDER BY 1, 2; - -SELECT table_name, column_name, dependent_column FROM information_schema.column_column_usage ORDER BY 1, 2, 3; - -\d gtest1 - --- duplicate generated -CREATE TABLE gtest_err_1 (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED GENERATED ALWAYS AS (a * 3) STORED); - --- references to other generated columns, including self-references -CREATE TABLE gtest_err_2a (a int PRIMARY KEY, b int GENERATED ALWAYS AS (b * 2) STORED); -CREATE TABLE gtest_err_2b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED, c int GENERATED ALWAYS AS (b * 3) STORED); --- a whole-row var is a self-reference on steroids, so disallow that too -CREATE TABLE gtest_err_2c (a int PRIMARY KEY, - b int GENERATED ALWAYS AS (num_nulls(gtest_err_2c)) STORED); - --- invalid reference -CREATE TABLE gtest_err_3 (a int PRIMARY KEY, b int GENERATED ALWAYS AS (c * 2) STORED); - --- generation expression must be immutable -CREATE TABLE gtest_err_4 (a int PRIMARY KEY, b double precision GENERATED ALWAYS AS (random()) STORED); - --- cannot have default/identity and generated -CREATE TABLE gtest_err_5a (a int PRIMARY KEY, b int DEFAULT 5 GENERATED ALWAYS AS (a * 2) STORED); -CREATE TABLE gtest_err_5b (a int PRIMARY KEY, b int GENERATED ALWAYS AS identity GENERATED ALWAYS AS (a * 2) STORED); - --- reference to system column not allowed in generated column --- (except tableoid, which we test below) -CREATE TABLE gtest_err_6a (a int PRIMARY KEY, b bool GENERATED ALWAYS AS (xmin <> 37) STORED); - --- various prohibited constructs -CREATE TABLE gtest_err_7a (a int PRIMARY KEY, b int GENERATED ALWAYS AS (avg(a)) STORED); -CREATE TABLE gtest_err_7b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (row_number() OVER (ORDER BY a)) STORED); -CREATE TABLE gtest_err_7c (a int PRIMARY KEY, b int GENERATED ALWAYS AS ((SELECT a)) STORED); -CREATE TABLE gtest_err_7d (a int PRIMARY KEY, b int GENERATED ALWAYS AS (generate_series(1, a)) STORED); - --- GENERATED BY DEFAULT not allowed -CREATE TABLE gtest_err_8 (a int PRIMARY KEY, b int GENERATED BY DEFAULT AS (a * 2) STORED); - -INSERT INTO gtest1 VALUES (1); -INSERT INTO gtest1 VALUES (2, DEFAULT); -- ok -INSERT INTO gtest1 VALUES (3, 33); -- error -INSERT INTO gtest1 VALUES (3, 33), (4, 44); -- error -INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error -INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error -INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok - -SELECT * FROM gtest1 ORDER BY a; -DELETE FROM gtest1 WHERE a >= 3; - -UPDATE gtest1 SET b = DEFAULT WHERE a = 1; -UPDATE gtest1 SET b = 11 WHERE a = 1; -- error - -SELECT * FROM gtest1 ORDER BY a; - -SELECT a, b, b * 2 AS b2 FROM gtest1 ORDER BY a; -SELECT a, b FROM gtest1 WHERE b = 4 ORDER BY a; - --- test that overflow error happens on write -INSERT INTO gtest1 VALUES (2000000000); -SELECT * FROM gtest1; -DELETE FROM gtest1 WHERE a = 2000000000; - --- test with joins -CREATE TABLE gtestx (x int, y int); -INSERT INTO gtestx VALUES (11, 1), (22, 2), (33, 3); -SELECT * FROM gtestx, gtest1 WHERE gtestx.y = gtest1.a; -DROP TABLE gtestx; - --- test UPDATE/DELETE quals -SELECT * FROM gtest1 ORDER BY a; -UPDATE gtest1 SET a = 3 WHERE b = 4; -SELECT * FROM gtest1 ORDER BY a; -DELETE FROM gtest1 WHERE b = 2; -SELECT * FROM gtest1 ORDER BY a; - --- views -CREATE VIEW gtest1v AS SELECT * FROM gtest1; -SELECT * FROM gtest1v; -INSERT INTO gtest1v VALUES (4, 8); -- error -INSERT INTO gtest1v VALUES (5, DEFAULT); -- ok -INSERT INTO gtest1v VALUES (6, 66), (7, 77); -- error -INSERT INTO gtest1v VALUES (6, DEFAULT), (7, 77); -- error -INSERT INTO gtest1v VALUES (6, 66), (7, DEFAULT); -- error -INSERT INTO gtest1v VALUES (6, DEFAULT), (7, DEFAULT); -- ok - -ALTER VIEW gtest1v ALTER COLUMN b SET DEFAULT 100; -INSERT INTO gtest1v VALUES (8, DEFAULT); -- error -INSERT INTO gtest1v VALUES (8, DEFAULT), (9, DEFAULT); -- error - -SELECT * FROM gtest1v; -DELETE FROM gtest1v WHERE a >= 5; -DROP VIEW gtest1v; - --- CTEs -WITH foo AS (SELECT * FROM gtest1) SELECT * FROM foo; - --- inheritance -CREATE TABLE gtest1_1 () INHERITS (gtest1); -SELECT * FROM gtest1_1; -\d gtest1_1 -INSERT INTO gtest1_1 VALUES (4); -SELECT * FROM gtest1_1; -SELECT * FROM gtest1; - -CREATE TABLE gtest_normal (a int, b int); -CREATE TABLE gtest_normal_child (a int, b int GENERATED ALWAYS AS (a * 2) STORED) INHERITS (gtest_normal); -\d gtest_normal_child -INSERT INTO gtest_normal (a) VALUES (1); -INSERT INTO gtest_normal_child (a) VALUES (2); -SELECT * FROM gtest_normal; - -CREATE TABLE gtest_normal_child2 (a int, b int GENERATED ALWAYS AS (a * 3) STORED); -ALTER TABLE gtest_normal_child2 INHERIT gtest_normal; -INSERT INTO gtest_normal_child2 (a) VALUES (3); -SELECT * FROM gtest_normal; - --- test inheritance mismatches between parent and child -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS (a * 22) STORED) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int DEFAULT 10) INHERITS (gtest1); -- error -CREATE TABLE gtestx (x int, b int GENERATED ALWAYS AS IDENTITY) INHERITS (gtest1); -- error - -CREATE TABLE gtestxx_1 (a int NOT NULL, b int); -ALTER TABLE gtestxx_1 INHERIT gtest1; -- error -CREATE TABLE gtestxx_2 (a int NOT NULL, b int GENERATED ALWAYS AS (a * 22) STORED); -ALTER TABLE gtestxx_2 INHERIT gtest1; -- error -CREATE TABLE gtestxx_3 (a int NOT NULL, b int GENERATED ALWAYS AS (a * 2) STORED); -ALTER TABLE gtestxx_3 INHERIT gtest1; -- ok -CREATE TABLE gtestxx_4 (b int GENERATED ALWAYS AS (a * 2) STORED, a int NOT NULL); -ALTER TABLE gtestxx_4 INHERIT gtest1; -- ok - --- test multiple inheritance mismatches -CREATE TABLE gtesty (x int, b int); -CREATE TABLE gtest1_2 () INHERITS (gtest1, gtesty); -- error -DROP TABLE gtesty; - -CREATE TABLE gtesty (x int, b int GENERATED ALWAYS AS (x * 22) STORED); -CREATE TABLE gtest1_2 () INHERITS (gtest1, gtesty); -- error -DROP TABLE gtesty; - -CREATE TABLE gtesty (x int, b int DEFAULT 55); -CREATE TABLE gtest1_2 () INHERITS (gtest0, gtesty); -- error -DROP TABLE gtesty; - --- test stored update -CREATE TABLE gtest3 (a int, b int GENERATED ALWAYS AS (a * 3) STORED); -INSERT INTO gtest3 (a) VALUES (1), (2), (3), (NULL); -SELECT * FROM gtest3 ORDER BY a; -UPDATE gtest3 SET a = 22 WHERE a = 2; -SELECT * FROM gtest3 ORDER BY a; - -CREATE TABLE gtest3a (a text, b text GENERATED ALWAYS AS (a || '+' || a) STORED); -INSERT INTO gtest3a (a) VALUES ('a'), ('b'), ('c'), (NULL); -SELECT * FROM gtest3a ORDER BY a; -UPDATE gtest3a SET a = 'bb' WHERE a = 'b'; -SELECT * FROM gtest3a ORDER BY a; - --- COPY -TRUNCATE gtest1; -INSERT INTO gtest1 (a) VALUES (1), (2); - -COPY gtest1 TO stdout; - -COPY gtest1 (a, b) TO stdout; - -COPY gtest1 FROM stdin; -3 -4 -\. - -COPY gtest1 (a, b) FROM stdin; - -SELECT * FROM gtest1 ORDER BY a; - -TRUNCATE gtest3; -INSERT INTO gtest3 (a) VALUES (1), (2); - -COPY gtest3 TO stdout; - -COPY gtest3 (a, b) TO stdout; - -COPY gtest3 FROM stdin; -3 -4 -\. - -COPY gtest3 (a, b) FROM stdin; - -SELECT * FROM gtest3 ORDER BY a; - --- null values -CREATE TABLE gtest2 (a int PRIMARY KEY, b int GENERATED ALWAYS AS (NULL) STORED); -INSERT INTO gtest2 VALUES (1); -SELECT * FROM gtest2; - --- simple column reference for varlena types -CREATE TABLE gtest_varlena (a varchar, b varchar GENERATED ALWAYS AS (a) STORED); -INSERT INTO gtest_varlena (a) VALUES('01234567890123456789'); -INSERT INTO gtest_varlena (a) VALUES(NULL); -SELECT * FROM gtest_varlena ORDER BY a; -DROP TABLE gtest_varlena; - --- composite types -CREATE TYPE double_int as (a int, b int); -CREATE TABLE gtest4 ( - a int, - b double_int GENERATED ALWAYS AS ((a * 2, a * 3)) STORED -); -INSERT INTO gtest4 VALUES (1), (6); -SELECT * FROM gtest4; - -DROP TABLE gtest4; -DROP TYPE double_int; - --- using tableoid is allowed -CREATE TABLE gtest_tableoid ( - a int PRIMARY KEY, - b bool GENERATED ALWAYS AS (tableoid = 'gtest_tableoid'::regclass) STORED -); -INSERT INTO gtest_tableoid VALUES (1), (2); -ALTER TABLE gtest_tableoid ADD COLUMN - c regclass GENERATED ALWAYS AS (tableoid) STORED; -SELECT * FROM gtest_tableoid; - --- drop column behavior -CREATE TABLE gtest10 (a int PRIMARY KEY, b int, c int GENERATED ALWAYS AS (b * 2) STORED); -ALTER TABLE gtest10 DROP COLUMN b; -- fails -ALTER TABLE gtest10 DROP COLUMN b CASCADE; -- drops c too - -\d gtest10 - -CREATE TABLE gtest10a (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED); -ALTER TABLE gtest10a DROP COLUMN b; -INSERT INTO gtest10a (a) VALUES (1); - --- privileges -CREATE USER regress_user11; - -CREATE TABLE gtest11s (a int PRIMARY KEY, b int, c int GENERATED ALWAYS AS (b * 2) STORED); -INSERT INTO gtest11s VALUES (1, 10), (2, 20); -GRANT SELECT (a, c) ON gtest11s TO regress_user11; - -CREATE FUNCTION gf1(a int) RETURNS int AS $$ SELECT a * 3 $$ IMMUTABLE LANGUAGE SQL; -REVOKE ALL ON FUNCTION gf1(int) FROM PUBLIC; - -CREATE TABLE gtest12s (a int PRIMARY KEY, b int, c int GENERATED ALWAYS AS (gf1(b)) STORED); -INSERT INTO gtest12s VALUES (1, 10), (2, 20); -GRANT SELECT (a, c) ON gtest12s TO regress_user11; - -SET ROLE regress_user11; -SELECT a, b FROM gtest11s; -- not allowed -SELECT a, c FROM gtest11s; -- allowed -SELECT gf1(10); -- not allowed -SELECT a, c FROM gtest12s; -- allowed -RESET ROLE; - -DROP FUNCTION gf1(int); -- fail -DROP TABLE gtest11s, gtest12s; -DROP FUNCTION gf1(int); -DROP USER regress_user11; - --- check constraints -CREATE TABLE gtest20 (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED CHECK (b < 50)); -INSERT INTO gtest20 (a) VALUES (10); -- ok -INSERT INTO gtest20 (a) VALUES (30); -- violates constraint - -CREATE TABLE gtest20a (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED); -INSERT INTO gtest20a (a) VALUES (10); -INSERT INTO gtest20a (a) VALUES (30); -ALTER TABLE gtest20a ADD CHECK (b < 50); -- fails on existing row - -CREATE TABLE gtest20b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED); -INSERT INTO gtest20b (a) VALUES (10); -INSERT INTO gtest20b (a) VALUES (30); -ALTER TABLE gtest20b ADD CONSTRAINT chk CHECK (b < 50) NOT VALID; -ALTER TABLE gtest20b VALIDATE CONSTRAINT chk; -- fails on existing row - --- not-null constraints -CREATE TABLE gtest21a (a int PRIMARY KEY, b int GENERATED ALWAYS AS (nullif(a, 0)) STORED NOT NULL); -INSERT INTO gtest21a (a) VALUES (1); -- ok -INSERT INTO gtest21a (a) VALUES (0); -- violates constraint - -CREATE TABLE gtest21b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (nullif(a, 0)) STORED); -ALTER TABLE gtest21b ALTER COLUMN b SET NOT NULL; -INSERT INTO gtest21b (a) VALUES (1); -- ok -INSERT INTO gtest21b (a) VALUES (0); -- violates constraint -ALTER TABLE gtest21b ALTER COLUMN b DROP NOT NULL; -INSERT INTO gtest21b (a) VALUES (0); -- ok now - --- index constraints -CREATE TABLE gtest22a (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a / 2) STORED UNIQUE); -INSERT INTO gtest22a VALUES (2); -INSERT INTO gtest22a VALUES (3); -INSERT INTO gtest22a VALUES (4); -CREATE TABLE gtest22b (a int, b int GENERATED ALWAYS AS (a / 2) STORED, PRIMARY KEY (a, b)); -INSERT INTO gtest22b VALUES (2); -INSERT INTO gtest22b VALUES (2); - --- indexes -CREATE TABLE gtest22c (a int, b int GENERATED ALWAYS AS (a * 2) STORED); -CREATE INDEX gtest22c_b_idx ON gtest22c (b); -CREATE INDEX gtest22c_expr_idx ON gtest22c ((b * 3)); -CREATE INDEX gtest22c_pred_idx ON gtest22c (a) WHERE b > 0; -\d gtest22c - -INSERT INTO gtest22c VALUES (1), (2), (3); -SET enable_seqscan TO off; -SET enable_bitmapscan TO off; -EXPLAIN (COSTS OFF) SELECT * FROM gtest22c WHERE b = 4; -SELECT * FROM gtest22c WHERE b = 4; -EXPLAIN (COSTS OFF) SELECT * FROM gtest22c WHERE b * 3 = 6; -SELECT * FROM gtest22c WHERE b * 3 = 6; -EXPLAIN (COSTS OFF) SELECT * FROM gtest22c WHERE a = 1 AND b > 0; -SELECT * FROM gtest22c WHERE a = 1 AND b > 0; -RESET enable_seqscan; -RESET enable_bitmapscan; - --- foreign keys -CREATE TABLE gtest23a (x int PRIMARY KEY, y int); -INSERT INTO gtest23a VALUES (1, 11), (2, 22), (3, 33); - -CREATE TABLE gtest23x (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED REFERENCES gtest23a (x) ON UPDATE CASCADE); -- error -CREATE TABLE gtest23x (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED REFERENCES gtest23a (x) ON DELETE SET NULL); -- error - -CREATE TABLE gtest23b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (a * 2) STORED REFERENCES gtest23a (x)); -\d gtest23b - -INSERT INTO gtest23b VALUES (1); -- ok -INSERT INTO gtest23b VALUES (5); -- error - -DROP TABLE gtest23b; -DROP TABLE gtest23a; - -CREATE TABLE gtest23p (x int, y int GENERATED ALWAYS AS (x * 2) STORED, PRIMARY KEY (y)); -INSERT INTO gtest23p VALUES (1), (2), (3); - -CREATE TABLE gtest23q (a int PRIMARY KEY, b int REFERENCES gtest23p (y)); -INSERT INTO gtest23q VALUES (1, 2); -- ok -INSERT INTO gtest23q VALUES (2, 5); -- error - --- domains -CREATE DOMAIN gtestdomain1 AS int CHECK (VALUE < 10); -CREATE TABLE gtest24 (a int PRIMARY KEY, b gtestdomain1 GENERATED ALWAYS AS (a * 2) STORED); -INSERT INTO gtest24 (a) VALUES (4); -- ok -INSERT INTO gtest24 (a) VALUES (6); -- error - --- typed tables (currently not supported) -CREATE TYPE gtest_type AS (f1 integer, f2 text, f3 bigint); -CREATE TABLE gtest28 OF gtest_type (f1 WITH OPTIONS GENERATED ALWAYS AS (f2 *2) STORED); -DROP TYPE gtest_type CASCADE; - --- table partitions (currently not supported) -CREATE TABLE gtest_parent (f1 date NOT NULL, f2 text, f3 bigint) PARTITION BY RANGE (f1); -CREATE TABLE gtest_child PARTITION OF gtest_parent ( - f3 WITH OPTIONS GENERATED ALWAYS AS (f2 * 2) STORED -) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -- error -DROP TABLE gtest_parent; - --- partitioned table -CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 2) STORED) PARTITION BY RANGE (f1); -CREATE TABLE gtest_child PARTITION OF gtest_parent FOR VALUES FROM ('2016-07-01') TO ('2016-08-01'); -INSERT INTO gtest_parent (f1, f2) VALUES ('2016-07-15', 1); -SELECT * FROM gtest_parent; -SELECT * FROM gtest_child; -DROP TABLE gtest_parent; - --- generated columns in partition key (not allowed) -CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 2) STORED) PARTITION BY RANGE (f3); -CREATE TABLE gtest_parent (f1 date NOT NULL, f2 bigint, f3 bigint GENERATED ALWAYS AS (f2 * 2) STORED) PARTITION BY RANGE ((f3 * 3)); - --- ALTER TABLE ... ADD COLUMN -CREATE TABLE gtest25 (a int PRIMARY KEY); -INSERT INTO gtest25 VALUES (3), (4); -ALTER TABLE gtest25 ADD COLUMN b int GENERATED ALWAYS AS (a * 3) STORED; -SELECT * FROM gtest25 ORDER BY a; -ALTER TABLE gtest25 ADD COLUMN x int GENERATED ALWAYS AS (b * 4) STORED; -- error -ALTER TABLE gtest25 ADD COLUMN x int GENERATED ALWAYS AS (z * 4) STORED; -- error -ALTER TABLE gtest25 ADD COLUMN c int DEFAULT 42, - ADD COLUMN x int GENERATED ALWAYS AS (c * 4) STORED; -ALTER TABLE gtest25 ADD COLUMN d int DEFAULT 101; -ALTER TABLE gtest25 ALTER COLUMN d SET DATA TYPE float8, - ADD COLUMN y float8 GENERATED ALWAYS AS (d * 4) STORED; -SELECT * FROM gtest25 ORDER BY a; -\d gtest25 - --- ALTER TABLE ... ALTER COLUMN -CREATE TABLE gtest27 ( - a int, - b int, - x int GENERATED ALWAYS AS ((a + b) * 2) STORED -); -INSERT INTO gtest27 (a, b) VALUES (3, 7), (4, 11); -ALTER TABLE gtest27 ALTER COLUMN a TYPE text; -- error -ALTER TABLE gtest27 ALTER COLUMN x TYPE numeric; -\d gtest27 -SELECT * FROM gtest27; -ALTER TABLE gtest27 ALTER COLUMN x TYPE boolean USING x <> 0; -- error -ALTER TABLE gtest27 ALTER COLUMN x DROP DEFAULT; -- error --- It's possible to alter the column types this way: -ALTER TABLE gtest27 - DROP COLUMN x, - ALTER COLUMN a TYPE bigint, - ALTER COLUMN b TYPE bigint, - ADD COLUMN x bigint GENERATED ALWAYS AS ((a + b) * 2) STORED; -\d gtest27 --- Ideally you could just do this, but not today (and should x change type?): -ALTER TABLE gtest27 - ALTER COLUMN a TYPE float8, - ALTER COLUMN b TYPE float8; -- error -\d gtest27 -SELECT * FROM gtest27; - --- ALTER TABLE ... ALTER COLUMN ... DROP EXPRESSION -CREATE TABLE gtest29 ( - a int, - b int GENERATED ALWAYS AS (a * 2) STORED -); -INSERT INTO gtest29 (a) VALUES (3), (4); -ALTER TABLE gtest29 ALTER COLUMN a DROP EXPRESSION; -- error -ALTER TABLE gtest29 ALTER COLUMN a DROP EXPRESSION IF EXISTS; -- notice -ALTER TABLE gtest29 ALTER COLUMN b DROP EXPRESSION; -INSERT INTO gtest29 (a) VALUES (5); -INSERT INTO gtest29 (a, b) VALUES (6, 66); -SELECT * FROM gtest29; -\d gtest29 - --- check that dependencies between columns have also been removed -ALTER TABLE gtest29 DROP COLUMN a; -- should not drop b -\d gtest29 - --- with inheritance -CREATE TABLE gtest30 ( - a int, - b int GENERATED ALWAYS AS (a * 2) STORED -); -CREATE TABLE gtest30_1 () INHERITS (gtest30); -ALTER TABLE gtest30 ALTER COLUMN b DROP EXPRESSION; -\d gtest30 -\d gtest30_1 -DROP TABLE gtest30 CASCADE; -CREATE TABLE gtest30 ( - a int, - b int GENERATED ALWAYS AS (a * 2) STORED -); -CREATE TABLE gtest30_1 () INHERITS (gtest30); -ALTER TABLE ONLY gtest30 ALTER COLUMN b DROP EXPRESSION; -- error -\d gtest30 -\d gtest30_1 -ALTER TABLE gtest30_1 ALTER COLUMN b DROP EXPRESSION; -- error - --- triggers -CREATE TABLE gtest26 ( - a int PRIMARY KEY, - b int GENERATED ALWAYS AS (a * 2) STORED -); - -CREATE FUNCTION gtest_trigger_func() RETURNS trigger - LANGUAGE plpgsql -AS $$ -BEGIN - IF tg_op IN ('DELETE', 'UPDATE') THEN - RAISE INFO '%: %: old = %', TG_NAME, TG_WHEN, OLD; - END IF; - IF tg_op IN ('INSERT', 'UPDATE') THEN - RAISE INFO '%: %: new = %', TG_NAME, TG_WHEN, NEW; - END IF; - IF tg_op = 'DELETE' THEN - RETURN OLD; - ELSE - RETURN NEW; - END IF; -END -$$; - -CREATE TRIGGER gtest1 BEFORE DELETE OR UPDATE ON gtest26 - FOR EACH ROW - WHEN (OLD.b < 0) -- ok - EXECUTE PROCEDURE gtest_trigger_func(); - -CREATE TRIGGER gtest2a BEFORE INSERT OR UPDATE ON gtest26 - FOR EACH ROW - WHEN (NEW.b < 0) -- error - EXECUTE PROCEDURE gtest_trigger_func(); - -CREATE TRIGGER gtest2b BEFORE INSERT OR UPDATE ON gtest26 - FOR EACH ROW - WHEN (NEW.* IS NOT NULL) -- error - EXECUTE PROCEDURE gtest_trigger_func(); - -CREATE TRIGGER gtest2 BEFORE INSERT ON gtest26 - FOR EACH ROW - WHEN (NEW.a < 0) - EXECUTE PROCEDURE gtest_trigger_func(); - -CREATE TRIGGER gtest3 AFTER DELETE OR UPDATE ON gtest26 - FOR EACH ROW - WHEN (OLD.b < 0) -- ok - EXECUTE PROCEDURE gtest_trigger_func(); - -CREATE TRIGGER gtest4 AFTER INSERT OR UPDATE ON gtest26 - FOR EACH ROW - WHEN (NEW.b < 0) -- ok - EXECUTE PROCEDURE gtest_trigger_func(); - -INSERT INTO gtest26 (a) VALUES (-2), (0), (3); -SELECT * FROM gtest26 ORDER BY a; -UPDATE gtest26 SET a = a * -2; -SELECT * FROM gtest26 ORDER BY a; -DELETE FROM gtest26 WHERE a = -6; -SELECT * FROM gtest26 ORDER BY a; - -DROP TRIGGER gtest1 ON gtest26; -DROP TRIGGER gtest2 ON gtest26; -DROP TRIGGER gtest3 ON gtest26; - --- Check that an UPDATE of "a" fires the trigger for UPDATE OF b, per --- SQL standard. -CREATE FUNCTION gtest_trigger_func3() RETURNS trigger - LANGUAGE plpgsql -AS $$ -BEGIN - RAISE NOTICE 'OK'; - RETURN NEW; -END -$$; - -CREATE TRIGGER gtest11 BEFORE UPDATE OF b ON gtest26 - FOR EACH ROW - EXECUTE PROCEDURE gtest_trigger_func3(); - -UPDATE gtest26 SET a = 1 WHERE a = 0; - -DROP TRIGGER gtest11 ON gtest26; -TRUNCATE gtest26; - --- check that modifications of stored generated columns in triggers do --- not get propagated -CREATE FUNCTION gtest_trigger_func4() RETURNS trigger - LANGUAGE plpgsql -AS $$ -BEGIN - NEW.a = 10; - NEW.b = 300; - RETURN NEW; -END; -$$; - -CREATE TRIGGER gtest12_01 BEFORE UPDATE ON gtest26 - FOR EACH ROW - EXECUTE PROCEDURE gtest_trigger_func(); - -CREATE TRIGGER gtest12_02 BEFORE UPDATE ON gtest26 - FOR EACH ROW - EXECUTE PROCEDURE gtest_trigger_func4(); - -CREATE TRIGGER gtest12_03 BEFORE UPDATE ON gtest26 - FOR EACH ROW - EXECUTE PROCEDURE gtest_trigger_func(); - -INSERT INTO gtest26 (a) VALUES (1); -UPDATE gtest26 SET a = 11 WHERE a = 1; -SELECT * FROM gtest26 ORDER BY a; - --- LIKE INCLUDING GENERATED and dropped column handling -CREATE TABLE gtest28a ( - a int, - b int, - c int, - x int GENERATED ALWAYS AS (b * 2) STORED -); - -ALTER TABLE gtest28a DROP COLUMN a; - -CREATE TABLE gtest28b (LIKE gtest28a INCLUDING GENERATED); - -\d gtest28* diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgin.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgin.sql deleted file mode 100644 index 746880937b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgin.sql +++ /dev/null @@ -1,173 +0,0 @@ --- --- Test GIN indexes. --- --- There are other tests to test different GIN opclasses. This is for testing --- GIN itself. - --- Create and populate a test table with a GIN index. -create table gin_test_tbl(i int4[]) with (autovacuum_enabled = off); -create index gin_test_idx on gin_test_tbl using gin (i) - with (fastupdate = on, gin_pending_list_limit = 4096); -insert into gin_test_tbl select array[1, 2, g] from generate_series(1, 20000) g; -insert into gin_test_tbl select array[1, 3, g] from generate_series(1, 1000) g; - -select gin_clean_pending_list('gin_test_idx')>10 as many; -- flush the fastupdate buffers - -insert into gin_test_tbl select array[3, 1, g] from generate_series(1, 1000) g; - -vacuum gin_test_tbl; -- flush the fastupdate buffers - -select gin_clean_pending_list('gin_test_idx'); -- nothing to flush - --- Test vacuuming -delete from gin_test_tbl where i @> array[2]; -vacuum gin_test_tbl; - --- Disable fastupdate, and do more insertions. With fastupdate enabled, most --- insertions (by flushing the list pages) cause page splits. Without --- fastupdate, we get more churn in the GIN data leaf pages, and exercise the --- recompression codepaths. -alter index gin_test_idx set (fastupdate = off); - -insert into gin_test_tbl select array[1, 2, g] from generate_series(1, 1000) g; -insert into gin_test_tbl select array[1, 3, g] from generate_series(1, 1000) g; - -delete from gin_test_tbl where i @> array[2]; -vacuum gin_test_tbl; - --- Test for "rare && frequent" searches -explain (costs off) -select count(*) from gin_test_tbl where i @> array[1, 999]; - -select count(*) from gin_test_tbl where i @> array[1, 999]; - --- Very weak test for gin_fuzzy_search_limit -set gin_fuzzy_search_limit = 1000; - -explain (costs off) -select count(*) > 0 as ok from gin_test_tbl where i @> array[1]; - -select count(*) > 0 as ok from gin_test_tbl where i @> array[1]; - -reset gin_fuzzy_search_limit; - --- Test optimization of empty queries -create unlogged table t_gin_test_tbl(i int4[], j int4[]); -create index on t_gin_test_tbl using gin (i, j); -insert into t_gin_test_tbl -values - (null, null), - ('{}', null), - ('{1}', null), - ('{1,2}', null), - (null, '{}'), - (null, '{10}'), - ('{1,2}', '{10}'), - ('{2}', '{10}'), - ('{1,3}', '{}'), - ('{1,1}', '{10}'); - -set enable_seqscan = off; -explain (costs off) -select * from t_gin_test_tbl where array[0] <@ i; -select * from t_gin_test_tbl where array[0] <@ i; -select * from t_gin_test_tbl where array[0] <@ i and '{}'::int4[] <@ j; - -explain (costs off) -select * from t_gin_test_tbl where i @> '{}'; -select * from t_gin_test_tbl where i @> '{}'; - -create function explain_query_json(query_sql text) -returns table (explain_line json) -language plpgsql as -$$ -begin - set enable_seqscan = off; - set enable_bitmapscan = on; - return query execute 'EXPLAIN (ANALYZE, FORMAT json) ' || query_sql; -end; -$$; - -create function execute_text_query_index(query_sql text) -returns setof text -language plpgsql -as -$$ -begin - set enable_seqscan = off; - set enable_bitmapscan = on; - return query execute query_sql; -end; -$$; - -create function execute_text_query_heap(query_sql text) -returns setof text -language plpgsql -as -$$ -begin - set enable_seqscan = on; - set enable_bitmapscan = off; - return query execute query_sql; -end; -$$; - --- check number of rows returned by index and removed by recheck -select - query, - js->0->'Plan'->'Plans'->0->'Actual Rows' as "return by index", - js->0->'Plan'->'Rows Removed by Index Recheck' as "removed by recheck", - (res_index = res_heap) as "match" -from - (values - ($$ i @> '{}' $$), - ($$ j @> '{}' $$), - ($$ i @> '{}' and j @> '{}' $$), - ($$ i @> '{1}' $$), - ($$ i @> '{1}' and j @> '{}' $$), - ($$ i @> '{1}' and i @> '{}' and j @> '{}' $$), - ($$ j @> '{10}' $$), - ($$ j @> '{10}' and i @> '{}' $$), - ($$ j @> '{10}' and j @> '{}' and i @> '{}' $$), - ($$ i @> '{1}' and j @> '{10}' $$) - ) q(query), - lateral explain_query_json($$select * from t_gin_test_tbl where $$ || query) js, - lateral execute_text_query_index($$select string_agg((i, j)::text, ' ') from t_gin_test_tbl where $$ || query) res_index, - lateral execute_text_query_heap($$select string_agg((i, j)::text, ' ') from t_gin_test_tbl where $$ || query) res_heap; - -reset enable_seqscan; -reset enable_bitmapscan; - --- re-purpose t_gin_test_tbl to test scans involving posting trees -insert into t_gin_test_tbl select array[1, g, g/10], array[2, g, g/10] - from generate_series(1, 20000) g; - -select gin_clean_pending_list('t_gin_test_tbl_i_j_idx') is not null; - -analyze t_gin_test_tbl; - -set enable_seqscan = off; -set enable_bitmapscan = on; - -explain (costs off) -select count(*) from t_gin_test_tbl where j @> array[50]; -select count(*) from t_gin_test_tbl where j @> array[50]; -explain (costs off) -select count(*) from t_gin_test_tbl where j @> array[2]; -select count(*) from t_gin_test_tbl where j @> array[2]; -explain (costs off) -select count(*) from t_gin_test_tbl where j @> '{}'::int[]; -select count(*) from t_gin_test_tbl where j @> '{}'::int[]; - --- test vacuuming of posting trees -delete from t_gin_test_tbl where j @> array[2]; -vacuum t_gin_test_tbl; - -select count(*) from t_gin_test_tbl where j @> array[50]; -select count(*) from t_gin_test_tbl where j @> array[2]; -select count(*) from t_gin_test_tbl where j @> '{}'::int[]; - -reset enable_seqscan; -reset enable_bitmapscan; - -drop table t_gin_test_tbl; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgroupingsets.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgroupingsets.sql deleted file mode 100644 index 90ba27257a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fgroupingsets.sql +++ /dev/null @@ -1,592 +0,0 @@ --- --- grouping sets --- - --- test data sources - -create temp view gstest1(a,b,v) - as values (1,1,10),(1,1,11),(1,2,12),(1,2,13),(1,3,14), - (2,3,15), - (3,3,16),(3,4,17), - (4,1,18),(4,1,19); - -create temp table gstest2 (a integer, b integer, c integer, d integer, - e integer, f integer, g integer, h integer); -copy gstest2 from stdin; -1 1 1 1 1 1 1 1 -1 1 1 1 1 1 1 2 -1 1 1 1 1 1 2 2 -1 1 1 1 1 2 2 2 -1 1 1 1 2 2 2 2 -1 1 1 2 2 2 2 2 -1 1 2 2 2 2 2 2 -1 2 2 2 2 2 2 2 -2 2 2 2 2 2 2 2 -\. - -create temp table gstest3 (a integer, b integer, c integer, d integer); -copy gstest3 from stdin; -1 1 1 1 -2 2 2 2 -\. -alter table gstest3 add primary key (a); - -create temp table gstest4(id integer, v integer, - unhashable_col bit(4), unsortable_col xid); -insert into gstest4 -values (1,1,b'0000','1'), (2,2,b'0001','1'), - (3,4,b'0010','2'), (4,8,b'0011','2'), - (5,16,b'0000','2'), (6,32,b'0001','2'), - (7,64,b'0010','1'), (8,128,b'0011','1'); - -create temp table gstest_empty (a integer, b integer, v integer); - -create function gstest_data(v integer, out a integer, out b integer) - returns setof record - as $f$ - begin - return query select v, i from generate_series(1,3) i; - end; - $f$ language plpgsql; - --- basic functionality - -set enable_hashagg = false; -- test hashing explicitly later - --- simple rollup with multiple plain aggregates, with and without ordering --- (and with ordering differing from grouping) - -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by rollup (a,b); -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by rollup (a,b) order by a,b; -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by rollup (a,b) order by b desc, a; -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by rollup (a,b) order by coalesce(a,0)+coalesce(b,0); - --- various types of ordered aggs -select a, b, grouping(a,b), - array_agg(v order by v), - string_agg(v::text, ':' order by v desc), - percentile_disc(0.5) within group (order by v), - rank(1,2,12) within group (order by a,b,v) - from gstest1 group by rollup (a,b) order by a,b; - --- test usage of grouped columns in direct args of aggs -select grouping(a), a, array_agg(b), - rank(a) within group (order by b nulls first), - rank(a) within group (order by b nulls last) - from (values (1,1),(1,4),(1,5),(3,1),(3,2)) v(a,b) - group by rollup (a) order by a; - --- nesting with window functions -select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum - from gstest2 group by rollup (a,b) order by rsum, a, b; - --- nesting with grouping sets -select sum(c) from gstest2 - group by grouping sets((), grouping sets((), grouping sets(()))) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets((), grouping sets((), grouping sets(((a, b))))) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets(grouping sets(rollup(c), grouping sets(cube(c)))) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets(a, grouping sets(a, cube(b))) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets(grouping sets((a, (b)))) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets(grouping sets((a, b))) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets(grouping sets(a, grouping sets(a), a)) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets(grouping sets(a, grouping sets(a, grouping sets(a), ((a)), a, grouping sets(a), (a)), a)) - order by 1 desc; -select sum(c) from gstest2 - group by grouping sets((a,(a,b)), grouping sets((a,(a,b)),a)) - order by 1 desc; - --- empty input: first is 0 rows, second 1, third 3 etc. -select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),a); -select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),()); -select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),(),(),()); -select sum(v), count(*) from gstest_empty group by grouping sets ((),(),()); - --- empty input with joins tests some important code paths -select t1.a, t2.b, sum(t1.v), count(*) from gstest_empty t1, gstest_empty t2 - group by grouping sets ((t1.a,t2.b),()); - --- simple joins, var resolution, GROUPING on join vars -select t1.a, t2.b, grouping(t1.a, t2.b), sum(t1.v), max(t2.a) - from gstest1 t1, gstest2 t2 - group by grouping sets ((t1.a, t2.b), ()); - -select t1.a, t2.b, grouping(t1.a, t2.b), sum(t1.v), max(t2.a) - from gstest1 t1 join gstest2 t2 on (t1.a=t2.a) - group by grouping sets ((t1.a, t2.b), ()); - -select a, b, grouping(a, b), sum(t1.v), max(t2.c) - from gstest1 t1 join gstest2 t2 using (a,b) - group by grouping sets ((a, b), ()); - --- check that functionally dependent cols are not nulled -select a, d, grouping(a,b,c) - from gstest3 - group by grouping sets ((a,b), (a,c)); - --- check that distinct grouping columns are kept separate --- even if they are equal() -explain (costs off) -select g as alias1, g as alias2 - from generate_series(1,3) g - group by alias1, rollup(alias2); - -select g as alias1, g as alias2 - from generate_series(1,3) g - group by alias1, rollup(alias2); - --- check that pulled-up subquery outputs still go to null when appropriate -select four, x - from (select four, ten, 'foo'::text as x from tenk1) as t - group by grouping sets (four, x) - having x = 'foo'; - -select four, x || 'x' - from (select four, ten, 'foo'::text as x from tenk1) as t - group by grouping sets (four, x) - order by four; - -select (x+y)*1, sum(z) - from (select 1 as x, 2 as y, 3 as z) s - group by grouping sets (x+y, x); - -select x, not x as not_x, q2 from - (select *, q1 = 1 as x from int8_tbl i1) as t - group by grouping sets(x, q2) - order by x, q2; - --- check qual push-down rules for a subquery with grouping sets -explain (verbose, costs off) -select * from ( - select 1 as x, q1, sum(q2) - from int8_tbl i1 - group by grouping sets(1, 2) -) ss -where x = 1 and q1 = 123; - -select * from ( - select 1 as x, q1, sum(q2) - from int8_tbl i1 - group by grouping sets(1, 2) -) ss -where x = 1 and q1 = 123; - --- check handling of pulled-up SubPlan in GROUPING() argument (bug #17479) -explain (verbose, costs off) -select grouping(ss.x) -from int8_tbl i1 -cross join lateral (select (select i1.q1) as x) ss -group by ss.x; - -select grouping(ss.x) -from int8_tbl i1 -cross join lateral (select (select i1.q1) as x) ss -group by ss.x; - -explain (verbose, costs off) -select (select grouping(ss.x)) -from int8_tbl i1 -cross join lateral (select (select i1.q1) as x) ss -group by ss.x; - -select (select grouping(ss.x)) -from int8_tbl i1 -cross join lateral (select (select i1.q1) as x) ss -group by ss.x; - --- simple rescan tests - -select a, b, sum(v.x) - from (values (1),(2)) v(x), gstest_data(v.x) - group by rollup (a,b); - -select * - from (values (1),(2)) v(x), - lateral (select a, b, sum(v.x) from gstest_data(v.x) group by rollup (a,b)) s; - --- min max optimization should still work with GROUP BY () -explain (costs off) - select min(unique1) from tenk1 GROUP BY (); - --- Views with GROUPING SET queries -CREATE VIEW gstest_view AS select a, b, grouping(a,b), sum(c), count(*), max(c) - from gstest2 group by rollup ((a,b,c),(c,d)); - -select pg_get_viewdef('gstest_view'::regclass, true); - --- Nested queries with 3 or more levels of nesting -select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP(e,f); -select(select (select grouping(e,f) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP(e,f); -select(select (select grouping(c) from (values (1)) v2(c) GROUP BY c) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP(e,f); - --- Combinations of operations -select a, b, c, d from gstest2 group by rollup(a,b),grouping sets(c,d); -select a, b from (values (1,2),(2,3)) v(a,b) group by a,b, grouping sets(a); - --- Tests for chained aggregates -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by grouping sets ((a,b),(a+1,b+1),(a+2,b+2)) order by 3,6; -select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY ROLLUP((e+1),(f+1)); -select(select (select grouping(a,b) from (values (1)) v2(c)) from (values (1,2)) v1(a,b) group by (a,b)) from (values(6,7)) v3(e,f) GROUP BY CUBE((e+1),(f+1)) ORDER BY (e+1),(f+1); -select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum - from gstest2 group by cube (a,b) order by rsum, a, b; -select a, b, sum(c) from (values (1,1,10),(1,1,11),(1,2,12),(1,2,13),(1,3,14),(2,3,15),(3,3,16),(3,4,17),(4,1,18),(4,1,19)) v(a,b,c) group by rollup (a,b); -select a, b, sum(v.x) - from (values (1),(2)) v(x), gstest_data(v.x) - group by cube (a,b) order by a,b; - --- Test reordering of grouping sets -explain (costs off) -select * from gstest1 group by grouping sets((a,b,v),(v)) order by v,b,a; - --- Agg level check. This query should error out. -select (select grouping(a,b) from gstest2) from gstest2 group by a,b; - ---Nested queries -select a, b, sum(c), count(*) from gstest2 group by grouping sets (rollup(a,b),a); - --- HAVING queries -select ten, sum(distinct four) from onek a -group by grouping sets((ten,four),(ten)) -having exists (select 1 from onek b where sum(distinct a.four) = b.four); - --- Tests around pushdown of HAVING clauses, partially testing against previous bugs -select a,count(*) from gstest2 group by rollup(a) order by a; -select a,count(*) from gstest2 group by rollup(a) having a is distinct from 1 order by a; -explain (costs off) - select a,count(*) from gstest2 group by rollup(a) having a is distinct from 1 order by a; - -select v.c, (select count(*) from gstest2 group by () having v.c) - from (values (false),(true)) v(c) order by v.c; -explain (costs off) - select v.c, (select count(*) from gstest2 group by () having v.c) - from (values (false),(true)) v(c) order by v.c; - --- HAVING with GROUPING queries -select ten, grouping(ten) from onek -group by grouping sets(ten) having grouping(ten) >= 0 -order by 2,1; -select ten, grouping(ten) from onek -group by grouping sets(ten, four) having grouping(ten) > 0 -order by 2,1; -select ten, grouping(ten) from onek -group by rollup(ten) having grouping(ten) > 0 -order by 2,1; -select ten, grouping(ten) from onek -group by cube(ten) having grouping(ten) > 0 -order by 2,1; -select ten, grouping(ten) from onek -group by (ten) having grouping(ten) >= 0 -order by 2,1; - --- FILTER queries -select ten, sum(distinct four) filter (where four::text ~ '123') from onek a -group by rollup(ten); - --- More rescan tests -select * from (values (1),(2)) v(a) left join lateral (select v.a, four, ten, count(*) from onek group by cube(four,ten)) s on true order by v.a,four,ten; -select array(select row(v.a,s1.*) from (select two,four, count(*) from onek group by cube(two,four) order by two,four) s1) from (values (1),(2)) v(a); - --- Grouping on text columns -select sum(ten) from onek group by two, rollup(four::text) order by 1; -select sum(ten) from onek group by rollup(four::text), two order by 1; - --- hashing support - -set enable_hashagg = true; - --- failure cases - -select count(*) from gstest4 group by rollup(unhashable_col,unsortable_col); -select array_agg(v order by v) from gstest4 group by grouping sets ((id,unsortable_col),(id)); - --- simple cases - -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by grouping sets ((a),(b)) order by 3,1,2; -explain (costs off) select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by grouping sets ((a),(b)) order by 3,1,2; - -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by cube(a,b) order by 3,1,2; -explain (costs off) select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by cube(a,b) order by 3,1,2; - --- shouldn't try and hash -explain (costs off) - select a, b, grouping(a,b), array_agg(v order by v) - from gstest1 group by cube(a,b); - --- unsortable cases -select unsortable_col, count(*) - from gstest4 group by grouping sets ((unsortable_col),(unsortable_col)) - order by unsortable_col::text; - --- mixed hashable/sortable cases -select unhashable_col, unsortable_col, - grouping(unhashable_col, unsortable_col), - count(*), sum(v) - from gstest4 group by grouping sets ((unhashable_col),(unsortable_col)) - order by 3, 5; -explain (costs off) - select unhashable_col, unsortable_col, - grouping(unhashable_col, unsortable_col), - count(*), sum(v) - from gstest4 group by grouping sets ((unhashable_col),(unsortable_col)) - order by 3,5; - -select unhashable_col, unsortable_col, - grouping(unhashable_col, unsortable_col), - count(*), sum(v) - from gstest4 group by grouping sets ((v,unhashable_col),(v,unsortable_col)) - order by 3,5; -explain (costs off) - select unhashable_col, unsortable_col, - grouping(unhashable_col, unsortable_col), - count(*), sum(v) - from gstest4 group by grouping sets ((v,unhashable_col),(v,unsortable_col)) - order by 3,5; - --- empty input: first is 0 rows, second 1, third 3 etc. -select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),a); -explain (costs off) - select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),a); -select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),()); -select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),(),(),()); -explain (costs off) - select a, b, sum(v), count(*) from gstest_empty group by grouping sets ((a,b),(),(),()); -select sum(v), count(*) from gstest_empty group by grouping sets ((),(),()); -explain (costs off) - select sum(v), count(*) from gstest_empty group by grouping sets ((),(),()); - --- check that functionally dependent cols are not nulled -select a, d, grouping(a,b,c) - from gstest3 - group by grouping sets ((a,b), (a,c)); -explain (costs off) - select a, d, grouping(a,b,c) - from gstest3 - group by grouping sets ((a,b), (a,c)); - --- simple rescan tests - -select a, b, sum(v.x) - from (values (1),(2)) v(x), gstest_data(v.x) - group by grouping sets (a,b) - order by 1, 2, 3; -explain (costs off) - select a, b, sum(v.x) - from (values (1),(2)) v(x), gstest_data(v.x) - group by grouping sets (a,b) - order by 3, 1, 2; -select * - from (values (1),(2)) v(x), - lateral (select a, b, sum(v.x) from gstest_data(v.x) group by grouping sets (a,b)) s; -explain (costs off) - select * - from (values (1),(2)) v(x), - lateral (select a, b, sum(v.x) from gstest_data(v.x) group by grouping sets (a,b)) s; - --- Tests for chained aggregates -select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by grouping sets ((a,b),(a+1,b+1),(a+2,b+2)) order by 3,6; -explain (costs off) - select a, b, grouping(a,b), sum(v), count(*), max(v) - from gstest1 group by grouping sets ((a,b),(a+1,b+1),(a+2,b+2)) order by 3,6; -select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum - from gstest2 group by cube (a,b) order by rsum, a, b; -explain (costs off) - select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum - from gstest2 group by cube (a,b) order by rsum, a, b; -select a, b, sum(v.x) - from (values (1),(2)) v(x), gstest_data(v.x) - group by cube (a,b) order by a,b; -explain (costs off) - select a, b, sum(v.x) - from (values (1),(2)) v(x), gstest_data(v.x) - group by cube (a,b) order by a,b; - --- Verify that we correctly handle the child node returning a --- non-minimal slot, which happens if the input is pre-sorted, --- e.g. due to an index scan. -BEGIN; -SET LOCAL enable_hashagg = false; -EXPLAIN (COSTS OFF) SELECT a, b, count(*), max(a), max(b) FROM gstest3 GROUP BY GROUPING SETS(a, b,()) ORDER BY a, b; -SELECT a, b, count(*), max(a), max(b) FROM gstest3 GROUP BY GROUPING SETS(a, b,()) ORDER BY a, b; -SET LOCAL enable_seqscan = false; -EXPLAIN (COSTS OFF) SELECT a, b, count(*), max(a), max(b) FROM gstest3 GROUP BY GROUPING SETS(a, b,()) ORDER BY a, b; -SELECT a, b, count(*), max(a), max(b) FROM gstest3 GROUP BY GROUPING SETS(a, b,()) ORDER BY a, b; -COMMIT; - --- More rescan tests -select * from (values (1),(2)) v(a) left join lateral (select v.a, four, ten, count(*) from onek group by cube(four,ten)) s on true order by v.a,four,ten; -select array(select row(v.a,s1.*) from (select two,four, count(*) from onek group by cube(two,four) order by two,four) s1) from (values (1),(2)) v(a); - --- Rescan logic changes when there are no empty grouping sets, so test --- that too: -select * from (values (1),(2)) v(a) left join lateral (select v.a, four, ten, count(*) from onek group by grouping sets(four,ten)) s on true order by v.a,four,ten; -select array(select row(v.a,s1.*) from (select two,four, count(*) from onek group by grouping sets(two,four) order by two,four) s1) from (values (1),(2)) v(a); - --- test the knapsack - -set enable_indexscan = false; -set hash_mem_multiplier = 1.0; -set work_mem = '64kB'; -explain (costs off) - select unique1, - count(two), count(four), count(ten), - count(hundred), count(thousand), count(twothousand), - count(*) - from tenk1 group by grouping sets (unique1,twothousand,thousand,hundred,ten,four,two); -explain (costs off) - select unique1, - count(two), count(four), count(ten), - count(hundred), count(thousand), count(twothousand), - count(*) - from tenk1 group by grouping sets (unique1,hundred,ten,four,two); - -set work_mem = '384kB'; -explain (costs off) - select unique1, - count(two), count(four), count(ten), - count(hundred), count(thousand), count(twothousand), - count(*) - from tenk1 group by grouping sets (unique1,twothousand,thousand,hundred,ten,four,two); - --- check collation-sensitive matching between grouping expressions --- (similar to a check for aggregates, but there are additional code --- paths for GROUPING, so check again here) - -select v||'a', case grouping(v||'a') when 1 then 1 else 0 end, count(*) - from unnest(array[1,1], array['a','b']) u(i,v) - group by rollup(i, v||'a') order by 1,3; -select v||'a', case when grouping(v||'a') = 1 then 1 else 0 end, count(*) - from unnest(array[1,1], array['a','b']) u(i,v) - group by rollup(i, v||'a') order by 1,3; - --- Bug #16784 -create table bug_16784(i int, j int); -analyze bug_16784; -alter table bug_16784 set (autovacuum_enabled = 'false'); -update pg_class set reltuples = 10 where relname='bug_16784'; - -insert into bug_16784 select g/10, g from generate_series(1,40) g; - -set work_mem='64kB'; -set enable_sort = false; - -select * from - (values (1),(2)) v(a), - lateral (select a, i, j, count(*) from - bug_16784 group by cube(i,j)) s - order by v.a, i, j; - --- --- Compare results between plans using sorting and plans using hash --- aggregation. Force spilling in both cases by setting work_mem low --- and altering the statistics. --- - -create table gs_data_1 as -select g%1000 as g1000, g%100 as g100, g%10 as g10, g - from generate_series(0,1999) g; - -analyze gs_data_1; -alter table gs_data_1 set (autovacuum_enabled = 'false'); -update pg_class set reltuples = 10 where relname='gs_data_1'; - -set work_mem='64kB'; - --- Produce results with sorting. - -set enable_sort = true; -set enable_hashagg = false; -set jit_above_cost = 0; - -explain (costs off) -select g100, g10, sum(g::numeric), count(*), max(g::text) -from gs_data_1 group by cube (g1000, g100,g10); - -create table gs_group_1 as -select g100, g10, sum(g::numeric), count(*), max(g::text) -from gs_data_1 group by cube (g1000, g100,g10); - --- Produce results with hash aggregation. - -set enable_hashagg = true; -set enable_sort = false; - -explain (costs off) -select g100, g10, sum(g::numeric), count(*), max(g::text) -from gs_data_1 group by cube (g1000, g100,g10); - -create table gs_hash_1 as -select g100, g10, sum(g::numeric), count(*), max(g::text) -from gs_data_1 group by cube (g1000, g100,g10); - -set enable_sort = true; -set work_mem to default; -set hash_mem_multiplier to default; - --- Compare results - -(select * from gs_hash_1 except select * from gs_group_1) - union all -(select * from gs_group_1 except select * from gs_hash_1); - -drop table gs_group_1; -drop table gs_hash_1; - --- GROUP BY DISTINCT - --- "normal" behavior... -select a, b, c -from (values (1, 2, 3), (4, null, 6), (7, 8, 9)) as t (a, b, c) -group by all rollup(a, b), rollup(a, c) -order by a, b, c; - --- ...which is also the default -select a, b, c -from (values (1, 2, 3), (4, null, 6), (7, 8, 9)) as t (a, b, c) -group by rollup(a, b), rollup(a, c) -order by a, b, c; - --- "group by distinct" behavior... -select a, b, c -from (values (1, 2, 3), (4, null, 6), (7, 8, 9)) as t (a, b, c) -group by distinct rollup(a, b), rollup(a, c) -order by a, b, c; - --- ...which is not the same as "select distinct" -select distinct a, b, c -from (values (1, 2, 3), (4, null, 6), (7, 8, 9)) as t (a, b, c) -group by rollup(a, b), rollup(a, c) -order by a, b, c; - --- test handling of outer GroupingFunc within subqueries -explain (costs off) -select (select grouping(v1)) from (values ((select 1))) v(v1) group by cube(v1); -select (select grouping(v1)) from (values ((select 1))) v(v1) group by cube(v1); - -explain (costs off) -select (select grouping(v1)) from (values ((select 1))) v(v1) group by v1; -select (select grouping(v1)) from (values ((select 1))) v(v1) group by v1; - --- end diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fguc.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fguc.sql deleted file mode 100644 index d5db101e48..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fguc.sql +++ /dev/null @@ -1,363 +0,0 @@ --- pg_regress should ensure that this default value applies; however --- we can't rely on any specific default value of vacuum_cost_delay -SHOW datestyle; - --- SET to some nondefault value -SET vacuum_cost_delay TO 40; -SET datestyle = 'ISO, YMD'; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- SET LOCAL has no effect outside of a transaction -SET LOCAL vacuum_cost_delay TO 50; -SHOW vacuum_cost_delay; -SET LOCAL datestyle = 'SQL'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- SET LOCAL within a transaction that commits -BEGIN; -SET LOCAL vacuum_cost_delay TO 50; -SHOW vacuum_cost_delay; -SET LOCAL datestyle = 'SQL'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -COMMIT; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- SET should be reverted after ROLLBACK -BEGIN; -SET vacuum_cost_delay TO 60; -SHOW vacuum_cost_delay; -SET datestyle = 'German'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- Some tests with subtransactions -BEGIN; -SET vacuum_cost_delay TO 70; -SET datestyle = 'MDY'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -SAVEPOINT first_sp; -SET vacuum_cost_delay TO 80.1; -SHOW vacuum_cost_delay; -SET datestyle = 'German, DMY'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK TO first_sp; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -SAVEPOINT second_sp; -SET vacuum_cost_delay TO '900us'; -SET datestyle = 'SQL, YMD'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -SAVEPOINT third_sp; -SET vacuum_cost_delay TO 100; -SHOW vacuum_cost_delay; -SET datestyle = 'Postgres, MDY'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK TO third_sp; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK TO second_sp; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- SET LOCAL with Savepoints -BEGIN; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -SAVEPOINT sp; -SET LOCAL vacuum_cost_delay TO 30; -SHOW vacuum_cost_delay; -SET LOCAL datestyle = 'Postgres, MDY'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK TO sp; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- SET LOCAL persists through RELEASE (which was not true in 8.0-8.2) -BEGIN; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -SAVEPOINT sp; -SET LOCAL vacuum_cost_delay TO 30; -SHOW vacuum_cost_delay; -SET LOCAL datestyle = 'Postgres, MDY'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -RELEASE SAVEPOINT sp; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -ROLLBACK; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- SET followed by SET LOCAL -BEGIN; -SET vacuum_cost_delay TO 40; -SET LOCAL vacuum_cost_delay TO 50; -SHOW vacuum_cost_delay; -SET datestyle = 'ISO, DMY'; -SET LOCAL datestyle = 'Postgres, MDY'; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -COMMIT; -SHOW vacuum_cost_delay; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- --- Test RESET. We use datestyle because the reset value is forced by --- pg_regress, so it doesn't depend on the installation's configuration. --- -SET datestyle = iso, ymd; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; -RESET datestyle; -SHOW datestyle; -SELECT '2006-08-13 12:34:56'::timestamptz; - --- Test some simple error cases -SET seq_page_cost TO 'NaN'; -SET vacuum_cost_delay TO '10s'; -SET no_such_variable TO 42; - --- Test "custom" GUCs created on the fly (which aren't really an --- intended feature, but many people use them). -SHOW custom.my_guc; -- error, not known yet -SET custom.my_guc = 42; -SHOW custom.my_guc; -RESET custom.my_guc; -- this makes it go to empty, not become unknown again -SHOW custom.my_guc; -SET custom.my.qualified.guc = 'foo'; -SHOW custom.my.qualified.guc; -SET custom."bad-guc" = 42; -- disallowed because -c cannot set this name -SHOW custom."bad-guc"; -SET special."weird name" = 'foo'; -- could be allowed, but we choose not to -SHOW special."weird name"; - --- Check what happens when you try to set a "custom" GUC within the --- namespace of an extension. -SET plpgsql.extra_foo_warnings = true; -- allowed if plpgsql is not loaded yet -LOAD 'plpgsql'; -- this will throw a warning and delete the variable -SET plpgsql.extra_foo_warnings = true; -- now, it's an error -SHOW plpgsql.extra_foo_warnings; - --- --- Test DISCARD TEMP --- -CREATE TEMP TABLE reset_test ( data text ) ON COMMIT DELETE ROWS; -SELECT relname FROM pg_class WHERE relname = 'reset_test'; -DISCARD TEMP; -SELECT relname FROM pg_class WHERE relname = 'reset_test'; - --- --- Test DISCARD ALL --- - --- do changes -DECLARE foo CURSOR WITH HOLD FOR SELECT 1; -PREPARE foo AS SELECT 1; -LISTEN foo_event; -SET vacuum_cost_delay = 13; -CREATE TEMP TABLE tmp_foo (data text) ON COMMIT DELETE ROWS; -CREATE ROLE regress_guc_user; -SET SESSION AUTHORIZATION regress_guc_user; --- look changes -SELECT pg_listening_channels(); -SELECT name FROM pg_prepared_statements; -SELECT name FROM pg_cursors; -SHOW vacuum_cost_delay; -SELECT relname from pg_class where relname = 'tmp_foo'; -SELECT current_user = 'regress_guc_user'; --- discard everything -DISCARD ALL; --- look again -SELECT pg_listening_channels(); -SELECT name FROM pg_prepared_statements; -SELECT name FROM pg_cursors; -SHOW vacuum_cost_delay; -SELECT relname from pg_class where relname = 'tmp_foo'; -SELECT current_user = 'regress_guc_user'; -DROP ROLE regress_guc_user; - --- --- search_path should react to changes in pg_namespace --- - -set search_path = foo, public, not_there_initially; -select current_schemas(false); -create schema not_there_initially; -select current_schemas(false); -drop schema not_there_initially; -select current_schemas(false); -reset search_path; - --- --- Tests for function-local GUC settings --- - -set work_mem = '3MB'; - -create function report_guc(text) returns text as -$$ select current_setting($1) $$ language sql -set work_mem = '1MB'; - -select report_guc('work_mem'), current_setting('work_mem'); - -alter function report_guc(text) set work_mem = '2MB'; - -select report_guc('work_mem'), current_setting('work_mem'); - -alter function report_guc(text) reset all; - -select report_guc('work_mem'), current_setting('work_mem'); - --- SET LOCAL is restricted by a function SET option -create or replace function myfunc(int) returns text as $$ -begin - set local work_mem = '2MB'; - return current_setting('work_mem'); -end $$ -language plpgsql -set work_mem = '1MB'; - -select myfunc(0), current_setting('work_mem'); - -alter function myfunc(int) reset all; - -select myfunc(0), current_setting('work_mem'); - -set work_mem = '3MB'; - --- but SET isn't -create or replace function myfunc(int) returns text as $$ -begin - set work_mem = '2MB'; - return current_setting('work_mem'); -end $$ -language plpgsql -set work_mem = '1MB'; - -select myfunc(0), current_setting('work_mem'); - -set work_mem = '3MB'; - --- it should roll back on error, though -create or replace function myfunc(int) returns text as $$ -begin - set work_mem = '2MB'; - perform 1/$1; - return current_setting('work_mem'); -end $$ -language plpgsql -set work_mem = '1MB'; - -select myfunc(0); -select current_setting('work_mem'); -select myfunc(1), current_setting('work_mem'); - --- check current_setting()'s behavior with invalid setting name - -select current_setting('nosuch.setting'); -- FAIL -select current_setting('nosuch.setting', false); -- FAIL -select current_setting('nosuch.setting', true) is null; - --- after this, all three cases should yield 'nada' -set nosuch.setting = 'nada'; - -select current_setting('nosuch.setting'); -select current_setting('nosuch.setting', false); -select current_setting('nosuch.setting', true); - --- Normally, CREATE FUNCTION should complain about invalid values in --- function SET options; but not if check_function_bodies is off, --- because that creates ordering hazards for pg_dump - -create function func_with_bad_set() returns int as $$ select 1 $$ -language sql -set default_text_search_config = no_such_config; - -set check_function_bodies = off; - -create function func_with_bad_set() returns int as $$ select 1 $$ -language sql -set default_text_search_config = no_such_config; - -select func_with_bad_set(); - -reset check_function_bodies; - -set default_with_oids to f; --- Should not allow to set it to true. -set default_with_oids to t; - --- Test GUC categories and flag patterns -SELECT pg_settings_get_flags(NULL); -SELECT pg_settings_get_flags('does_not_exist'); -CREATE TABLE tab_settings_flags AS SELECT name, category, - 'EXPLAIN' = ANY(flags) AS explain, - 'NO_RESET_ALL' = ANY(flags) AS no_reset_all, - 'NO_SHOW_ALL' = ANY(flags) AS no_show_all, - 'NOT_IN_SAMPLE' = ANY(flags) AS not_in_sample, - 'RUNTIME_COMPUTED' = ANY(flags) AS runtime_computed - FROM pg_show_all_settings() AS psas, - pg_settings_get_flags(psas.name) AS flags; - --- Developer GUCs should be flagged with GUC_NOT_IN_SAMPLE: -SELECT name FROM tab_settings_flags - WHERE category = 'Developer Options' AND NOT not_in_sample - ORDER BY 1; --- Most query-tuning GUCs are flagged as valid for EXPLAIN. --- default_statistics_target is an exception. -SELECT name FROM tab_settings_flags - WHERE category ~ '^Query Tuning' AND NOT explain - ORDER BY 1; --- Runtime-computed GUCs should be part of the preset category. -SELECT name FROM tab_settings_flags - WHERE NOT category = 'Preset Options' AND runtime_computed - ORDER BY 1; --- Preset GUCs are flagged as NOT_IN_SAMPLE. -SELECT name FROM tab_settings_flags - WHERE category = 'Preset Options' AND NOT not_in_sample - ORDER BY 1; --- NO_SHOW_ALL implies NO_RESET_ALL, and vice-versa. -SELECT name FROM tab_settings_flags - WHERE no_show_all AND NOT no_reset_all - ORDER BY 1; --- Exceptions are transaction_*. -SELECT name FROM tab_settings_flags - WHERE NOT no_show_all AND no_reset_all - ORDER BY 1; --- NO_SHOW_ALL implies NOT_IN_SAMPLE. -SELECT name FROM tab_settings_flags - WHERE no_show_all AND NOT not_in_sample - ORDER BY 1; -DROP TABLE tab_settings_flags; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fhash_index.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fhash_index.sql deleted file mode 100644 index 527024f710..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fhash_index.sql +++ /dev/null @@ -1,266 +0,0 @@ --- --- HASH_INDEX --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - -CREATE TABLE hash_i4_heap ( - seqno int4, - random int4 -); - -CREATE TABLE hash_name_heap ( - seqno int4, - random name -); - -CREATE TABLE hash_txt_heap ( - seqno int4, - random text -); - -CREATE TABLE hash_f8_heap ( - seqno int4, - random float8 -); - -\set filename :abs_srcdir '/data/hash.data' -COPY hash_i4_heap FROM :'filename'; -COPY hash_name_heap FROM :'filename'; -COPY hash_txt_heap FROM :'filename'; -COPY hash_f8_heap FROM :'filename'; - --- the data in this file has a lot of duplicates in the index key --- fields, leading to long bucket chains and lots of table expansion. --- this is therefore a stress test of the bucket overflow code (unlike --- the data in hash.data, which has unique index keys). --- --- \set filename :abs_srcdir '/data/hashovfl.data' --- COPY hash_ovfl_heap FROM :'filename'; - -ANALYZE hash_i4_heap; -ANALYZE hash_name_heap; -ANALYZE hash_txt_heap; -ANALYZE hash_f8_heap; - -CREATE INDEX hash_i4_index ON hash_i4_heap USING hash (random int4_ops); - -CREATE INDEX hash_name_index ON hash_name_heap USING hash (random name_ops); - -CREATE INDEX hash_txt_index ON hash_txt_heap USING hash (random text_ops); - -CREATE INDEX hash_f8_index ON hash_f8_heap USING hash (random float8_ops) - WITH (fillfactor=60); - --- --- Also try building functional, expressional, and partial indexes on --- tables that already contain data. --- -create unique index hash_f8_index_1 on hash_f8_heap(abs(random)); -create unique index hash_f8_index_2 on hash_f8_heap((seqno + 1), random); -create unique index hash_f8_index_3 on hash_f8_heap(random) where seqno > 1000; - --- --- hash index --- grep 843938989 hash.data --- -SELECT * FROM hash_i4_heap - WHERE hash_i4_heap.random = 843938989; - --- --- hash index --- grep 66766766 hash.data --- -SELECT * FROM hash_i4_heap - WHERE hash_i4_heap.random = 66766766; - --- --- hash index --- grep 1505703298 hash.data --- -SELECT * FROM hash_name_heap - WHERE hash_name_heap.random = '1505703298'::name; - --- --- hash index --- grep 7777777 hash.data --- -SELECT * FROM hash_name_heap - WHERE hash_name_heap.random = '7777777'::name; - --- --- hash index --- grep 1351610853 hash.data --- -SELECT * FROM hash_txt_heap - WHERE hash_txt_heap.random = '1351610853'::text; - --- --- hash index --- grep 111111112222222233333333 hash.data --- -SELECT * FROM hash_txt_heap - WHERE hash_txt_heap.random = '111111112222222233333333'::text; - --- --- hash index --- grep 444705537 hash.data --- -SELECT * FROM hash_f8_heap - WHERE hash_f8_heap.random = '444705537'::float8; - --- --- hash index --- grep 88888888 hash.data --- -SELECT * FROM hash_f8_heap - WHERE hash_f8_heap.random = '88888888'::float8; - --- --- hash index --- grep '^90[^0-9]' hashovfl.data --- --- SELECT count(*) AS i988 FROM hash_ovfl_heap --- WHERE x = 90; - --- --- hash index --- grep '^1000[^0-9]' hashovfl.data --- --- SELECT count(*) AS i0 FROM hash_ovfl_heap --- WHERE x = 1000; - --- --- HASH --- -UPDATE hash_i4_heap - SET random = 1 - WHERE hash_i4_heap.seqno = 1492; - -SELECT h.seqno AS i1492, h.random AS i1 - FROM hash_i4_heap h - WHERE h.random = 1; - -UPDATE hash_i4_heap - SET seqno = 20000 - WHERE hash_i4_heap.random = 1492795354; - -SELECT h.seqno AS i20000 - FROM hash_i4_heap h - WHERE h.random = 1492795354; - -UPDATE hash_name_heap - SET random = '0123456789abcdef'::name - WHERE hash_name_heap.seqno = 6543; - -SELECT h.seqno AS i6543, h.random AS c0_to_f - FROM hash_name_heap h - WHERE h.random = '0123456789abcdef'::name; - -UPDATE hash_name_heap - SET seqno = 20000 - WHERE hash_name_heap.random = '76652222'::name; - --- --- this is the row we just replaced; index scan should return zero rows --- -SELECT h.seqno AS emptyset - FROM hash_name_heap h - WHERE h.random = '76652222'::name; - -UPDATE hash_txt_heap - SET random = '0123456789abcdefghijklmnop'::text - WHERE hash_txt_heap.seqno = 4002; - -SELECT h.seqno AS i4002, h.random AS c0_to_p - FROM hash_txt_heap h - WHERE h.random = '0123456789abcdefghijklmnop'::text; - -UPDATE hash_txt_heap - SET seqno = 20000 - WHERE hash_txt_heap.random = '959363399'::text; - -SELECT h.seqno AS t20000 - FROM hash_txt_heap h - WHERE h.random = '959363399'::text; - -UPDATE hash_f8_heap - SET random = '-1234.1234'::float8 - WHERE hash_f8_heap.seqno = 8906; - -SELECT h.seqno AS i8096, h.random AS f1234_1234 - FROM hash_f8_heap h - WHERE h.random = '-1234.1234'::float8; - -UPDATE hash_f8_heap - SET seqno = 20000 - WHERE hash_f8_heap.random = '488912369'::float8; - -SELECT h.seqno AS f20000 - FROM hash_f8_heap h - WHERE h.random = '488912369'::float8; - --- UPDATE hash_ovfl_heap --- SET x = 1000 --- WHERE x = 90; - --- this vacuums the index as well --- VACUUM hash_ovfl_heap; - --- SELECT count(*) AS i0 FROM hash_ovfl_heap --- WHERE x = 90; - --- SELECT count(*) AS i988 FROM hash_ovfl_heap --- WHERE x = 1000; - --- --- Cause some overflow insert and splits. --- -CREATE TABLE hash_split_heap (keycol INT); -INSERT INTO hash_split_heap SELECT 1 FROM generate_series(1, 500) a; -CREATE INDEX hash_split_index on hash_split_heap USING HASH (keycol); -INSERT INTO hash_split_heap SELECT 1 FROM generate_series(1, 5000) a; - --- Let's do a backward scan. -BEGIN; -SET enable_seqscan = OFF; -SET enable_bitmapscan = OFF; - -DECLARE c CURSOR FOR SELECT * from hash_split_heap WHERE keycol = 1; -MOVE FORWARD ALL FROM c; -MOVE BACKWARD 10000 FROM c; -MOVE BACKWARD ALL FROM c; -CLOSE c; -END; - --- DELETE, INSERT, VACUUM. -DELETE FROM hash_split_heap WHERE keycol = 1; -INSERT INTO hash_split_heap SELECT a/2 FROM generate_series(1, 25000) a; - -VACUUM hash_split_heap; - --- Rebuild the index using a different fillfactor -ALTER INDEX hash_split_index SET (fillfactor = 10); -REINDEX INDEX hash_split_index; - --- Clean up. -DROP TABLE hash_split_heap; - --- Index on temp table. -CREATE TEMP TABLE hash_temp_heap (x int, y int); -INSERT INTO hash_temp_heap VALUES (1,1); -CREATE INDEX hash_idx ON hash_temp_heap USING hash (x); -DROP TABLE hash_temp_heap CASCADE; - --- Float4 type. -CREATE TABLE hash_heap_float4 (x float4, y int); -INSERT INTO hash_heap_float4 VALUES (1.1,1); -CREATE INDEX hash_idx ON hash_heap_float4 USING hash (x); -DROP TABLE hash_heap_float4 CASCADE; - --- Test out-of-range fillfactor values -CREATE INDEX hash_f8_index2 ON hash_f8_heap USING hash (random float8_ops) - WITH (fillfactor=9); -CREATE INDEX hash_f8_index2 ON hash_f8_heap USING hash (random float8_ops) - WITH (fillfactor=101); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fincremental_sort.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fincremental_sort.sql deleted file mode 100644 index 1de163e039..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fincremental_sort.sql +++ /dev/null @@ -1,285 +0,0 @@ --- When we have to sort the entire table, incremental sort will --- be slower than plain sort, so it should not be used. -explain (costs off) -select * from (select * from tenk1 order by four) t order by four, ten; - --- When there is a LIMIT clause, incremental sort is beneficial because --- it only has to sort some of the groups, and not the entire table. -explain (costs off) -select * from (select * from tenk1 order by four) t order by four, ten -limit 1; - --- When work_mem is not enough to sort the entire table, incremental sort --- may be faster if individual groups still fit into work_mem. -set work_mem to '2MB'; -explain (costs off) -select * from (select * from tenk1 order by four) t order by four, ten; -reset work_mem; - -create table t(a integer, b integer); - -create or replace function explain_analyze_without_memory(query text) -returns table (out_line text) language plpgsql -as -$$ -declare - line text; -begin - for line in - execute 'explain (analyze, costs off, summary off, timing off) ' || query - loop - out_line := regexp_replace(line, '\d+kB', 'NNkB', 'g'); - return next; - end loop; -end; -$$; - -create or replace function explain_analyze_inc_sort_nodes(query text) -returns jsonb language plpgsql -as -$$ -declare - elements jsonb; - element jsonb; - matching_nodes jsonb := '[]'::jsonb; -begin - execute 'explain (analyze, costs off, summary off, timing off, format ''json'') ' || query into strict elements; - while jsonb_array_length(elements) > 0 loop - element := elements->0; - elements := elements - 0; - case jsonb_typeof(element) - when 'array' then - if jsonb_array_length(element) > 0 then - elements := elements || element; - end if; - when 'object' then - if element ? 'Plan' then - elements := elements || jsonb_build_array(element->'Plan'); - element := element - 'Plan'; - else - if element ? 'Plans' then - elements := elements || jsonb_build_array(element->'Plans'); - element := element - 'Plans'; - end if; - if (element->>'Node Type')::text = 'Incremental Sort' then - matching_nodes := matching_nodes || element; - end if; - end if; - end case; - end loop; - return matching_nodes; -end; -$$; - -create or replace function explain_analyze_inc_sort_nodes_without_memory(query text) -returns jsonb language plpgsql -as -$$ -declare - nodes jsonb := '[]'::jsonb; - node jsonb; - group_key text; - space_key text; -begin - for node in select * from jsonb_array_elements(explain_analyze_inc_sort_nodes(query)) t loop - for group_key in select unnest(array['Full-sort Groups', 'Pre-sorted Groups']::text[]) t loop - for space_key in select unnest(array['Sort Space Memory', 'Sort Space Disk']::text[]) t loop - node := jsonb_set(node, array[group_key, space_key, 'Average Sort Space Used'], '"NN"', false); - node := jsonb_set(node, array[group_key, space_key, 'Peak Sort Space Used'], '"NN"', false); - end loop; - end loop; - nodes := nodes || node; - end loop; - return nodes; -end; -$$; - -create or replace function explain_analyze_inc_sort_nodes_verify_invariants(query text) -returns bool language plpgsql -as -$$ -declare - node jsonb; - group_stats jsonb; - group_key text; - space_key text; -begin - for node in select * from jsonb_array_elements(explain_analyze_inc_sort_nodes(query)) t loop - for group_key in select unnest(array['Full-sort Groups', 'Pre-sorted Groups']::text[]) t loop - group_stats := node->group_key; - for space_key in select unnest(array['Sort Space Memory', 'Sort Space Disk']::text[]) t loop - if (group_stats->space_key->'Peak Sort Space Used')::bigint < (group_stats->space_key->'Peak Sort Space Used')::bigint then - raise exception '% has invalid max space < average space', group_key; - end if; - end loop; - end loop; - end loop; - return true; -end; -$$; - --- A single large group tested around each mode transition point. -insert into t(a, b) select i/100 + 1, i + 1 from generate_series(0, 999) n(i); -analyze t; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 31; -select * from (select * from t order by a) s order by a, b limit 31; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 32; -select * from (select * from t order by a) s order by a, b limit 32; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 33; -select * from (select * from t order by a) s order by a, b limit 33; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 65; -select * from (select * from t order by a) s order by a, b limit 65; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 66; -select * from (select * from t order by a) s order by a, b limit 66; -delete from t; - --- An initial large group followed by a small group. -insert into t(a, b) select i/50 + 1, i + 1 from generate_series(0, 999) n(i); -analyze t; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 55; -select * from (select * from t order by a) s order by a, b limit 55; --- Test EXPLAIN ANALYZE with only a fullsort group. -select explain_analyze_without_memory('select * from (select * from t order by a) s order by a, b limit 55'); -select jsonb_pretty(explain_analyze_inc_sort_nodes_without_memory('select * from (select * from t order by a) s order by a, b limit 55')); -select explain_analyze_inc_sort_nodes_verify_invariants('select * from (select * from t order by a) s order by a, b limit 55'); -delete from t; - --- An initial small group followed by a large group. -insert into t(a, b) select (case when i < 5 then i else 9 end), i from generate_series(1, 1000) n(i); -analyze t; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 70; -select * from (select * from t order by a) s order by a, b limit 70; --- Checks case where we hit a group boundary at the last tuple of a batch. --- Because the full sort state is bounded, we scan 64 tuples (the mode --- transition point) but only retain 5. Thus when we transition modes, all --- tuples in the full sort state have different prefix keys. -explain (costs off) select * from (select * from t order by a) s order by a, b limit 5; -select * from (select * from t order by a) s order by a, b limit 5; - --- Test rescan. -begin; --- We force the planner to choose a plan with incremental sort on the right side --- of a nested loop join node. That way we trigger the rescan code path. -set local enable_hashjoin = off; -set local enable_mergejoin = off; -set local enable_material = off; -set local enable_sort = off; -explain (costs off) select * from t left join (select * from (select * from t order by a) v order by a, b) s on s.a = t.a where t.a in (1, 2); -select * from t left join (select * from (select * from t order by a) v order by a, b) s on s.a = t.a where t.a in (1, 2); -rollback; --- Test EXPLAIN ANALYZE with both fullsort and presorted groups. -select explain_analyze_without_memory('select * from (select * from t order by a) s order by a, b limit 70'); -select jsonb_pretty(explain_analyze_inc_sort_nodes_without_memory('select * from (select * from t order by a) s order by a, b limit 70')); -select explain_analyze_inc_sort_nodes_verify_invariants('select * from (select * from t order by a) s order by a, b limit 70'); -delete from t; - --- Small groups of 10 tuples each tested around each mode transition point. -insert into t(a, b) select i / 10, i from generate_series(1, 1000) n(i); -analyze t; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 31; -select * from (select * from t order by a) s order by a, b limit 31; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 32; -select * from (select * from t order by a) s order by a, b limit 32; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 33; -select * from (select * from t order by a) s order by a, b limit 33; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 65; -select * from (select * from t order by a) s order by a, b limit 65; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 66; -select * from (select * from t order by a) s order by a, b limit 66; -delete from t; - --- Small groups of only 1 tuple each tested around each mode transition point. -insert into t(a, b) select i, i from generate_series(1, 1000) n(i); -analyze t; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 31; -select * from (select * from t order by a) s order by a, b limit 31; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 32; -select * from (select * from t order by a) s order by a, b limit 32; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 33; -select * from (select * from t order by a) s order by a, b limit 33; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 65; -select * from (select * from t order by a) s order by a, b limit 65; -explain (costs off) select * from (select * from t order by a) s order by a, b limit 66; -select * from (select * from t order by a) s order by a, b limit 66; -delete from t; - -drop table t; - --- Incremental sort vs. parallel queries -set min_parallel_table_scan_size = '1kB'; -set min_parallel_index_scan_size = '1kB'; -set parallel_setup_cost = 0; -set parallel_tuple_cost = 0; -set max_parallel_workers_per_gather = 2; - -create table t (a int, b int, c int); -insert into t select mod(i,10),mod(i,10),i from generate_series(1,60000) s(i); -create index on t (a); -analyze t; - -set enable_incremental_sort = off; -explain (costs off) select a,b,sum(c) from t group by 1,2 order by 1,2,3 limit 1; - -set enable_incremental_sort = on; -explain (costs off) select a,b,sum(c) from t group by 1,2 order by 1,2,3 limit 1; - --- Incremental sort vs. set operations with varno 0 -set enable_hashagg to off; -explain (costs off) select * from t union select * from t order by 1,3; - --- Full sort, not just incremental sort can be pushed below a gather merge path --- by generate_useful_gather_paths. -explain (costs off) select distinct a,b from t; - -drop table t; - --- Sort pushdown can't go below where expressions are part of the rel target. --- In particular this is interesting for volatile expressions which have to --- go above joins since otherwise we'll incorrectly use expression evaluations --- across multiple rows. -set enable_hashagg=off; -set enable_seqscan=off; -set enable_incremental_sort = off; -set parallel_tuple_cost=0; -set parallel_setup_cost=0; -set min_parallel_table_scan_size = 0; -set min_parallel_index_scan_size = 0; - --- Parallel sort below join. -explain (costs off) select distinct sub.unique1, stringu1 -from tenk1, lateral (select tenk1.unique1 from generate_series(1, 1000)) as sub; -explain (costs off) select sub.unique1, stringu1 -from tenk1, lateral (select tenk1.unique1 from generate_series(1, 1000)) as sub -order by 1, 2; --- Parallel sort but with expression that can be safely generated at the base rel. -explain (costs off) select distinct sub.unique1, md5(stringu1) -from tenk1, lateral (select tenk1.unique1 from generate_series(1, 1000)) as sub; -explain (costs off) select sub.unique1, md5(stringu1) -from tenk1, lateral (select tenk1.unique1 from generate_series(1, 1000)) as sub -order by 1, 2; --- Parallel sort with an aggregate that can be safely generated in parallel, --- but we can't sort by partial aggregate values. -explain (costs off) select count(*) -from tenk1 t1 -join tenk1 t2 on t1.unique1 = t2.unique2 -join tenk1 t3 on t2.unique1 = t3.unique1 -order by count(*); --- Parallel sort but with expression (correlated subquery) that --- is prohibited in parallel plans. -explain (costs off) select distinct - unique1, - (select t.unique1 from tenk1 where tenk1.unique1 = t.unique1) -from tenk1 t, generate_series(1, 1000); -explain (costs off) select - unique1, - (select t.unique1 from tenk1 where tenk1.unique1 = t.unique1) -from tenk1 t, generate_series(1, 1000) -order by 1, 2; --- Parallel sort but with expression not available until the upper rel. -explain (costs off) select distinct sub.unique1, stringu1 || random()::text -from tenk1, lateral (select tenk1.unique1 from generate_series(1, 1000)) as sub; -explain (costs off) select sub.unique1, stringu1 || random()::text -from tenk1, lateral (select tenk1.unique1 from generate_series(1, 1000)) as sub -order by 1, 2; --- Disallow pushing down sort when pathkey is an SRF. -explain (costs off) select unique1 from tenk1 order by unnest('{1,2}'::int[]); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Findirect_toast.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Findirect_toast.sql deleted file mode 100644 index 3e2f6c0237..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Findirect_toast.sql +++ /dev/null @@ -1,82 +0,0 @@ --- --- Tests for external toast datums --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - -CREATE FUNCTION make_tuple_indirect (record) - RETURNS record - AS :'regresslib' - LANGUAGE C STRICT; - --- Other compression algorithms may cause the compressed data to be stored --- inline. pglz guarantees that the data is externalized, so stick to it. -SET default_toast_compression = 'pglz'; - -CREATE TABLE indtoasttest(descr text, cnt int DEFAULT 0, f1 text, f2 text); - -INSERT INTO indtoasttest(descr, f1, f2) VALUES('two-compressed', repeat('1234567890',1000), repeat('1234567890',1000)); -INSERT INTO indtoasttest(descr, f1, f2) VALUES('two-toasted', repeat('1234567890',30000), repeat('1234567890',50000)); -INSERT INTO indtoasttest(descr, f1, f2) VALUES('one-compressed,one-null', NULL, repeat('1234567890',1000)); -INSERT INTO indtoasttest(descr, f1, f2) VALUES('one-toasted,one-null', NULL, repeat('1234567890',50000)); - --- check whether indirect tuples works on the most basic level -SELECT descr, substring(make_tuple_indirect(indtoasttest)::text, 1, 200) FROM indtoasttest; - --- modification without changing varlenas -UPDATE indtoasttest SET cnt = cnt +1 RETURNING substring(indtoasttest::text, 1, 200); - --- modification without modifying assigned value -UPDATE indtoasttest SET cnt = cnt +1, f1 = f1 RETURNING substring(indtoasttest::text, 1, 200); - --- modification modifying, but effectively not changing -UPDATE indtoasttest SET cnt = cnt +1, f1 = f1||'' RETURNING substring(indtoasttest::text, 1, 200); - -UPDATE indtoasttest SET cnt = cnt +1, f1 = '-'||f1||'-' RETURNING substring(indtoasttest::text, 1, 200); - -SELECT substring(indtoasttest::text, 1, 200) FROM indtoasttest; --- check we didn't screw with main/toast tuple visibility -VACUUM FREEZE indtoasttest; -SELECT substring(indtoasttest::text, 1, 200) FROM indtoasttest; - --- now create a trigger that forces all Datums to be indirect ones -CREATE FUNCTION update_using_indirect() - RETURNS trigger - LANGUAGE plpgsql AS $$ -BEGIN - NEW := make_tuple_indirect(NEW); - RETURN NEW; -END$$; - -CREATE TRIGGER indtoasttest_update_indirect - BEFORE INSERT OR UPDATE - ON indtoasttest - FOR EACH ROW - EXECUTE PROCEDURE update_using_indirect(); - --- modification without changing varlenas -UPDATE indtoasttest SET cnt = cnt +1 RETURNING substring(indtoasttest::text, 1, 200); - --- modification without modifying assigned value -UPDATE indtoasttest SET cnt = cnt +1, f1 = f1 RETURNING substring(indtoasttest::text, 1, 200); - --- modification modifying, but effectively not changing -UPDATE indtoasttest SET cnt = cnt +1, f1 = f1||'' RETURNING substring(indtoasttest::text, 1, 200); - -UPDATE indtoasttest SET cnt = cnt +1, f1 = '-'||f1||'-' RETURNING substring(indtoasttest::text, 1, 200); - -INSERT INTO indtoasttest(descr, f1, f2) VALUES('one-toasted,one-null, via indirect', repeat('1234567890',30000), NULL); - -SELECT substring(indtoasttest::text, 1, 200) FROM indtoasttest; --- check we didn't screw with main/toast tuple visibility -VACUUM FREEZE indtoasttest; -SELECT substring(indtoasttest::text, 1, 200) FROM indtoasttest; - -DROP TABLE indtoasttest; -DROP FUNCTION update_using_indirect(); - -RESET default_toast_compression; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finherit.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finherit.sql deleted file mode 100644 index 195aedb5ff..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finherit.sql +++ /dev/null @@ -1,1015 +0,0 @@ --- --- Test inheritance features --- -CREATE TABLE a (aa TEXT); -CREATE TABLE b (bb TEXT) INHERITS (a); -CREATE TABLE c (cc TEXT) INHERITS (a); -CREATE TABLE d (dd TEXT) INHERITS (b,c,a); - -INSERT INTO a(aa) VALUES('aaa'); -INSERT INTO a(aa) VALUES('aaaa'); -INSERT INTO a(aa) VALUES('aaaaa'); -INSERT INTO a(aa) VALUES('aaaaaa'); -INSERT INTO a(aa) VALUES('aaaaaaa'); -INSERT INTO a(aa) VALUES('aaaaaaaa'); - -INSERT INTO b(aa) VALUES('bbb'); -INSERT INTO b(aa) VALUES('bbbb'); -INSERT INTO b(aa) VALUES('bbbbb'); -INSERT INTO b(aa) VALUES('bbbbbb'); -INSERT INTO b(aa) VALUES('bbbbbbb'); -INSERT INTO b(aa) VALUES('bbbbbbbb'); - -INSERT INTO c(aa) VALUES('ccc'); -INSERT INTO c(aa) VALUES('cccc'); -INSERT INTO c(aa) VALUES('ccccc'); -INSERT INTO c(aa) VALUES('cccccc'); -INSERT INTO c(aa) VALUES('ccccccc'); -INSERT INTO c(aa) VALUES('cccccccc'); - -INSERT INTO d(aa) VALUES('ddd'); -INSERT INTO d(aa) VALUES('dddd'); -INSERT INTO d(aa) VALUES('ddddd'); -INSERT INTO d(aa) VALUES('dddddd'); -INSERT INTO d(aa) VALUES('ddddddd'); -INSERT INTO d(aa) VALUES('dddddddd'); - -SELECT relname, a.* FROM a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM d, pg_class where d.tableoid = pg_class.oid; -SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM ONLY c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid; - -UPDATE a SET aa='zzzz' WHERE aa='aaaa'; -UPDATE ONLY a SET aa='zzzzz' WHERE aa='aaaaa'; -UPDATE b SET aa='zzz' WHERE aa='aaa'; -UPDATE ONLY b SET aa='zzz' WHERE aa='aaa'; -UPDATE a SET aa='zzzzzz' WHERE aa LIKE 'aaa%'; - -SELECT relname, a.* FROM a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM d, pg_class where d.tableoid = pg_class.oid; -SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM ONLY c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid; - -UPDATE b SET aa='new'; - -SELECT relname, a.* FROM a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM d, pg_class where d.tableoid = pg_class.oid; -SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM ONLY c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid; - -UPDATE a SET aa='new'; - -DELETE FROM ONLY c WHERE aa='new'; - -SELECT relname, a.* FROM a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM d, pg_class where d.tableoid = pg_class.oid; -SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM ONLY c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid; - -DELETE FROM a; - -SELECT relname, a.* FROM a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM d, pg_class where d.tableoid = pg_class.oid; -SELECT relname, a.* FROM ONLY a, pg_class where a.tableoid = pg_class.oid; -SELECT relname, b.* FROM ONLY b, pg_class where b.tableoid = pg_class.oid; -SELECT relname, c.* FROM ONLY c, pg_class where c.tableoid = pg_class.oid; -SELECT relname, d.* FROM ONLY d, pg_class where d.tableoid = pg_class.oid; - --- Confirm PRIMARY KEY adds NOT NULL constraint to child table -CREATE TEMP TABLE z (b TEXT, PRIMARY KEY(aa, b)) inherits (a); -INSERT INTO z VALUES (NULL, 'text'); -- should fail - --- Check inherited UPDATE with all children excluded -create table some_tab (a int, b int); -create table some_tab_child () inherits (some_tab); -insert into some_tab_child values(1,2); - -explain (verbose, costs off) -update some_tab set a = a + 1 where false; -update some_tab set a = a + 1 where false; -explain (verbose, costs off) -update some_tab set a = a + 1 where false returning b, a; -update some_tab set a = a + 1 where false returning b, a; -table some_tab; - -drop table some_tab cascade; - --- Check UPDATE with inherited target and an inherited source table -create temp table foo(f1 int, f2 int); -create temp table foo2(f3 int) inherits (foo); -create temp table bar(f1 int, f2 int); -create temp table bar2(f3 int) inherits (bar); - -insert into foo values(1,1); -insert into foo values(3,3); -insert into foo2 values(2,2,2); -insert into foo2 values(3,3,3); -insert into bar values(1,1); -insert into bar values(2,2); -insert into bar values(3,3); -insert into bar values(4,4); -insert into bar2 values(1,1,1); -insert into bar2 values(2,2,2); -insert into bar2 values(3,3,3); -insert into bar2 values(4,4,4); - -update bar set f2 = f2 + 100 where f1 in (select f1 from foo); - -select tableoid::regclass::text as relname, bar.* from bar order by 1,2; - --- Check UPDATE with inherited target and an appendrel subquery -update bar set f2 = f2 + 100 -from - ( select f1 from foo union all select f1+3 from foo ) ss -where bar.f1 = ss.f1; - -select tableoid::regclass::text as relname, bar.* from bar order by 1,2; - --- Check UPDATE with *partitioned* inherited target and an appendrel subquery -create table some_tab (a int); -insert into some_tab values (0); -create table some_tab_child () inherits (some_tab); -insert into some_tab_child values (1); -create table parted_tab (a int, b char) partition by list (a); -create table parted_tab_part1 partition of parted_tab for values in (1); -create table parted_tab_part2 partition of parted_tab for values in (2); -create table parted_tab_part3 partition of parted_tab for values in (3); -insert into parted_tab values (1, 'a'), (2, 'a'), (3, 'a'); - -update parted_tab set b = 'b' -from - (select a from some_tab union all select a+1 from some_tab) ss (a) -where parted_tab.a = ss.a; -select tableoid::regclass::text as relname, parted_tab.* from parted_tab order by 1,2; - -truncate parted_tab; -insert into parted_tab values (1, 'a'), (2, 'a'), (3, 'a'); -update parted_tab set b = 'b' -from - (select 0 from parted_tab union all select 1 from parted_tab) ss (a) -where parted_tab.a = ss.a; -select tableoid::regclass::text as relname, parted_tab.* from parted_tab order by 1,2; - --- modifies partition key, but no rows will actually be updated -explain update parted_tab set a = 2 where false; - -drop table parted_tab; - --- Check UPDATE with multi-level partitioned inherited target -create table mlparted_tab (a int, b char, c text) partition by list (a); -create table mlparted_tab_part1 partition of mlparted_tab for values in (1); -create table mlparted_tab_part2 partition of mlparted_tab for values in (2) partition by list (b); -create table mlparted_tab_part3 partition of mlparted_tab for values in (3); -create table mlparted_tab_part2a partition of mlparted_tab_part2 for values in ('a'); -create table mlparted_tab_part2b partition of mlparted_tab_part2 for values in ('b'); -insert into mlparted_tab values (1, 'a'), (2, 'a'), (2, 'b'), (3, 'a'); - -update mlparted_tab mlp set c = 'xxx' -from - (select a from some_tab union all select a+1 from some_tab) ss (a) -where (mlp.a = ss.a and mlp.b = 'b') or mlp.a = 3; -select tableoid::regclass::text as relname, mlparted_tab.* from mlparted_tab order by 1,2; - -drop table mlparted_tab; -drop table some_tab cascade; - -/* Test multiple inheritance of column defaults */ - -CREATE TABLE firstparent (tomorrow date default now()::date + 1); -CREATE TABLE secondparent (tomorrow date default now() :: date + 1); -CREATE TABLE jointchild () INHERITS (firstparent, secondparent); -- ok -CREATE TABLE thirdparent (tomorrow date default now()::date - 1); -CREATE TABLE otherchild () INHERITS (firstparent, thirdparent); -- not ok -CREATE TABLE otherchild (tomorrow date default now()) - INHERITS (firstparent, thirdparent); -- ok, child resolves ambiguous default - -DROP TABLE firstparent, secondparent, jointchild, thirdparent, otherchild; - --- Test changing the type of inherited columns -insert into d values('test','one','two','three'); -alter table a alter column aa type integer using bit_length(aa); -select * from d; - --- The above verified that we can change the type of a multiply-inherited --- column; but we should reject that if any definition was inherited from --- an unrelated parent. -create temp table parent1(f1 int, f2 int); -create temp table parent2(f1 int, f3 bigint); -create temp table childtab(f4 int) inherits(parent1, parent2); -alter table parent1 alter column f1 type bigint; -- fail, conflict w/parent2 -alter table parent1 alter column f2 type bigint; -- ok - --- Test non-inheritable parent constraints -create table p1(ff1 int); -alter table p1 add constraint p1chk check (ff1 > 0) no inherit; -alter table p1 add constraint p2chk check (ff1 > 10); --- connoinherit should be true for NO INHERIT constraint -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pgc.connoinherit from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname = 'p1' order by 1,2; - --- Test that child does not inherit NO INHERIT constraints -create table c1 () inherits (p1); -\d p1 -\d c1 - --- Test that child does not override inheritable constraints of the parent -create table c2 (constraint p2chk check (ff1 > 10) no inherit) inherits (p1); --fails - -drop table p1 cascade; - --- Tests for casting between the rowtypes of parent and child --- tables. See the pgsql-hackers thread beginning Dec. 4/04 -create table base (i integer); -create table derived () inherits (base); -create table more_derived (like derived, b int) inherits (derived); -insert into derived (i) values (0); -select derived::base from derived; -select NULL::derived::base; --- remove redundant conversions. -explain (verbose on, costs off) select row(i, b)::more_derived::derived::base from more_derived; -explain (verbose on, costs off) select (1, 2)::more_derived::derived::base; -drop table more_derived; -drop table derived; -drop table base; - -create table p1(ff1 int); -create table p2(f1 text); -create function p2text(p2) returns text as 'select $1.f1' language sql; -create table c1(f3 int) inherits(p1,p2); -insert into c1 values(123456789, 'hi', 42); -select p2text(c1.*) from c1; -drop function p2text(p2); -drop table c1; -drop table p2; -drop table p1; - -CREATE TABLE ac (aa TEXT); -alter table ac add constraint ac_check check (aa is not null); -CREATE TABLE bc (bb TEXT) INHERITS (ac); -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; - -insert into ac (aa) values (NULL); -insert into bc (aa) values (NULL); - -alter table bc drop constraint ac_check; -- fail, disallowed -alter table ac drop constraint ac_check; -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; - --- try the unnamed-constraint case -alter table ac add check (aa is not null); -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; - -insert into ac (aa) values (NULL); -insert into bc (aa) values (NULL); - -alter table bc drop constraint ac_aa_check; -- fail, disallowed -alter table ac drop constraint ac_aa_check; -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; - -alter table ac add constraint ac_check check (aa is not null); -alter table bc no inherit ac; -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; -alter table bc drop constraint ac_check; -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; -alter table ac drop constraint ac_check; -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; - -drop table bc; -drop table ac; - -create table ac (a int constraint check_a check (a <> 0)); -create table bc (a int constraint check_a check (a <> 0), b int constraint check_b check (b <> 0)) inherits (ac); -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc') order by 1,2; - -drop table bc; -drop table ac; - -create table ac (a int constraint check_a check (a <> 0)); -create table bc (b int constraint check_b check (b <> 0)); -create table cc (c int constraint check_c check (c <> 0)) inherits (ac, bc); -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc', 'cc') order by 1,2; - -alter table cc no inherit bc; -select pc.relname, pgc.conname, pgc.contype, pgc.conislocal, pgc.coninhcount, pg_get_expr(pgc.conbin, pc.oid) as consrc from pg_class as pc inner join pg_constraint as pgc on (pgc.conrelid = pc.oid) where pc.relname in ('ac', 'bc', 'cc') order by 1,2; - -drop table cc; -drop table bc; -drop table ac; - -create table p1(f1 int); -create table p2(f2 int); -create table c1(f3 int) inherits(p1,p2); -insert into c1 values(1,-1,2); -alter table p2 add constraint cc check (f2>0); -- fail -alter table p2 add check (f2>0); -- check it without a name, too -delete from c1; -insert into c1 values(1,1,2); -alter table p2 add check (f2>0); -insert into c1 values(1,-1,2); -- fail -create table c2(f3 int) inherits(p1,p2); -\d c2 -create table c3 (f4 int) inherits(c1,c2); -\d c3 -drop table p1 cascade; -drop table p2 cascade; - -create table pp1 (f1 int); -create table cc1 (f2 text, f3 int) inherits (pp1); -alter table pp1 add column a1 int check (a1 > 0); -\d cc1 -create table cc2(f4 float) inherits(pp1,cc1); -\d cc2 -alter table pp1 add column a2 int check (a2 > 0); -\d cc2 -drop table pp1 cascade; - --- Test for renaming in simple multiple inheritance -CREATE TABLE inht1 (a int, b int); -CREATE TABLE inhs1 (b int, c int); -CREATE TABLE inhts (d int) INHERITS (inht1, inhs1); - -ALTER TABLE inht1 RENAME a TO aa; -ALTER TABLE inht1 RENAME b TO bb; -- to be failed -ALTER TABLE inhts RENAME aa TO aaa; -- to be failed -ALTER TABLE inhts RENAME d TO dd; -\d+ inhts - -DROP TABLE inhts; - --- Test for renaming in diamond inheritance -CREATE TABLE inht2 (x int) INHERITS (inht1); -CREATE TABLE inht3 (y int) INHERITS (inht1); -CREATE TABLE inht4 (z int) INHERITS (inht2, inht3); - -ALTER TABLE inht1 RENAME aa TO aaa; -\d+ inht4 - -CREATE TABLE inhts (d int) INHERITS (inht2, inhs1); -ALTER TABLE inht1 RENAME aaa TO aaaa; -ALTER TABLE inht1 RENAME b TO bb; -- to be failed -\d+ inhts - -WITH RECURSIVE r AS ( - SELECT 'inht1'::regclass AS inhrelid -UNION ALL - SELECT c.inhrelid FROM pg_inherits c, r WHERE r.inhrelid = c.inhparent -) -SELECT a.attrelid::regclass, a.attname, a.attinhcount, e.expected - FROM (SELECT inhrelid, count(*) AS expected FROM pg_inherits - WHERE inhparent IN (SELECT inhrelid FROM r) GROUP BY inhrelid) e - JOIN pg_attribute a ON e.inhrelid = a.attrelid WHERE NOT attislocal - ORDER BY a.attrelid::regclass::name, a.attnum; - -DROP TABLE inht1, inhs1 CASCADE; - - --- Test non-inheritable indices [UNIQUE, EXCLUDE] constraints -CREATE TABLE test_constraints (id int, val1 varchar, val2 int, UNIQUE(val1, val2)); -CREATE TABLE test_constraints_inh () INHERITS (test_constraints); -\d+ test_constraints -ALTER TABLE ONLY test_constraints DROP CONSTRAINT test_constraints_val1_val2_key; -\d+ test_constraints -\d+ test_constraints_inh -DROP TABLE test_constraints_inh; -DROP TABLE test_constraints; - -CREATE TABLE test_ex_constraints ( - c circle, - EXCLUDE USING gist (c WITH &&) -); -CREATE TABLE test_ex_constraints_inh () INHERITS (test_ex_constraints); -\d+ test_ex_constraints -ALTER TABLE test_ex_constraints DROP CONSTRAINT test_ex_constraints_c_excl; -\d+ test_ex_constraints -\d+ test_ex_constraints_inh -DROP TABLE test_ex_constraints_inh; -DROP TABLE test_ex_constraints; - --- Test non-inheritable foreign key constraints -CREATE TABLE test_primary_constraints(id int PRIMARY KEY); -CREATE TABLE test_foreign_constraints(id1 int REFERENCES test_primary_constraints(id)); -CREATE TABLE test_foreign_constraints_inh () INHERITS (test_foreign_constraints); -\d+ test_primary_constraints -\d+ test_foreign_constraints -ALTER TABLE test_foreign_constraints DROP CONSTRAINT test_foreign_constraints_id1_fkey; -\d+ test_foreign_constraints -\d+ test_foreign_constraints_inh -DROP TABLE test_foreign_constraints_inh; -DROP TABLE test_foreign_constraints; -DROP TABLE test_primary_constraints; - --- Test foreign key behavior -create table inh_fk_1 (a int primary key); -insert into inh_fk_1 values (1), (2), (3); -create table inh_fk_2 (x int primary key, y int references inh_fk_1 on delete cascade); -insert into inh_fk_2 values (11, 1), (22, 2), (33, 3); -create table inh_fk_2_child () inherits (inh_fk_2); -insert into inh_fk_2_child values (111, 1), (222, 2); -delete from inh_fk_1 where a = 1; -select * from inh_fk_1 order by 1; -select * from inh_fk_2 order by 1, 2; -drop table inh_fk_1, inh_fk_2, inh_fk_2_child; - --- Test that parent and child CHECK constraints can be created in either order -create table p1(f1 int); -create table p1_c1() inherits(p1); - -alter table p1 add constraint inh_check_constraint1 check (f1 > 0); -alter table p1_c1 add constraint inh_check_constraint1 check (f1 > 0); - -alter table p1_c1 add constraint inh_check_constraint2 check (f1 < 10); -alter table p1 add constraint inh_check_constraint2 check (f1 < 10); - -select conrelid::regclass::text as relname, conname, conislocal, coninhcount -from pg_constraint where conname like 'inh\_check\_constraint%' -order by 1, 2; - -drop table p1 cascade; - --- Test that a valid child can have not-valid parent, but not vice versa -create table invalid_check_con(f1 int); -create table invalid_check_con_child() inherits(invalid_check_con); - -alter table invalid_check_con_child add constraint inh_check_constraint check(f1 > 0) not valid; -alter table invalid_check_con add constraint inh_check_constraint check(f1 > 0); -- fail -alter table invalid_check_con_child drop constraint inh_check_constraint; - -insert into invalid_check_con values(0); - -alter table invalid_check_con_child add constraint inh_check_constraint check(f1 > 0); -alter table invalid_check_con add constraint inh_check_constraint check(f1 > 0) not valid; - -insert into invalid_check_con values(0); -- fail -insert into invalid_check_con_child values(0); -- fail - -select conrelid::regclass::text as relname, conname, - convalidated, conislocal, coninhcount, connoinherit -from pg_constraint where conname like 'inh\_check\_constraint%' -order by 1, 2; - --- We don't drop the invalid_check_con* tables, to test dump/reload with - --- --- Test parameterized append plans for inheritance trees --- - -create temp table patest0 (id, x) as - select x, x from generate_series(0,1000) x; -create temp table patest1() inherits (patest0); -insert into patest1 - select x, x from generate_series(0,1000) x; -create temp table patest2() inherits (patest0); -insert into patest2 - select x, x from generate_series(0,1000) x; -create index patest0i on patest0(id); -create index patest1i on patest1(id); -create index patest2i on patest2(id); -analyze patest0; -analyze patest1; -analyze patest2; - -explain (costs off) -select * from patest0 join (select f1 from int4_tbl limit 1) ss on id = f1; -select * from patest0 join (select f1 from int4_tbl limit 1) ss on id = f1; - -drop index patest2i; - -explain (costs off) -select * from patest0 join (select f1 from int4_tbl limit 1) ss on id = f1; -select * from patest0 join (select f1 from int4_tbl limit 1) ss on id = f1; - -drop table patest0 cascade; - --- --- Test merge-append plans for inheritance trees --- - -create table matest0 (id serial primary key, name text); -create table matest1 (id integer primary key) inherits (matest0); -create table matest2 (id integer primary key) inherits (matest0); -create table matest3 (id integer primary key) inherits (matest0); - -create index matest0i on matest0 ((1-id)); -create index matest1i on matest1 ((1-id)); --- create index matest2i on matest2 ((1-id)); -- intentionally missing -create index matest3i on matest3 ((1-id)); - -insert into matest1 (name) values ('Test 1'); -insert into matest1 (name) values ('Test 2'); -insert into matest2 (name) values ('Test 3'); -insert into matest2 (name) values ('Test 4'); -insert into matest3 (name) values ('Test 5'); -insert into matest3 (name) values ('Test 6'); - -set enable_indexscan = off; -- force use of seqscan/sort, so no merge -explain (verbose, costs off) select * from matest0 order by 1-id; -select * from matest0 order by 1-id; -explain (verbose, costs off) select min(1-id) from matest0; -select min(1-id) from matest0; -reset enable_indexscan; - -set enable_seqscan = off; -- plan with fewest seqscans should be merge -set enable_parallel_append = off; -- Don't let parallel-append interfere -explain (verbose, costs off) select * from matest0 order by 1-id; -select * from matest0 order by 1-id; -explain (verbose, costs off) select min(1-id) from matest0; -select min(1-id) from matest0; -reset enable_seqscan; -reset enable_parallel_append; - -drop table matest0 cascade; - --- --- Check that use of an index with an extraneous column doesn't produce --- a plan with extraneous sorting --- - -create table matest0 (a int, b int, c int, d int); -create table matest1 () inherits(matest0); -create index matest0i on matest0 (b, c); -create index matest1i on matest1 (b, c); - -set enable_nestloop = off; -- we want a plan with two MergeAppends - -explain (costs off) -select t1.* from matest0 t1, matest0 t2 -where t1.b = t2.b and t2.c = t2.d -order by t1.b limit 10; - -reset enable_nestloop; - -drop table matest0 cascade; - --- --- Test merge-append for UNION ALL append relations --- - -set enable_seqscan = off; -set enable_indexscan = on; -set enable_bitmapscan = off; - --- Check handling of duplicated, constant, or volatile targetlist items -explain (costs off) -SELECT thousand, tenthous FROM tenk1 -UNION ALL -SELECT thousand, thousand FROM tenk1 -ORDER BY thousand, tenthous; - -explain (costs off) -SELECT thousand, tenthous, thousand+tenthous AS x FROM tenk1 -UNION ALL -SELECT 42, 42, hundred FROM tenk1 -ORDER BY thousand, tenthous; - -explain (costs off) -SELECT thousand, tenthous FROM tenk1 -UNION ALL -SELECT thousand, random()::integer FROM tenk1 -ORDER BY thousand, tenthous; - --- Check min/max aggregate optimization -explain (costs off) -SELECT min(x) FROM - (SELECT unique1 AS x FROM tenk1 a - UNION ALL - SELECT unique2 AS x FROM tenk1 b) s; - -explain (costs off) -SELECT min(y) FROM - (SELECT unique1 AS x, unique1 AS y FROM tenk1 a - UNION ALL - SELECT unique2 AS x, unique2 AS y FROM tenk1 b) s; - --- XXX planner doesn't recognize that index on unique2 is sufficiently sorted -explain (costs off) -SELECT x, y FROM - (SELECT thousand AS x, tenthous AS y FROM tenk1 a - UNION ALL - SELECT unique2 AS x, unique2 AS y FROM tenk1 b) s -ORDER BY x, y; - --- exercise rescan code path via a repeatedly-evaluated subquery -explain (costs off) -SELECT - ARRAY(SELECT f.i FROM ( - (SELECT d + g.i FROM generate_series(4, 30, 3) d ORDER BY 1) - UNION ALL - (SELECT d + g.i FROM generate_series(0, 30, 5) d ORDER BY 1) - ) f(i) - ORDER BY f.i LIMIT 10) -FROM generate_series(1, 3) g(i); - -SELECT - ARRAY(SELECT f.i FROM ( - (SELECT d + g.i FROM generate_series(4, 30, 3) d ORDER BY 1) - UNION ALL - (SELECT d + g.i FROM generate_series(0, 30, 5) d ORDER BY 1) - ) f(i) - ORDER BY f.i LIMIT 10) -FROM generate_series(1, 3) g(i); - -reset enable_seqscan; -reset enable_indexscan; -reset enable_bitmapscan; - --- --- Check handling of a constant-null CHECK constraint --- -create table cnullparent (f1 int); -create table cnullchild (check (f1 = 1 or f1 = null)) inherits(cnullparent); -insert into cnullchild values(1); -insert into cnullchild values(2); -insert into cnullchild values(null); -select * from cnullparent; -select * from cnullparent where f1 = 2; -drop table cnullparent cascade; - --- --- Check use of temporary tables with inheritance trees --- -create table inh_perm_parent (a1 int); -create temp table inh_temp_parent (a1 int); -create temp table inh_temp_child () inherits (inh_perm_parent); -- ok -create table inh_perm_child () inherits (inh_temp_parent); -- error -create temp table inh_temp_child_2 () inherits (inh_temp_parent); -- ok -insert into inh_perm_parent values (1); -insert into inh_temp_parent values (2); -insert into inh_temp_child values (3); -insert into inh_temp_child_2 values (4); -select tableoid::regclass, a1 from inh_perm_parent; -select tableoid::regclass, a1 from inh_temp_parent; -drop table inh_perm_parent cascade; -drop table inh_temp_parent cascade; - --- --- Check that constraint exclusion works correctly with partitions using --- implicit constraints generated from the partition bound information. --- -create table list_parted ( - a varchar -) partition by list (a); -create table part_ab_cd partition of list_parted for values in ('ab', 'cd'); -create table part_ef_gh partition of list_parted for values in ('ef', 'gh'); -create table part_null_xy partition of list_parted for values in (null, 'xy'); - -explain (costs off) select * from list_parted; -explain (costs off) select * from list_parted where a is null; -explain (costs off) select * from list_parted where a is not null; -explain (costs off) select * from list_parted where a in ('ab', 'cd', 'ef'); -explain (costs off) select * from list_parted where a = 'ab' or a in (null, 'cd'); -explain (costs off) select * from list_parted where a = 'ab'; - -create table range_list_parted ( - a int, - b char(2) -) partition by range (a); -create table part_1_10 partition of range_list_parted for values from (1) to (10) partition by list (b); -create table part_1_10_ab partition of part_1_10 for values in ('ab'); -create table part_1_10_cd partition of part_1_10 for values in ('cd'); -create table part_10_20 partition of range_list_parted for values from (10) to (20) partition by list (b); -create table part_10_20_ab partition of part_10_20 for values in ('ab'); -create table part_10_20_cd partition of part_10_20 for values in ('cd'); -create table part_21_30 partition of range_list_parted for values from (21) to (30) partition by list (b); -create table part_21_30_ab partition of part_21_30 for values in ('ab'); -create table part_21_30_cd partition of part_21_30 for values in ('cd'); -create table part_40_inf partition of range_list_parted for values from (40) to (maxvalue) partition by list (b); -create table part_40_inf_ab partition of part_40_inf for values in ('ab'); -create table part_40_inf_cd partition of part_40_inf for values in ('cd'); -create table part_40_inf_null partition of part_40_inf for values in (null); - -explain (costs off) select * from range_list_parted; -explain (costs off) select * from range_list_parted where a = 5; -explain (costs off) select * from range_list_parted where b = 'ab'; -explain (costs off) select * from range_list_parted where a between 3 and 23 and b in ('ab'); - -/* Should select no rows because range partition key cannot be null */ -explain (costs off) select * from range_list_parted where a is null; - -/* Should only select rows from the null-accepting partition */ -explain (costs off) select * from range_list_parted where b is null; -explain (costs off) select * from range_list_parted where a is not null and a < 67; -explain (costs off) select * from range_list_parted where a >= 30; - -drop table list_parted; -drop table range_list_parted; - --- check that constraint exclusion is able to cope with the partition --- constraint emitted for multi-column range partitioned tables -create table mcrparted (a int, b int, c int) partition by range (a, abs(b), c); -create table mcrparted_def partition of mcrparted default; -create table mcrparted0 partition of mcrparted for values from (minvalue, minvalue, minvalue) to (1, 1, 1); -create table mcrparted1 partition of mcrparted for values from (1, 1, 1) to (10, 5, 10); -create table mcrparted2 partition of mcrparted for values from (10, 5, 10) to (10, 10, 10); -create table mcrparted3 partition of mcrparted for values from (11, 1, 1) to (20, 10, 10); -create table mcrparted4 partition of mcrparted for values from (20, 10, 10) to (20, 20, 20); -create table mcrparted5 partition of mcrparted for values from (20, 20, 20) to (maxvalue, maxvalue, maxvalue); -explain (costs off) select * from mcrparted where a = 0; -- scans mcrparted0, mcrparted_def -explain (costs off) select * from mcrparted where a = 10 and abs(b) < 5; -- scans mcrparted1, mcrparted_def -explain (costs off) select * from mcrparted where a = 10 and abs(b) = 5; -- scans mcrparted1, mcrparted2, mcrparted_def -explain (costs off) select * from mcrparted where abs(b) = 5; -- scans all partitions -explain (costs off) select * from mcrparted where a > -1; -- scans all partitions -explain (costs off) select * from mcrparted where a = 20 and abs(b) = 10 and c > 10; -- scans mcrparted4 -explain (costs off) select * from mcrparted where a = 20 and c > 20; -- scans mcrparted3, mcrparte4, mcrparte5, mcrparted_def - --- check that partitioned table Appends cope with being referenced in --- subplans -create table parted_minmax (a int, b varchar(16)) partition by range (a); -create table parted_minmax1 partition of parted_minmax for values from (1) to (10); -create index parted_minmax1i on parted_minmax1 (a, b); -insert into parted_minmax values (1,'12345'); -explain (costs off) select min(a), max(a) from parted_minmax where b = '12345'; -select min(a), max(a) from parted_minmax where b = '12345'; -drop table parted_minmax; - --- Test code that uses Append nodes in place of MergeAppend when the --- partition ordering matches the desired ordering. - -create index mcrparted_a_abs_c_idx on mcrparted (a, abs(b), c); - --- MergeAppend must be used when a default partition exists -explain (costs off) select * from mcrparted order by a, abs(b), c; - -drop table mcrparted_def; - --- Append is used for a RANGE partitioned table with no default --- and no subpartitions -explain (costs off) select * from mcrparted order by a, abs(b), c; - --- Append is used with subpaths in reverse order with backwards index scans -explain (costs off) select * from mcrparted order by a desc, abs(b) desc, c desc; - --- check that Append plan is used containing a MergeAppend for sub-partitions --- that are unordered. -drop table mcrparted5; -create table mcrparted5 partition of mcrparted for values from (20, 20, 20) to (maxvalue, maxvalue, maxvalue) partition by list (a); -create table mcrparted5a partition of mcrparted5 for values in(20); -create table mcrparted5_def partition of mcrparted5 default; - -explain (costs off) select * from mcrparted order by a, abs(b), c; - -drop table mcrparted5_def; - --- check that an Append plan is used and the sub-partitions are flattened --- into the main Append when the sub-partition is unordered but contains --- just a single sub-partition. -explain (costs off) select a, abs(b) from mcrparted order by a, abs(b), c; - --- check that Append is used when the sub-partitioned tables are pruned --- during planning. -explain (costs off) select * from mcrparted where a < 20 order by a, abs(b), c; - -set enable_bitmapscan to off; -set enable_sort to off; -create table mclparted (a int) partition by list(a); -create table mclparted1 partition of mclparted for values in(1); -create table mclparted2 partition of mclparted for values in(2); -create index on mclparted (a); - --- Ensure an Append is used for a list partition with an order by. -explain (costs off) select * from mclparted order by a; - --- Ensure a MergeAppend is used when a partition exists with interleaved --- datums in the partition bound. -create table mclparted3_5 partition of mclparted for values in(3,5); -create table mclparted4 partition of mclparted for values in(4); - -explain (costs off) select * from mclparted order by a; -explain (costs off) select * from mclparted where a in(3,4,5) order by a; - --- Introduce a NULL and DEFAULT partition so we can test more complex cases -create table mclparted_null partition of mclparted for values in(null); -create table mclparted_def partition of mclparted default; - --- Append can be used providing we don't scan the interleaved partition -explain (costs off) select * from mclparted where a in(1,2,4) order by a; -explain (costs off) select * from mclparted where a in(1,2,4) or a is null order by a; - --- Test a more complex case where the NULL partition allows some other value -drop table mclparted_null; -create table mclparted_0_null partition of mclparted for values in(0,null); - --- Ensure MergeAppend is used since 0 and NULLs are in the same partition. -explain (costs off) select * from mclparted where a in(1,2,4) or a is null order by a; -explain (costs off) select * from mclparted where a in(0,1,2,4) order by a; - --- Ensure Append is used when the null partition is pruned -explain (costs off) select * from mclparted where a in(1,2,4) order by a; - --- Ensure MergeAppend is used when the default partition is not pruned -explain (costs off) select * from mclparted where a in(1,2,4,100) order by a; - -drop table mclparted; -reset enable_sort; -reset enable_bitmapscan; - --- Ensure subplans which don't have a path with the correct pathkeys get --- sorted correctly. -drop index mcrparted_a_abs_c_idx; -create index on mcrparted1 (a, abs(b), c); -create index on mcrparted2 (a, abs(b), c); -create index on mcrparted3 (a, abs(b), c); -create index on mcrparted4 (a, abs(b), c); - -explain (costs off) select * from mcrparted where a < 20 order by a, abs(b), c limit 1; - -set enable_bitmapscan = 0; --- Ensure Append node can be used when the partition is ordered by some --- pathkeys which were deemed redundant. -explain (costs off) select * from mcrparted where a = 10 order by a, abs(b), c; -reset enable_bitmapscan; - -drop table mcrparted; - --- Ensure LIST partitions allow an Append to be used instead of a MergeAppend -create table bool_lp (b bool) partition by list(b); -create table bool_lp_true partition of bool_lp for values in(true); -create table bool_lp_false partition of bool_lp for values in(false); -create index on bool_lp (b); - -explain (costs off) select * from bool_lp order by b; - -drop table bool_lp; - --- Ensure const bool quals can be properly detected as redundant -create table bool_rp (b bool, a int) partition by range(b,a); -create table bool_rp_false_1k partition of bool_rp for values from (false,0) to (false,1000); -create table bool_rp_true_1k partition of bool_rp for values from (true,0) to (true,1000); -create table bool_rp_false_2k partition of bool_rp for values from (false,1000) to (false,2000); -create table bool_rp_true_2k partition of bool_rp for values from (true,1000) to (true,2000); -create index on bool_rp (b,a); -explain (costs off) select * from bool_rp where b = true order by b,a; -explain (costs off) select * from bool_rp where b = false order by b,a; -explain (costs off) select * from bool_rp where b = true order by a; -explain (costs off) select * from bool_rp where b = false order by a; - -drop table bool_rp; - --- Ensure an Append scan is chosen when the partition order is a subset of --- the required order. -create table range_parted (a int, b int, c int) partition by range(a, b); -create table range_parted1 partition of range_parted for values from (0,0) to (10,10); -create table range_parted2 partition of range_parted for values from (10,10) to (20,20); -create index on range_parted (a,b,c); - -explain (costs off) select * from range_parted order by a,b,c; -explain (costs off) select * from range_parted order by a desc,b desc,c desc; - -drop table range_parted; - --- Check that we allow access to a child table's statistics when the user --- has permissions only for the parent table. -create table permtest_parent (a int, b text, c text) partition by list (a); -create table permtest_child (b text, c text, a int) partition by list (b); -create table permtest_grandchild (c text, b text, a int); -alter table permtest_child attach partition permtest_grandchild for values in ('a'); -alter table permtest_parent attach partition permtest_child for values in (1); -create index on permtest_parent (left(c, 3)); -insert into permtest_parent - select 1, 'a', left(md5(i::text), 5) from generate_series(0, 100) i; -analyze permtest_parent; -create role regress_no_child_access; -revoke all on permtest_grandchild from regress_no_child_access; -grant select on permtest_parent to regress_no_child_access; -set session authorization regress_no_child_access; --- without stats access, these queries would produce hash join plans: -explain (costs off) - select * from permtest_parent p1 inner join permtest_parent p2 - on p1.a = p2.a and p1.c ~ 'a1$'; -explain (costs off) - select * from permtest_parent p1 inner join permtest_parent p2 - on p1.a = p2.a and left(p1.c, 3) ~ 'a1$'; -reset session authorization; -revoke all on permtest_parent from regress_no_child_access; -grant select(a,c) on permtest_parent to regress_no_child_access; -set session authorization regress_no_child_access; -explain (costs off) - select p2.a, p1.c from permtest_parent p1 inner join permtest_parent p2 - on p1.a = p2.a and p1.c ~ 'a1$'; --- we will not have access to the expression index's stats here: -explain (costs off) - select p2.a, p1.c from permtest_parent p1 inner join permtest_parent p2 - on p1.a = p2.a and left(p1.c, 3) ~ 'a1$'; -reset session authorization; -revoke all on permtest_parent from regress_no_child_access; -drop role regress_no_child_access; -drop table permtest_parent; - --- Verify that constraint errors across partition root / child are --- handled correctly (Bug #16293) -CREATE TABLE errtst_parent ( - partid int not null, - shdata int not null, - data int NOT NULL DEFAULT 0, - CONSTRAINT shdata_small CHECK(shdata < 3) -) PARTITION BY RANGE (partid); - --- fast defaults lead to attribute mapping being used in one --- direction, but not the other -CREATE TABLE errtst_child_fastdef ( - partid int not null, - shdata int not null, - CONSTRAINT shdata_small CHECK(shdata < 3) -); - --- no remapping in either direction necessary -CREATE TABLE errtst_child_plaindef ( - partid int not null, - shdata int not null, - data int NOT NULL DEFAULT 0, - CONSTRAINT shdata_small CHECK(shdata < 3), - CHECK(data < 10) -); - --- remapping in both direction -CREATE TABLE errtst_child_reorder ( - data int NOT NULL DEFAULT 0, - shdata int not null, - partid int not null, - CONSTRAINT shdata_small CHECK(shdata < 3), - CHECK(data < 10) -); - -ALTER TABLE errtst_child_fastdef ADD COLUMN data int NOT NULL DEFAULT 0; -ALTER TABLE errtst_child_fastdef ADD CONSTRAINT errtest_child_fastdef_data_check CHECK (data < 10); - -ALTER TABLE errtst_parent ATTACH PARTITION errtst_child_fastdef FOR VALUES FROM (0) TO (10); -ALTER TABLE errtst_parent ATTACH PARTITION errtst_child_plaindef FOR VALUES FROM (10) TO (20); -ALTER TABLE errtst_parent ATTACH PARTITION errtst_child_reorder FOR VALUES FROM (20) TO (30); - --- insert without child check constraint error -INSERT INTO errtst_parent(partid, shdata, data) VALUES ( '0', '1', '5'); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('10', '1', '5'); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('20', '1', '5'); - --- insert with child check constraint error -INSERT INTO errtst_parent(partid, shdata, data) VALUES ( '0', '1', '10'); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('10', '1', '10'); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('20', '1', '10'); - --- insert with child not null constraint error -INSERT INTO errtst_parent(partid, shdata, data) VALUES ( '0', '1', NULL); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('10', '1', NULL); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('20', '1', NULL); - --- insert with shared check constraint error -INSERT INTO errtst_parent(partid, shdata, data) VALUES ( '0', '5', '5'); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('10', '5', '5'); -INSERT INTO errtst_parent(partid, shdata, data) VALUES ('20', '5', '5'); - --- within partition update without child check constraint violation -BEGIN; -UPDATE errtst_parent SET data = data + 1 WHERE partid = 0; -UPDATE errtst_parent SET data = data + 1 WHERE partid = 10; -UPDATE errtst_parent SET data = data + 1 WHERE partid = 20; -ROLLBACK; - --- within partition update with child check constraint violation -UPDATE errtst_parent SET data = data + 10 WHERE partid = 0; -UPDATE errtst_parent SET data = data + 10 WHERE partid = 10; -UPDATE errtst_parent SET data = data + 10 WHERE partid = 20; - --- direct leaf partition update, without partition id violation -BEGIN; -UPDATE errtst_child_fastdef SET partid = 1 WHERE partid = 0; -UPDATE errtst_child_plaindef SET partid = 11 WHERE partid = 10; -UPDATE errtst_child_reorder SET partid = 21 WHERE partid = 20; -ROLLBACK; - --- direct leaf partition update, with partition id violation -UPDATE errtst_child_fastdef SET partid = partid + 10 WHERE partid = 0; -UPDATE errtst_child_plaindef SET partid = partid + 10 WHERE partid = 10; -UPDATE errtst_child_reorder SET partid = partid + 10 WHERE partid = 20; - --- partition move, without child check constraint violation -BEGIN; -UPDATE errtst_parent SET partid = 10, data = data + 1 WHERE partid = 0; -UPDATE errtst_parent SET partid = 20, data = data + 1 WHERE partid = 10; -UPDATE errtst_parent SET partid = 0, data = data + 1 WHERE partid = 20; -ROLLBACK; - --- partition move, with child check constraint violation -UPDATE errtst_parent SET partid = 10, data = data + 10 WHERE partid = 0; -UPDATE errtst_parent SET partid = 20, data = data + 10 WHERE partid = 10; -UPDATE errtst_parent SET partid = 0, data = data + 10 WHERE partid = 20; - --- partition move, without target partition -UPDATE errtst_parent SET partid = 30, data = data + 10 WHERE partid = 20; - -DROP TABLE errtst_parent; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finsert.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finsert.sql deleted file mode 100644 index bdcffd0314..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finsert.sql +++ /dev/null @@ -1,599 +0,0 @@ --- --- insert with DEFAULT in the target_list --- -create table inserttest (col1 int4, col2 int4 NOT NULL, col3 text default 'testing'); -insert into inserttest (col1, col2, col3) values (DEFAULT, DEFAULT, DEFAULT); -insert into inserttest (col2, col3) values (3, DEFAULT); -insert into inserttest (col1, col2, col3) values (DEFAULT, 5, DEFAULT); -insert into inserttest values (DEFAULT, 5, 'test'); -insert into inserttest values (DEFAULT, 7); - -select * from inserttest; - --- --- insert with similar expression / target_list values (all fail) --- -insert into inserttest (col1, col2, col3) values (DEFAULT, DEFAULT); -insert into inserttest (col1, col2, col3) values (1, 2); -insert into inserttest (col1) values (1, 2); -insert into inserttest (col1) values (DEFAULT, DEFAULT); - -select * from inserttest; - --- --- VALUES test --- -insert into inserttest values(10, 20, '40'), (-1, 2, DEFAULT), - ((select 2), (select i from (values(3)) as foo (i)), 'values are fun!'); - -select * from inserttest; - --- --- TOASTed value test --- -insert into inserttest values(30, 50, repeat('x', 10000)); - -select col1, col2, char_length(col3) from inserttest; - -drop table inserttest; - --- --- tuple larger than fillfactor --- -CREATE TABLE large_tuple_test (a int, b text) WITH (fillfactor = 10); -ALTER TABLE large_tuple_test ALTER COLUMN b SET STORAGE plain; - --- create page w/ free space in range [nearlyEmptyFreeSpace, MaxHeapTupleSize) -INSERT INTO large_tuple_test (select 1, NULL); - --- should still fit on the page -INSERT INTO large_tuple_test (select 2, repeat('a', 1000)); -SELECT pg_size_pretty(pg_relation_size('large_tuple_test'::regclass, 'main')); - --- add small record to the second page -INSERT INTO large_tuple_test (select 3, NULL); - --- now this tuple won't fit on the second page, but the insert should --- still succeed by extending the relation -INSERT INTO large_tuple_test (select 4, repeat('a', 8126)); - -DROP TABLE large_tuple_test; - --- --- check indirection (field/array assignment), cf bug #14265 --- --- these tests are aware that transformInsertStmt has 3 separate code paths --- - -create type insert_test_type as (if1 int, if2 text[]); - -create table inserttest (f1 int, f2 int[], - f3 insert_test_type, f4 insert_test_type[]); - -insert into inserttest (f2[1], f2[2]) values (1,2); -insert into inserttest (f2[1], f2[2]) values (3,4), (5,6); -insert into inserttest (f2[1], f2[2]) select 7,8; -insert into inserttest (f2[1], f2[2]) values (1,default); -- not supported - -insert into inserttest (f3.if1, f3.if2) values (1,array['foo']); -insert into inserttest (f3.if1, f3.if2) values (1,'{foo}'), (2,'{bar}'); -insert into inserttest (f3.if1, f3.if2) select 3, '{baz,quux}'; -insert into inserttest (f3.if1, f3.if2) values (1,default); -- not supported - -insert into inserttest (f3.if2[1], f3.if2[2]) values ('foo', 'bar'); -insert into inserttest (f3.if2[1], f3.if2[2]) values ('foo', 'bar'), ('baz', 'quux'); -insert into inserttest (f3.if2[1], f3.if2[2]) select 'bear', 'beer'; - -insert into inserttest (f4[1].if2[1], f4[1].if2[2]) values ('foo', 'bar'); -insert into inserttest (f4[1].if2[1], f4[1].if2[2]) values ('foo', 'bar'), ('baz', 'quux'); -insert into inserttest (f4[1].if2[1], f4[1].if2[2]) select 'bear', 'beer'; - -select * from inserttest; - --- also check reverse-listing -create table inserttest2 (f1 bigint, f2 text); -create rule irule1 as on insert to inserttest2 do also - insert into inserttest (f3.if2[1], f3.if2[2]) - values (new.f1,new.f2); -create rule irule2 as on insert to inserttest2 do also - insert into inserttest (f4[1].if1, f4[1].if2[2]) - values (1,'fool'),(new.f1,new.f2); -create rule irule3 as on insert to inserttest2 do also - insert into inserttest (f4[1].if1, f4[1].if2[2]) - select new.f1, new.f2; -\d+ inserttest2 - -drop table inserttest2; -drop table inserttest; -drop type insert_test_type; - --- direct partition inserts should check partition bound constraint -create table range_parted ( - a text, - b int -) partition by range (a, (b+0)); - --- no partitions, so fail -insert into range_parted values ('a', 11); - -create table part1 partition of range_parted for values from ('a', 1) to ('a', 10); -create table part2 partition of range_parted for values from ('a', 10) to ('a', 20); -create table part3 partition of range_parted for values from ('b', 1) to ('b', 10); -create table part4 partition of range_parted for values from ('b', 10) to ('b', 20); - --- fail -insert into part1 values ('a', 11); -insert into part1 values ('b', 1); --- ok -insert into part1 values ('a', 1); --- fail -insert into part4 values ('b', 21); -insert into part4 values ('a', 10); --- ok -insert into part4 values ('b', 10); - --- fail (partition key a has a NOT NULL constraint) -insert into part1 values (null); --- fail (expression key (b+0) cannot be null either) -insert into part1 values (1); - -create table list_parted ( - a text, - b int -) partition by list (lower(a)); -create table part_aa_bb partition of list_parted FOR VALUES IN ('aa', 'bb'); -create table part_cc_dd partition of list_parted FOR VALUES IN ('cc', 'dd'); -create table part_null partition of list_parted FOR VALUES IN (null); - --- fail -insert into part_aa_bb values ('cc', 1); -insert into part_aa_bb values ('AAa', 1); -insert into part_aa_bb values (null); --- ok -insert into part_cc_dd values ('cC', 1); -insert into part_null values (null, 0); - --- check in case of multi-level partitioned table -create table part_ee_ff partition of list_parted for values in ('ee', 'ff') partition by range (b); -create table part_ee_ff1 partition of part_ee_ff for values from (1) to (10); -create table part_ee_ff2 partition of part_ee_ff for values from (10) to (20); - --- test default partition -create table part_default partition of list_parted default; --- Negative test: a row, which would fit in other partition, does not fit --- default partition, even when inserted directly -insert into part_default values ('aa', 2); -insert into part_default values (null, 2); --- ok -insert into part_default values ('Zz', 2); --- test if default partition works as expected for multi-level partitioned --- table as well as when default partition itself is further partitioned -drop table part_default; -create table part_xx_yy partition of list_parted for values in ('xx', 'yy') partition by list (a); -create table part_xx_yy_p1 partition of part_xx_yy for values in ('xx'); -create table part_xx_yy_defpart partition of part_xx_yy default; -create table part_default partition of list_parted default partition by range(b); -create table part_default_p1 partition of part_default for values from (20) to (30); -create table part_default_p2 partition of part_default for values from (30) to (40); - --- fail -insert into part_ee_ff1 values ('EE', 11); -insert into part_default_p2 values ('gg', 43); --- fail (even the parent's, ie, part_ee_ff's partition constraint applies) -insert into part_ee_ff1 values ('cc', 1); -insert into part_default values ('gg', 43); --- ok -insert into part_ee_ff1 values ('ff', 1); -insert into part_ee_ff2 values ('ff', 11); -insert into part_default_p1 values ('cd', 25); -insert into part_default_p2 values ('de', 35); -insert into list_parted values ('ab', 21); -insert into list_parted values ('xx', 1); -insert into list_parted values ('yy', 2); -select tableoid::regclass, * from list_parted; - --- Check tuple routing for partitioned tables - --- fail -insert into range_parted values ('a', 0); --- ok -insert into range_parted values ('a', 1); -insert into range_parted values ('a', 10); --- fail -insert into range_parted values ('a', 20); --- ok -insert into range_parted values ('b', 1); -insert into range_parted values ('b', 10); --- fail (partition key (b+0) is null) -insert into range_parted values ('a'); - --- Check default partition -create table part_def partition of range_parted default; --- fail -insert into part_def values ('b', 10); --- ok -insert into part_def values ('c', 10); -insert into range_parted values (null, null); -insert into range_parted values ('a', null); -insert into range_parted values (null, 19); -insert into range_parted values ('b', 20); - -select tableoid::regclass, * from range_parted; --- ok -insert into list_parted values (null, 1); -insert into list_parted (a) values ('aA'); --- fail (partition of part_ee_ff not found in both cases) -insert into list_parted values ('EE', 0); -insert into part_ee_ff values ('EE', 0); --- ok -insert into list_parted values ('EE', 1); -insert into part_ee_ff values ('EE', 10); -select tableoid::regclass, * from list_parted; - --- some more tests to exercise tuple-routing with multi-level partitioning -create table part_gg partition of list_parted for values in ('gg') partition by range (b); -create table part_gg1 partition of part_gg for values from (minvalue) to (1); -create table part_gg2 partition of part_gg for values from (1) to (10) partition by range (b); -create table part_gg2_1 partition of part_gg2 for values from (1) to (5); -create table part_gg2_2 partition of part_gg2 for values from (5) to (10); - -create table part_ee_ff3 partition of part_ee_ff for values from (20) to (30) partition by range (b); -create table part_ee_ff3_1 partition of part_ee_ff3 for values from (20) to (25); -create table part_ee_ff3_2 partition of part_ee_ff3 for values from (25) to (30); - -truncate list_parted; -insert into list_parted values ('aa'), ('cc'); -insert into list_parted select 'Ff', s.a from generate_series(1, 29) s(a); -insert into list_parted select 'gg', s.a from generate_series(1, 9) s(a); -insert into list_parted (b) values (1); -select tableoid::regclass::text, a, min(b) as min_b, max(b) as max_b from list_parted group by 1, 2 order by 1; - --- direct partition inserts should check hash partition bound constraint - -create table hash_parted ( - a int -) partition by hash (a part_test_int4_ops); -create table hpart0 partition of hash_parted for values with (modulus 4, remainder 0); -create table hpart1 partition of hash_parted for values with (modulus 4, remainder 1); -create table hpart2 partition of hash_parted for values with (modulus 4, remainder 2); -create table hpart3 partition of hash_parted for values with (modulus 4, remainder 3); - -insert into hash_parted values(generate_series(1,10)); - --- direct insert of values divisible by 4 - ok; -insert into hpart0 values(12),(16); --- fail; -insert into hpart0 values(11); --- 11 % 4 -> 3 remainder i.e. valid data for hpart3 partition -insert into hpart3 values(11); - --- view data -select tableoid::regclass as part, a, a%4 as "remainder = a % 4" -from hash_parted order by part; - --- test \d+ output on a table which has both partitioned and unpartitioned --- partitions -\d+ list_parted - --- cleanup -drop table range_parted, list_parted; -drop table hash_parted; - --- test that a default partition added as the first partition accepts any value --- including null -create table list_parted (a int) partition by list (a); -create table part_default partition of list_parted default; -\d+ part_default -insert into part_default values (null); -insert into part_default values (1); -insert into part_default values (-1); -select tableoid::regclass, a from list_parted; --- cleanup -drop table list_parted; - --- more tests for certain multi-level partitioning scenarios -create table mlparted (a int, b int) partition by range (a, b); -create table mlparted1 (b int not null, a int not null) partition by range ((b+0)); -create table mlparted11 (like mlparted1); -alter table mlparted11 drop a; -alter table mlparted11 add a int; -alter table mlparted11 drop a; -alter table mlparted11 add a int not null; --- attnum for key attribute 'a' is different in mlparted, mlparted1, and mlparted11 -select attrelid::regclass, attname, attnum -from pg_attribute -where attname = 'a' - and (attrelid = 'mlparted'::regclass - or attrelid = 'mlparted1'::regclass - or attrelid = 'mlparted11'::regclass) -order by attrelid::regclass::text; - -alter table mlparted1 attach partition mlparted11 for values from (2) to (5); -alter table mlparted attach partition mlparted1 for values from (1, 2) to (1, 10); - --- check that "(1, 2)" is correctly routed to mlparted11. -insert into mlparted values (1, 2); -select tableoid::regclass, * from mlparted; - --- check that proper message is shown after failure to route through mlparted1 -insert into mlparted (a, b) values (1, 5); - -truncate mlparted; -alter table mlparted add constraint check_b check (b = 3); - --- have a BR trigger modify the row such that the check_b is violated -create function mlparted11_trig_fn() -returns trigger AS -$$ -begin - NEW.b := 4; - return NEW; -end; -$$ -language plpgsql; -create trigger mlparted11_trig before insert ON mlparted11 - for each row execute procedure mlparted11_trig_fn(); - --- check that the correct row is shown when constraint check_b fails after --- "(1, 2)" is routed to mlparted11 (actually "(1, 4)" would be shown due --- to the BR trigger mlparted11_trig_fn) -insert into mlparted values (1, 2); -drop trigger mlparted11_trig on mlparted11; -drop function mlparted11_trig_fn(); - --- check that inserting into an internal partition successfully results in --- checking its partition constraint before inserting into the leaf partition --- selected by tuple-routing -insert into mlparted1 (a, b) values (2, 3); - --- check routing error through a list partitioned table when the key is null -create table lparted_nonullpart (a int, b char) partition by list (b); -create table lparted_nonullpart_a partition of lparted_nonullpart for values in ('a'); -insert into lparted_nonullpart values (1); -drop table lparted_nonullpart; - --- check that RETURNING works correctly with tuple-routing -alter table mlparted drop constraint check_b; -create table mlparted12 partition of mlparted1 for values from (5) to (10); -create table mlparted2 (b int not null, a int not null); -alter table mlparted attach partition mlparted2 for values from (1, 10) to (1, 20); -create table mlparted3 partition of mlparted for values from (1, 20) to (1, 30); -create table mlparted4 (like mlparted); -alter table mlparted4 drop a; -alter table mlparted4 add a int not null; -alter table mlparted attach partition mlparted4 for values from (1, 30) to (1, 40); -with ins (a, b, c) as - (insert into mlparted (b, a) select s.a, 1 from generate_series(2, 39) s(a) returning tableoid::regclass, *) - select a, b, min(c), max(c) from ins group by a, b order by 1; - -alter table mlparted add c text; -create table mlparted5 (c text, a int not null, b int not null) partition by list (c); -create table mlparted5a (a int not null, c text, b int not null); -alter table mlparted5 attach partition mlparted5a for values in ('a'); -alter table mlparted attach partition mlparted5 for values from (1, 40) to (1, 50); -alter table mlparted add constraint check_b check (a = 1 and b < 45); -insert into mlparted values (1, 45, 'a'); -create function mlparted5abrtrig_func() returns trigger as $$ begin new.c = 'b'; return new; end; $$ language plpgsql; -create trigger mlparted5abrtrig before insert on mlparted5a for each row execute procedure mlparted5abrtrig_func(); -insert into mlparted5 (a, b, c) values (1, 40, 'a'); -drop table mlparted5; -alter table mlparted drop constraint check_b; - --- Check multi-level default partition -create table mlparted_def partition of mlparted default partition by range(a); -create table mlparted_def1 partition of mlparted_def for values from (40) to (50); -create table mlparted_def2 partition of mlparted_def for values from (50) to (60); -insert into mlparted values (40, 100); -insert into mlparted_def1 values (42, 100); -insert into mlparted_def2 values (54, 50); --- fail -insert into mlparted values (70, 100); -insert into mlparted_def1 values (52, 50); -insert into mlparted_def2 values (34, 50); --- ok -create table mlparted_defd partition of mlparted_def default; -insert into mlparted values (70, 100); - -select tableoid::regclass, * from mlparted_def; - --- Check multi-level tuple routing with attributes dropped from the --- top-most parent. First remove the last attribute. -alter table mlparted add d int, add e int; -alter table mlparted drop e; -create table mlparted5 partition of mlparted - for values from (1, 40) to (1, 50) partition by range (c); -create table mlparted5_ab partition of mlparted5 - for values from ('a') to ('c') partition by list (c); --- This partitioned table should remain with no partitions. -create table mlparted5_cd partition of mlparted5 - for values from ('c') to ('e') partition by list (c); -create table mlparted5_a partition of mlparted5_ab for values in ('a'); -create table mlparted5_b (d int, b int, c text, a int); -alter table mlparted5_ab attach partition mlparted5_b for values in ('b'); -truncate mlparted; -insert into mlparted values (1, 2, 'a', 1); -insert into mlparted values (1, 40, 'a', 1); -- goes to mlparted5_a -insert into mlparted values (1, 45, 'b', 1); -- goes to mlparted5_b -insert into mlparted values (1, 45, 'c', 1); -- goes to mlparted5_cd, fails -insert into mlparted values (1, 45, 'f', 1); -- goes to mlparted5, fails -select tableoid::regclass, * from mlparted order by a, b, c, d; -alter table mlparted drop d; -truncate mlparted; --- Remove the before last attribute. -alter table mlparted add e int, add d int; -alter table mlparted drop e; -insert into mlparted values (1, 2, 'a', 1); -insert into mlparted values (1, 40, 'a', 1); -- goes to mlparted5_a -insert into mlparted values (1, 45, 'b', 1); -- goes to mlparted5_b -insert into mlparted values (1, 45, 'c', 1); -- goes to mlparted5_cd, fails -insert into mlparted values (1, 45, 'f', 1); -- goes to mlparted5, fails -select tableoid::regclass, * from mlparted order by a, b, c, d; -alter table mlparted drop d; -drop table mlparted5; - --- check that message shown after failure to find a partition shows the --- appropriate key description (or none) in various situations -create table key_desc (a int, b int) partition by list ((a+0)); -create table key_desc_1 partition of key_desc for values in (1) partition by range (b); - -create user regress_insert_other_user; -grant select (a) on key_desc_1 to regress_insert_other_user; -grant insert on key_desc to regress_insert_other_user; - -set role regress_insert_other_user; --- no key description is shown -insert into key_desc values (1, 1); - -reset role; -grant select (b) on key_desc_1 to regress_insert_other_user; -set role regress_insert_other_user; --- key description (b)=(1) is now shown -insert into key_desc values (1, 1); - --- key description is not shown if key contains expression -insert into key_desc values (2, 1); -reset role; -revoke all on key_desc from regress_insert_other_user; -revoke all on key_desc_1 from regress_insert_other_user; -drop role regress_insert_other_user; -drop table key_desc, key_desc_1; - --- test minvalue/maxvalue restrictions -create table mcrparted (a int, b int, c int) partition by range (a, abs(b), c); -create table mcrparted0 partition of mcrparted for values from (minvalue, 0, 0) to (1, maxvalue, maxvalue); -create table mcrparted2 partition of mcrparted for values from (10, 6, minvalue) to (10, maxvalue, minvalue); -create table mcrparted4 partition of mcrparted for values from (21, minvalue, 0) to (30, 20, minvalue); - --- check multi-column range partitioning expression enforces the same --- constraint as what tuple-routing would determine it to be -create table mcrparted0 partition of mcrparted for values from (minvalue, minvalue, minvalue) to (1, maxvalue, maxvalue); -create table mcrparted1 partition of mcrparted for values from (2, 1, minvalue) to (10, 5, 10); -create table mcrparted2 partition of mcrparted for values from (10, 6, minvalue) to (10, maxvalue, maxvalue); -create table mcrparted3 partition of mcrparted for values from (11, 1, 1) to (20, 10, 10); -create table mcrparted4 partition of mcrparted for values from (21, minvalue, minvalue) to (30, 20, maxvalue); -create table mcrparted5 partition of mcrparted for values from (30, 21, 20) to (maxvalue, maxvalue, maxvalue); - --- null not allowed in range partition -insert into mcrparted values (null, null, null); - --- routed to mcrparted0 -insert into mcrparted values (0, 1, 1); -insert into mcrparted0 values (0, 1, 1); - --- routed to mcparted1 -insert into mcrparted values (9, 1000, 1); -insert into mcrparted1 values (9, 1000, 1); -insert into mcrparted values (10, 5, -1); -insert into mcrparted1 values (10, 5, -1); -insert into mcrparted values (2, 1, 0); -insert into mcrparted1 values (2, 1, 0); - --- routed to mcparted2 -insert into mcrparted values (10, 6, 1000); -insert into mcrparted2 values (10, 6, 1000); -insert into mcrparted values (10, 1000, 1000); -insert into mcrparted2 values (10, 1000, 1000); - --- no partition exists, nor does mcrparted3 accept it -insert into mcrparted values (11, 1, -1); -insert into mcrparted3 values (11, 1, -1); - --- routed to mcrparted5 -insert into mcrparted values (30, 21, 20); -insert into mcrparted5 values (30, 21, 20); -insert into mcrparted4 values (30, 21, 20); -- error - --- check rows -select tableoid::regclass::text, * from mcrparted order by 1; - --- cleanup -drop table mcrparted; - --- check that a BR constraint can't make partition contain violating rows -create table brtrigpartcon (a int, b text) partition by list (a); -create table brtrigpartcon1 partition of brtrigpartcon for values in (1); -create or replace function brtrigpartcon1trigf() returns trigger as $$begin new.a := 2; return new; end$$ language plpgsql; -create trigger brtrigpartcon1trig before insert on brtrigpartcon1 for each row execute procedure brtrigpartcon1trigf(); -insert into brtrigpartcon values (1, 'hi there'); -insert into brtrigpartcon1 values (1, 'hi there'); - --- check that the message shows the appropriate column description in a --- situation where the partitioned table is not the primary ModifyTable node -create table inserttest3 (f1 text default 'foo', f2 text default 'bar', f3 int); -create role regress_coldesc_role; -grant insert on inserttest3 to regress_coldesc_role; -grant insert on brtrigpartcon to regress_coldesc_role; -revoke select on brtrigpartcon from regress_coldesc_role; -set role regress_coldesc_role; -with result as (insert into brtrigpartcon values (1, 'hi there') returning 1) - insert into inserttest3 (f3) select * from result; -reset role; - --- cleanup -revoke all on inserttest3 from regress_coldesc_role; -revoke all on brtrigpartcon from regress_coldesc_role; -drop role regress_coldesc_role; -drop table inserttest3; -drop table brtrigpartcon; -drop function brtrigpartcon1trigf(); - --- check that "do nothing" BR triggers work with tuple-routing -create table donothingbrtrig_test (a int, b text) partition by list (a); -create table donothingbrtrig_test1 (b text, a int); -create table donothingbrtrig_test2 (c text, b text, a int); -alter table donothingbrtrig_test2 drop column c; -create or replace function donothingbrtrig_func() returns trigger as $$begin raise notice 'b: %', new.b; return NULL; end$$ language plpgsql; -create trigger donothingbrtrig1 before insert on donothingbrtrig_test1 for each row execute procedure donothingbrtrig_func(); -create trigger donothingbrtrig2 before insert on donothingbrtrig_test2 for each row execute procedure donothingbrtrig_func(); -alter table donothingbrtrig_test attach partition donothingbrtrig_test1 for values in (1); -alter table donothingbrtrig_test attach partition donothingbrtrig_test2 for values in (2); -insert into donothingbrtrig_test values (1, 'foo'), (2, 'bar'); -copy donothingbrtrig_test from stdout; -1 baz -2 qux -\. -select tableoid::regclass, * from donothingbrtrig_test; - --- cleanup -drop table donothingbrtrig_test; -drop function donothingbrtrig_func(); - --- check multi-column range partitioning with minvalue/maxvalue constraints -create table mcrparted (a text, b int) partition by range(a, b); -create table mcrparted1_lt_b partition of mcrparted for values from (minvalue, minvalue) to ('b', minvalue); -create table mcrparted2_b partition of mcrparted for values from ('b', minvalue) to ('c', minvalue); -create table mcrparted3_c_to_common partition of mcrparted for values from ('c', minvalue) to ('common', minvalue); -create table mcrparted4_common_lt_0 partition of mcrparted for values from ('common', minvalue) to ('common', 0); -create table mcrparted5_common_0_to_10 partition of mcrparted for values from ('common', 0) to ('common', 10); -create table mcrparted6_common_ge_10 partition of mcrparted for values from ('common', 10) to ('common', maxvalue); -create table mcrparted7_gt_common_lt_d partition of mcrparted for values from ('common', maxvalue) to ('d', minvalue); -create table mcrparted8_ge_d partition of mcrparted for values from ('d', minvalue) to (maxvalue, maxvalue); - -\d+ mcrparted -\d+ mcrparted1_lt_b -\d+ mcrparted2_b -\d+ mcrparted3_c_to_common -\d+ mcrparted4_common_lt_0 -\d+ mcrparted5_common_0_to_10 -\d+ mcrparted6_common_ge_10 -\d+ mcrparted7_gt_common_lt_d -\d+ mcrparted8_ge_d - -insert into mcrparted values ('aaa', 0), ('b', 0), ('bz', 10), ('c', -10), - ('comm', -10), ('common', -10), ('common', 0), ('common', 10), - ('commons', 0), ('d', -10), ('e', 0); -select tableoid::regclass, * from mcrparted order by a, b; -drop table mcrparted; - --- check that wholerow vars in the RETURNING list work with partitioned tables -create table returningwrtest (a int) partition by list (a); -create table returningwrtest1 partition of returningwrtest for values in (1); -insert into returningwrtest values (1) returning returningwrtest; - --- check also that the wholerow vars in RETURNING list are converted as needed -alter table returningwrtest add b text; -create table returningwrtest2 (b text, c int, a int); -alter table returningwrtest2 drop c; -alter table returningwrtest attach partition returningwrtest2 for values in (2); -insert into returningwrtest values (2, 'foo') returning returningwrtest; -drop table returningwrtest; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finsert_conflict.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finsert_conflict.sql deleted file mode 100644 index 23d5778b82..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Finsert_conflict.sql +++ /dev/null @@ -1,582 +0,0 @@ --- --- insert...on conflict do unique index inference --- -create table insertconflicttest(key int4, fruit text); - --- --- Test unique index inference with operator class specifications and --- named collations --- -create unique index op_index_key on insertconflicttest(key, fruit text_pattern_ops); -create unique index collation_index_key on insertconflicttest(key, fruit collate "C"); -create unique index both_index_key on insertconflicttest(key, fruit collate "C" text_pattern_ops); -create unique index both_index_expr_key on insertconflicttest(key, lower(fruit) collate "C" text_pattern_ops); - --- fails -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (key) do nothing; -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (fruit) do nothing; - --- succeeds -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (key, fruit) do nothing; -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (fruit, key, fruit, key) do nothing; -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (lower(fruit), key, lower(fruit), key) do nothing; -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (key, fruit) do update set fruit = excluded.fruit - where exists (select 1 from insertconflicttest ii where ii.key = excluded.key); --- Neither collation nor operator class specifications are required -- --- supplying them merely *limits* matches to indexes with matching opclasses --- used for relevant indexes -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (key, fruit text_pattern_ops) do nothing; --- Okay, arbitrates using both index where text_pattern_ops opclass does and --- does not appear. -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (key, fruit collate "C") do nothing; --- Okay, but only accepts the single index where both opclass and collation are --- specified -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (fruit collate "C" text_pattern_ops, key) do nothing; --- Okay, but only accepts the single index where both opclass and collation are --- specified (plus expression variant) -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (lower(fruit) collate "C", key, key) do nothing; --- Attribute appears twice, while not all attributes/expressions on attributes --- appearing within index definition match in terms of both opclass and --- collation. --- --- Works because every attribute in inference specification needs to be --- satisfied once or more by cataloged index attribute, and as always when an --- attribute in the cataloged definition has a non-default opclass/collation, --- it still satisfied some inference attribute lacking any particular --- opclass/collation specification. --- --- The implementation is liberal in accepting inference specifications on the --- assumption that multiple inferred unique indexes will prevent problematic --- cases. It rolls with unique indexes where attributes redundantly appear --- multiple times, too (which is not tested here). -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (fruit, key, fruit text_pattern_ops, key) do nothing; -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (lower(fruit) collate "C" text_pattern_ops, key, key) do nothing; - -drop index op_index_key; -drop index collation_index_key; -drop index both_index_key; -drop index both_index_expr_key; - --- --- Make sure that cross matching of attribute opclass/collation does not occur --- -create unique index cross_match on insertconflicttest(lower(fruit) collate "C", upper(fruit) text_pattern_ops); - --- fails: -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (lower(fruit) text_pattern_ops, upper(fruit) collate "C") do nothing; --- works: -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (lower(fruit) collate "C", upper(fruit) text_pattern_ops) do nothing; - -drop index cross_match; - --- --- Single key tests --- -create unique index key_index on insertconflicttest(key); - --- --- Explain tests --- -explain (costs off) insert into insertconflicttest values (0, 'Bilberry') on conflict (key) do update set fruit = excluded.fruit; --- Should display qual actually attributable to internal sequential scan: -explain (costs off) insert into insertconflicttest values (0, 'Bilberry') on conflict (key) do update set fruit = excluded.fruit where insertconflicttest.fruit != 'Cawesh'; --- With EXCLUDED.* expression in scan node: -explain (costs off) insert into insertconflicttest values(0, 'Crowberry') on conflict (key) do update set fruit = excluded.fruit where excluded.fruit != 'Elderberry'; --- Does the same, but JSON format shows "Conflict Arbiter Index" as JSON array: -explain (costs off, format json) insert into insertconflicttest values (0, 'Bilberry') on conflict (key) do update set fruit = excluded.fruit where insertconflicttest.fruit != 'Lime' returning *; - --- Fails (no unique index inference specification, required for do update variant): -insert into insertconflicttest values (1, 'Apple') on conflict do update set fruit = excluded.fruit; - --- inference succeeds: -insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) do update set fruit = excluded.fruit; - --- Succeed, since multi-assignment does not involve subquery: -insert into insertconflicttest -values (1, 'Apple'), (2, 'Orange') -on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); - --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: -insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; - --- Only suggest .* column when inference element misspelled: -insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; - --- Have useful HINT for EXCLUDED.* RTE within UPDATE: -insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruitt; - --- inference fails: -insert into insertconflicttest values (3, 'Kiwi') on conflict (key, fruit) do update set fruit = excluded.fruit; -insert into insertconflicttest values (4, 'Mango') on conflict (fruit, key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (5, 'Lemon') on conflict (fruit) do update set fruit = excluded.fruit; -insert into insertconflicttest values (6, 'Passionfruit') on conflict (lower(fruit)) do update set fruit = excluded.fruit; - --- Check the target relation can be aliased -insert into insertconflicttest AS ict values (6, 'Passionfruit') on conflict (key) do update set fruit = excluded.fruit; -- ok, no reference to target table -insert into insertconflicttest AS ict values (6, 'Passionfruit') on conflict (key) do update set fruit = ict.fruit; -- ok, alias -insert into insertconflicttest AS ict values (6, 'Passionfruit') on conflict (key) do update set fruit = insertconflicttest.fruit; -- error, references aliased away name - -drop index key_index; - --- --- Composite key tests --- -create unique index comp_key_index on insertconflicttest(key, fruit); - --- inference succeeds: -insert into insertconflicttest values (7, 'Raspberry') on conflict (key, fruit) do update set fruit = excluded.fruit; -insert into insertconflicttest values (8, 'Lime') on conflict (fruit, key) do update set fruit = excluded.fruit; - --- inference fails: -insert into insertconflicttest values (9, 'Banana') on conflict (key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (10, 'Blueberry') on conflict (key, key, key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (11, 'Cherry') on conflict (key, lower(fruit)) do update set fruit = excluded.fruit; -insert into insertconflicttest values (12, 'Date') on conflict (lower(fruit), key) do update set fruit = excluded.fruit; - -drop index comp_key_index; - --- --- Partial index tests, no inference predicate specified --- -create unique index part_comp_key_index on insertconflicttest(key, fruit) where key < 5; -create unique index expr_part_comp_key_index on insertconflicttest(key, lower(fruit)) where key < 5; - --- inference fails: -insert into insertconflicttest values (13, 'Grape') on conflict (key, fruit) do update set fruit = excluded.fruit; -insert into insertconflicttest values (14, 'Raisin') on conflict (fruit, key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (15, 'Cranberry') on conflict (key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (16, 'Melon') on conflict (key, key, key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (17, 'Mulberry') on conflict (key, lower(fruit)) do update set fruit = excluded.fruit; -insert into insertconflicttest values (18, 'Pineapple') on conflict (lower(fruit), key) do update set fruit = excluded.fruit; - -drop index part_comp_key_index; -drop index expr_part_comp_key_index; - --- --- Expression index tests --- -create unique index expr_key_index on insertconflicttest(lower(fruit)); - --- inference succeeds: -insert into insertconflicttest values (20, 'Quince') on conflict (lower(fruit)) do update set fruit = excluded.fruit; -insert into insertconflicttest values (21, 'Pomegranate') on conflict (lower(fruit), lower(fruit)) do update set fruit = excluded.fruit; - --- inference fails: -insert into insertconflicttest values (22, 'Apricot') on conflict (upper(fruit)) do update set fruit = excluded.fruit; -insert into insertconflicttest values (23, 'Blackberry') on conflict (fruit) do update set fruit = excluded.fruit; - -drop index expr_key_index; - --- --- Expression index tests (with regular column) --- -create unique index expr_comp_key_index on insertconflicttest(key, lower(fruit)); -create unique index tricky_expr_comp_key_index on insertconflicttest(key, lower(fruit), upper(fruit)); - --- inference succeeds: -insert into insertconflicttest values (24, 'Plum') on conflict (key, lower(fruit)) do update set fruit = excluded.fruit; -insert into insertconflicttest values (25, 'Peach') on conflict (lower(fruit), key) do update set fruit = excluded.fruit; --- Should not infer "tricky_expr_comp_key_index" index: -explain (costs off) insert into insertconflicttest values (26, 'Fig') on conflict (lower(fruit), key, lower(fruit), key) do update set fruit = excluded.fruit; - --- inference fails: -insert into insertconflicttest values (27, 'Prune') on conflict (key, upper(fruit)) do update set fruit = excluded.fruit; -insert into insertconflicttest values (28, 'Redcurrant') on conflict (fruit, key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (29, 'Nectarine') on conflict (key) do update set fruit = excluded.fruit; - -drop index expr_comp_key_index; -drop index tricky_expr_comp_key_index; - --- --- Non-spurious duplicate violation tests --- -create unique index key_index on insertconflicttest(key); -create unique index fruit_index on insertconflicttest(fruit); - --- succeeds, since UPDATE happens to update "fruit" to existing value: -insert into insertconflicttest values (26, 'Fig') on conflict (key) do update set fruit = excluded.fruit; --- fails, since UPDATE is to row with key value 26, and we're updating "fruit" --- to a value that happens to exist in another row ('peach'): -insert into insertconflicttest values (26, 'Peach') on conflict (key) do update set fruit = excluded.fruit; --- succeeds, since "key" isn't repeated/referenced in UPDATE, and "fruit" --- arbitrates that statement updates existing "Fig" row: -insert into insertconflicttest values (25, 'Fig') on conflict (fruit) do update set fruit = excluded.fruit; - -drop index key_index; -drop index fruit_index; - --- --- Test partial unique index inference --- -create unique index partial_key_index on insertconflicttest(key) where fruit like '%berry'; - --- Succeeds -insert into insertconflicttest values (23, 'Blackberry') on conflict (key) where fruit like '%berry' do update set fruit = excluded.fruit; -insert into insertconflicttest as t values (23, 'Blackberry') on conflict (key) where fruit like '%berry' and t.fruit = 'inconsequential' do nothing; - --- fails -insert into insertconflicttest values (23, 'Blackberry') on conflict (key) do update set fruit = excluded.fruit; -insert into insertconflicttest values (23, 'Blackberry') on conflict (key) where fruit like '%berry' or fruit = 'consequential' do nothing; -insert into insertconflicttest values (23, 'Blackberry') on conflict (fruit) where fruit like '%berry' do update set fruit = excluded.fruit; - -drop index partial_key_index; - --- --- Test that wholerow references to ON CONFLICT's EXCLUDED work --- -create unique index plain on insertconflicttest(key); - --- Succeeds, updates existing row: -insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; --- No update this time, though: -insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; --- Predicate changed to require match rather than non-match, so updates once more: -insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; --- Assign: -insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; --- deparse whole row var in WHERE and SET clauses: -explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.fruit where excluded.* is null; -explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text; - -drop index plain; - --- Cleanup -drop table insertconflicttest; - - --- --- Verify that EXCLUDED does not allow system column references. These --- do not make sense because EXCLUDED isn't an already stored tuple --- (and thus doesn't have a ctid etc). --- -create table syscolconflicttest(key int4, data text); -insert into syscolconflicttest values (1); -insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.ctid::text; -drop table syscolconflicttest; - --- --- Previous tests all managed to not test any expressions requiring --- planner preprocessing ... --- -create table insertconflict (a bigint, b bigint); - -create unique index insertconflicti1 on insertconflict(coalesce(a, 0)); - -create unique index insertconflicti2 on insertconflict(b) - where coalesce(a, 1) > 0; - -insert into insertconflict values (1, 2) -on conflict (coalesce(a, 0)) do nothing; - -insert into insertconflict values (1, 2) -on conflict (b) where coalesce(a, 1) > 0 do nothing; - -insert into insertconflict values (1, 2) -on conflict (b) where coalesce(a, 1) > 1 do nothing; - -drop table insertconflict; - --- --- test insertion through view --- - -create table insertconflict (f1 int primary key, f2 text); -create view insertconflictv as - select * from insertconflict with cascaded check option; - -insert into insertconflictv values (1,'foo') - on conflict (f1) do update set f2 = excluded.f2; -select * from insertconflict; -insert into insertconflictv values (1,'bar') - on conflict (f1) do update set f2 = excluded.f2; -select * from insertconflict; - -drop view insertconflictv; -drop table insertconflict; - - --- ****************************************************************** --- * * --- * Test inheritance (example taken from tutorial) * --- * * --- ****************************************************************** -create table cities ( - name text, - population float8, - altitude int -- (in ft) -); - -create table capitals ( - state char(2) -) inherits (cities); - --- Create unique indexes. Due to a general limitation of inheritance, --- uniqueness is only enforced per-relation. Unique index inference --- specification will do the right thing, though. -create unique index cities_names_unique on cities (name); -create unique index capitals_names_unique on capitals (name); - --- prepopulate the tables. -insert into cities values ('San Francisco', 7.24E+5, 63); -insert into cities values ('Las Vegas', 2.583E+5, 2174); -insert into cities values ('Mariposa', 1200, 1953); - -insert into capitals values ('Sacramento', 3.694E+5, 30, 'CA'); -insert into capitals values ('Madison', 1.913E+5, 845, 'WI'); - --- Tests proper for inheritance: -select * from capitals; - --- Succeeds: -insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; --- Wrong "Sacramento", so do nothing: -insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; -select * from capitals; -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; -select tableoid::regclass, * from cities; -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; --- Capitals will contain new capital, Las Vegas: -select * from capitals; --- Cities contains two instances of "Las Vegas", since unique constraints don't --- work across inheritance: -select tableoid::regclass, * from cities; --- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; -select tableoid::regclass, * from cities; - --- clean up -drop table capitals; -drop table cities; - - --- Make sure a table named excluded is handled properly -create table excluded(key int primary key, data text); -insert into excluded values(1, '1'); --- error, ambiguous -insert into excluded values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; --- ok, aliased -insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; --- ok, aliased -insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause -insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - --- clean up -drop table excluded; - - --- check that references to columns after dropped columns are handled correctly -create table dropcol(key int primary key, drop1 int, keep1 text, drop2 numeric, keep2 float); -insert into dropcol(key, drop1, keep1, drop2, keep2) values(1, 1, '1', '1', 1); --- set using excluded -insert into dropcol(key, drop1, keep1, drop2, keep2) values(1, 2, '2', '2', 2) on conflict(key) - do update set drop1 = excluded.drop1, keep1 = excluded.keep1, drop2 = excluded.drop2, keep2 = excluded.keep2 - where excluded.drop1 is not null and excluded.keep1 is not null and excluded.drop2 is not null and excluded.keep2 is not null - and dropcol.drop1 is not null and dropcol.keep1 is not null and dropcol.drop2 is not null and dropcol.keep2 is not null - returning *; -; --- set using existing table -insert into dropcol(key, drop1, keep1, drop2, keep2) values(1, 3, '3', '3', 3) on conflict(key) - do update set drop1 = dropcol.drop1, keep1 = dropcol.keep1, drop2 = dropcol.drop2, keep2 = dropcol.keep2 - returning *; -; -alter table dropcol drop column drop1, drop column drop2; --- set using excluded -insert into dropcol(key, keep1, keep2) values(1, '4', 4) on conflict(key) - do update set keep1 = excluded.keep1, keep2 = excluded.keep2 - where excluded.keep1 is not null and excluded.keep2 is not null - and dropcol.keep1 is not null and dropcol.keep2 is not null - returning *; -; --- set using existing table -insert into dropcol(key, keep1, keep2) values(1, '5', 5) on conflict(key) - do update set keep1 = dropcol.keep1, keep2 = dropcol.keep2 - returning *; -; - -DROP TABLE dropcol; - --- check handling of regular btree constraint along with gist constraint - -create table twoconstraints (f1 int unique, f2 box, - exclude using gist(f2 with &&)); -insert into twoconstraints values(1, '((0,0),(1,1))'); -insert into twoconstraints values(1, '((2,2),(3,3))'); -- fail on f1 -insert into twoconstraints values(2, '((0,0),(1,2))'); -- fail on f2 -insert into twoconstraints values(2, '((0,0),(1,2))') - on conflict on constraint twoconstraints_f1_key do nothing; -- fail on f2 -insert into twoconstraints values(2, '((0,0),(1,2))') - on conflict on constraint twoconstraints_f2_excl do nothing; -- do nothing -select * from twoconstraints; -drop table twoconstraints; - --- check handling of self-conflicts at various isolation levels - -create table selfconflict (f1 int primary key, f2 int); - -begin transaction isolation level read committed; -insert into selfconflict values (1,1), (1,2) on conflict do nothing; -commit; - -begin transaction isolation level repeatable read; -insert into selfconflict values (2,1), (2,2) on conflict do nothing; -commit; - -begin transaction isolation level serializable; -insert into selfconflict values (3,1), (3,2) on conflict do nothing; -commit; - -begin transaction isolation level read committed; -insert into selfconflict values (4,1), (4,2) on conflict(f1) do update set f2 = 0; -commit; - -begin transaction isolation level repeatable read; -insert into selfconflict values (5,1), (5,2) on conflict(f1) do update set f2 = 0; -commit; - -begin transaction isolation level serializable; -insert into selfconflict values (6,1), (6,2) on conflict(f1) do update set f2 = 0; -commit; - -select * from selfconflict; - -drop table selfconflict; - --- check ON CONFLICT handling with partitioned tables -create table parted_conflict_test (a int unique, b char) partition by list (a); -create table parted_conflict_test_1 partition of parted_conflict_test (b unique) for values in (1, 2); - --- no indexes required here -insert into parted_conflict_test values (1, 'a') on conflict do nothing; - --- index on a required, which does exist in parent -insert into parted_conflict_test values (1, 'a') on conflict (a) do nothing; -insert into parted_conflict_test values (1, 'a') on conflict (a) do update set b = excluded.b; - --- targeting partition directly will work -insert into parted_conflict_test_1 values (1, 'a') on conflict (a) do nothing; -insert into parted_conflict_test_1 values (1, 'b') on conflict (a) do update set b = excluded.b; - --- index on b required, which doesn't exist in parent -insert into parted_conflict_test values (2, 'b') on conflict (b) do update set a = excluded.a; - --- targeting partition directly will work -insert into parted_conflict_test_1 values (2, 'b') on conflict (b) do update set a = excluded.a; - --- should see (2, 'b') -select * from parted_conflict_test order by a; - --- now check that DO UPDATE works correctly for target partition with --- different attribute numbers -create table parted_conflict_test_2 (b char, a int unique); -alter table parted_conflict_test attach partition parted_conflict_test_2 for values in (3); -truncate parted_conflict_test; -insert into parted_conflict_test values (3, 'a') on conflict (a) do update set b = excluded.b; -insert into parted_conflict_test values (3, 'b') on conflict (a) do update set b = excluded.b; - --- should see (3, 'b') -select * from parted_conflict_test order by a; - --- case where parent will have a dropped column, but the partition won't -alter table parted_conflict_test drop b, add b char; -create table parted_conflict_test_3 partition of parted_conflict_test for values in (4); -truncate parted_conflict_test; -insert into parted_conflict_test (a, b) values (4, 'a') on conflict (a) do update set b = excluded.b; -insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do update set b = excluded.b where parted_conflict_test.b = 'a'; - --- should see (4, 'b') -select * from parted_conflict_test order by a; - --- case with multi-level partitioning -create table parted_conflict_test_4 partition of parted_conflict_test for values in (5) partition by list (a); -create table parted_conflict_test_4_1 partition of parted_conflict_test_4 for values in (5); -truncate parted_conflict_test; -insert into parted_conflict_test (a, b) values (5, 'a') on conflict (a) do update set b = excluded.b; -insert into parted_conflict_test (a, b) values (5, 'b') on conflict (a) do update set b = excluded.b where parted_conflict_test.b = 'a'; - --- should see (5, 'b') -select * from parted_conflict_test order by a; - --- test with multiple rows -truncate parted_conflict_test; -insert into parted_conflict_test (a, b) values (1, 'a'), (2, 'a'), (4, 'a') on conflict (a) do update set b = excluded.b where excluded.b = 'b'; -insert into parted_conflict_test (a, b) values (1, 'b'), (2, 'c'), (4, 'b') on conflict (a) do update set b = excluded.b where excluded.b = 'b'; - --- should see (1, 'b'), (2, 'a'), (4, 'b') -select * from parted_conflict_test order by a; - -drop table parted_conflict_test; - --- test behavior of inserting a conflicting tuple into an intermediate --- partitioning level -create table parted_conflict (a int primary key, b text) partition by range (a); -create table parted_conflict_1 partition of parted_conflict for values from (0) to (1000) partition by range (a); -create table parted_conflict_1_1 partition of parted_conflict_1 for values from (0) to (500); -insert into parted_conflict values (40, 'forty'); -insert into parted_conflict_1 values (40, 'cuarenta') - on conflict (a) do update set b = excluded.b; -drop table parted_conflict; - --- same thing, but this time try to use an index that's created not in the --- partition -create table parted_conflict (a int, b text) partition by range (a); -create table parted_conflict_1 partition of parted_conflict for values from (0) to (1000) partition by range (a); -create table parted_conflict_1_1 partition of parted_conflict_1 for values from (0) to (500); -create unique index on only parted_conflict_1 (a); -create unique index on only parted_conflict (a); -alter index parted_conflict_a_idx attach partition parted_conflict_1_a_idx; -insert into parted_conflict values (40, 'forty'); -insert into parted_conflict_1 values (40, 'cuarenta') - on conflict (a) do update set b = excluded.b; -drop table parted_conflict; - --- test whole-row Vars in ON CONFLICT expressions -create table parted_conflict (a int, b text, c int) partition by range (a); -create table parted_conflict_1 (drp text, c int, a int, b text); -alter table parted_conflict_1 drop column drp; -create unique index on parted_conflict (a, b); -alter table parted_conflict attach partition parted_conflict_1 for values from (0) to (1000); -truncate parted_conflict; -insert into parted_conflict values (50, 'cincuenta', 1); -insert into parted_conflict values (50, 'cincuenta', 2) - on conflict (a, b) do update set (a, b, c) = row(excluded.*) - where parted_conflict = (50, text 'cincuenta', 1) and - excluded = (50, text 'cincuenta', 2); - --- should see (50, 'cincuenta', 2) -select * from parted_conflict order by a; - --- test with statement level triggers -create or replace function parted_conflict_update_func() returns trigger as $$ -declare - r record; -begin - for r in select * from inserted loop - raise notice 'a = %, b = %, c = %', r.a, r.b, r.c; - end loop; - return new; -end; -$$ language plpgsql; - -create trigger parted_conflict_update - after update on parted_conflict - referencing new table as inserted - for each statement - execute procedure parted_conflict_update_func(); - -truncate parted_conflict; - -insert into parted_conflict values (0, 'cero', 1); - -insert into parted_conflict values(0, 'cero', 1) - on conflict (a,b) do update set c = parted_conflict.c + 1; - -drop table parted_conflict; -drop function parted_conflict_update_func(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjoin.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjoin.sql deleted file mode 100644 index a27a72086e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjoin.sql +++ /dev/null @@ -1,2303 +0,0 @@ --- --- JOIN --- Test JOIN clauses --- - -CREATE TABLE J1_TBL ( - i integer, - j integer, - t text -); - -CREATE TABLE J2_TBL ( - i integer, - k integer -); - - -INSERT INTO J1_TBL VALUES (1, 4, 'one'); -INSERT INTO J1_TBL VALUES (2, 3, 'two'); -INSERT INTO J1_TBL VALUES (3, 2, 'three'); -INSERT INTO J1_TBL VALUES (4, 1, 'four'); -INSERT INTO J1_TBL VALUES (5, 0, 'five'); -INSERT INTO J1_TBL VALUES (6, 6, 'six'); -INSERT INTO J1_TBL VALUES (7, 7, 'seven'); -INSERT INTO J1_TBL VALUES (8, 8, 'eight'); -INSERT INTO J1_TBL VALUES (0, NULL, 'zero'); -INSERT INTO J1_TBL VALUES (NULL, NULL, 'null'); -INSERT INTO J1_TBL VALUES (NULL, 0, 'zero'); - -INSERT INTO J2_TBL VALUES (1, -1); -INSERT INTO J2_TBL VALUES (2, 2); -INSERT INTO J2_TBL VALUES (3, -3); -INSERT INTO J2_TBL VALUES (2, 4); -INSERT INTO J2_TBL VALUES (5, -5); -INSERT INTO J2_TBL VALUES (5, -5); -INSERT INTO J2_TBL VALUES (0, NULL); -INSERT INTO J2_TBL VALUES (NULL, NULL); -INSERT INTO J2_TBL VALUES (NULL, 0); - --- useful in some tests below -create temp table onerow(); -insert into onerow default values; -analyze onerow; - - --- --- CORRELATION NAMES --- Make sure that table/column aliases are supported --- before diving into more complex join syntax. --- - -SELECT * - FROM J1_TBL AS tx; - -SELECT * - FROM J1_TBL tx; - -SELECT * - FROM J1_TBL AS t1 (a, b, c); - -SELECT * - FROM J1_TBL t1 (a, b, c); - -SELECT * - FROM J1_TBL t1 (a, b, c), J2_TBL t2 (d, e); - -SELECT t1.a, t2.e - FROM J1_TBL t1 (a, b, c), J2_TBL t2 (d, e) - WHERE t1.a = t2.d; - - --- --- CROSS JOIN --- Qualifications are not allowed on cross joins, --- which degenerate into a standard unqualified inner join. --- - -SELECT * - FROM J1_TBL CROSS JOIN J2_TBL; - --- ambiguous column -SELECT i, k, t - FROM J1_TBL CROSS JOIN J2_TBL; - --- resolve previous ambiguity by specifying the table name -SELECT t1.i, k, t - FROM J1_TBL t1 CROSS JOIN J2_TBL t2; - -SELECT ii, tt, kk - FROM (J1_TBL CROSS JOIN J2_TBL) - AS tx (ii, jj, tt, ii2, kk); - -SELECT tx.ii, tx.jj, tx.kk - FROM (J1_TBL t1 (a, b, c) CROSS JOIN J2_TBL t2 (d, e)) - AS tx (ii, jj, tt, ii2, kk); - -SELECT * - FROM J1_TBL CROSS JOIN J2_TBL a CROSS JOIN J2_TBL b; - - --- --- --- Inner joins (equi-joins) --- --- - --- --- Inner joins (equi-joins) with USING clause --- The USING syntax changes the shape of the resulting table --- by including a column in the USING clause only once in the result. --- - --- Inner equi-join on specified column -SELECT * - FROM J1_TBL INNER JOIN J2_TBL USING (i); - --- Same as above, slightly different syntax -SELECT * - FROM J1_TBL JOIN J2_TBL USING (i); - -SELECT * - FROM J1_TBL t1 (a, b, c) JOIN J2_TBL t2 (a, d) USING (a) - ORDER BY a, d; - -SELECT * - FROM J1_TBL t1 (a, b, c) JOIN J2_TBL t2 (a, b) USING (b) - ORDER BY b, t1.a; - --- test join using aliases -SELECT * FROM J1_TBL JOIN J2_TBL USING (i) WHERE J1_TBL.t = 'one'; -- ok -SELECT * FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE J1_TBL.t = 'one'; -- ok -SELECT * FROM (J1_TBL JOIN J2_TBL USING (i)) AS x WHERE J1_TBL.t = 'one'; -- error -SELECT * FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE x.i = 1; -- ok -SELECT * FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE x.t = 'one'; -- error -SELECT * FROM (J1_TBL JOIN J2_TBL USING (i) AS x) AS xx WHERE x.i = 1; -- error (XXX could use better hint) -SELECT * FROM J1_TBL a1 JOIN J2_TBL a2 USING (i) AS a1; -- error -SELECT x.* FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE J1_TBL.t = 'one'; -SELECT ROW(x.*) FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE J1_TBL.t = 'one'; -SELECT row_to_json(x.*) FROM J1_TBL JOIN J2_TBL USING (i) AS x WHERE J1_TBL.t = 'one'; - --- --- NATURAL JOIN --- Inner equi-join on all columns with the same name --- - -SELECT * - FROM J1_TBL NATURAL JOIN J2_TBL; - -SELECT * - FROM J1_TBL t1 (a, b, c) NATURAL JOIN J2_TBL t2 (a, d); - -SELECT * - FROM J1_TBL t1 (a, b, c) NATURAL JOIN J2_TBL t2 (d, a); - --- mismatch number of columns --- currently, Postgres will fill in with underlying names -SELECT * - FROM J1_TBL t1 (a, b) NATURAL JOIN J2_TBL t2 (a); - - --- --- Inner joins (equi-joins) --- - -SELECT * - FROM J1_TBL JOIN J2_TBL ON (J1_TBL.i = J2_TBL.i); - -SELECT * - FROM J1_TBL JOIN J2_TBL ON (J1_TBL.i = J2_TBL.k); - - --- --- Non-equi-joins --- - -SELECT * - FROM J1_TBL JOIN J2_TBL ON (J1_TBL.i <= J2_TBL.k); - - --- --- Outer joins --- Note that OUTER is a noise word --- - -SELECT * - FROM J1_TBL LEFT OUTER JOIN J2_TBL USING (i) - ORDER BY i, k, t; - -SELECT * - FROM J1_TBL LEFT JOIN J2_TBL USING (i) - ORDER BY i, k, t; - -SELECT * - FROM J1_TBL RIGHT OUTER JOIN J2_TBL USING (i); - -SELECT * - FROM J1_TBL RIGHT JOIN J2_TBL USING (i); - -SELECT * - FROM J1_TBL FULL OUTER JOIN J2_TBL USING (i) - ORDER BY i, k, t; - -SELECT * - FROM J1_TBL FULL JOIN J2_TBL USING (i) - ORDER BY i, k, t; - -SELECT * - FROM J1_TBL LEFT JOIN J2_TBL USING (i) WHERE (k = 1); - -SELECT * - FROM J1_TBL LEFT JOIN J2_TBL USING (i) WHERE (i = 1); - --- --- semijoin selectivity for <> --- -explain (costs off) -select * from int4_tbl i4, tenk1 a -where exists(select * from tenk1 b - where a.twothousand = b.twothousand and a.fivethous <> b.fivethous) - and i4.f1 = a.tenthous; - - --- --- More complicated constructs --- - --- --- Multiway full join --- - -CREATE TABLE t1 (name TEXT, n INTEGER); -CREATE TABLE t2 (name TEXT, n INTEGER); -CREATE TABLE t3 (name TEXT, n INTEGER); - -INSERT INTO t1 VALUES ( 'bb', 11 ); -INSERT INTO t2 VALUES ( 'bb', 12 ); -INSERT INTO t2 VALUES ( 'cc', 22 ); -INSERT INTO t2 VALUES ( 'ee', 42 ); -INSERT INTO t3 VALUES ( 'bb', 13 ); -INSERT INTO t3 VALUES ( 'cc', 23 ); -INSERT INTO t3 VALUES ( 'dd', 33 ); - -SELECT * FROM t1 FULL JOIN t2 USING (name) FULL JOIN t3 USING (name); - --- --- Test interactions of join syntax and subqueries --- - --- Basic cases (we expect planner to pull up the subquery here) -SELECT * FROM -(SELECT * FROM t2) as s2 -INNER JOIN -(SELECT * FROM t3) s3 -USING (name); - -SELECT * FROM -(SELECT * FROM t2) as s2 -LEFT JOIN -(SELECT * FROM t3) s3 -USING (name); - -SELECT * FROM -(SELECT * FROM t2) as s2 -FULL JOIN -(SELECT * FROM t3) s3 -USING (name); - --- Cases with non-nullable expressions in subquery results; --- make sure these go to null as expected -SELECT * FROM -(SELECT name, n as s2_n, 2 as s2_2 FROM t2) as s2 -NATURAL INNER JOIN -(SELECT name, n as s3_n, 3 as s3_2 FROM t3) s3; - -SELECT * FROM -(SELECT name, n as s2_n, 2 as s2_2 FROM t2) as s2 -NATURAL LEFT JOIN -(SELECT name, n as s3_n, 3 as s3_2 FROM t3) s3; - -SELECT * FROM -(SELECT name, n as s2_n, 2 as s2_2 FROM t2) as s2 -NATURAL FULL JOIN -(SELECT name, n as s3_n, 3 as s3_2 FROM t3) s3; - -SELECT * FROM -(SELECT name, n as s1_n, 1 as s1_1 FROM t1) as s1 -NATURAL INNER JOIN -(SELECT name, n as s2_n, 2 as s2_2 FROM t2) as s2 -NATURAL INNER JOIN -(SELECT name, n as s3_n, 3 as s3_2 FROM t3) s3; - -SELECT * FROM -(SELECT name, n as s1_n, 1 as s1_1 FROM t1) as s1 -NATURAL FULL JOIN -(SELECT name, n as s2_n, 2 as s2_2 FROM t2) as s2 -NATURAL FULL JOIN -(SELECT name, n as s3_n, 3 as s3_2 FROM t3) s3; - -SELECT * FROM -(SELECT name, n as s1_n FROM t1) as s1 -NATURAL FULL JOIN - (SELECT * FROM - (SELECT name, n as s2_n FROM t2) as s2 - NATURAL FULL JOIN - (SELECT name, n as s3_n FROM t3) as s3 - ) ss2; - -SELECT * FROM -(SELECT name, n as s1_n FROM t1) as s1 -NATURAL FULL JOIN - (SELECT * FROM - (SELECT name, n as s2_n, 2 as s2_2 FROM t2) as s2 - NATURAL FULL JOIN - (SELECT name, n as s3_n FROM t3) as s3 - ) ss2; - --- Constants as join keys can also be problematic -SELECT * FROM - (SELECT name, n as s1_n FROM t1) as s1 -FULL JOIN - (SELECT name, 2 as s2_n FROM t2) as s2 -ON (s1_n = s2_n); - - --- Test for propagation of nullability constraints into sub-joins - -create temp table x (x1 int, x2 int); -insert into x values (1,11); -insert into x values (2,22); -insert into x values (3,null); -insert into x values (4,44); -insert into x values (5,null); - -create temp table y (y1 int, y2 int); -insert into y values (1,111); -insert into y values (2,222); -insert into y values (3,333); -insert into y values (4,null); - -select * from x; -select * from y; - -select * from x left join y on (x1 = y1 and x2 is not null); -select * from x left join y on (x1 = y1 and y2 is not null); - -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1); -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1 and x2 is not null); -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1 and y2 is not null); -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1 and xx2 is not null); --- these should NOT give the same answers as above -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1) where (x2 is not null); -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1) where (y2 is not null); -select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2) -on (x1 = xx1) where (xx2 is not null); - --- --- regression test: check for bug with propagation of implied equality --- to outside an IN --- -select count(*) from tenk1 a where unique1 in - (select unique1 from tenk1 b join tenk1 c using (unique1) - where b.unique2 = 42); - --- --- regression test: check for failure to generate a plan with multiple --- degenerate IN clauses --- -select count(*) from tenk1 x where - x.unique1 in (select a.f1 from int4_tbl a,float8_tbl b where a.f1=b.f1) and - x.unique1 = 0 and - x.unique1 in (select aa.f1 from int4_tbl aa,float8_tbl bb where aa.f1=bb.f1); - --- try that with GEQO too -begin; -set geqo = on; -set geqo_threshold = 2; -select count(*) from tenk1 x where - x.unique1 in (select a.f1 from int4_tbl a,float8_tbl b where a.f1=b.f1) and - x.unique1 = 0 and - x.unique1 in (select aa.f1 from int4_tbl aa,float8_tbl bb where aa.f1=bb.f1); -rollback; - --- --- regression test: be sure we cope with proven-dummy append rels --- -explain (costs off) -select aa, bb, unique1, unique1 - from tenk1 right join b_star on aa = unique1 - where bb < bb and bb is null; - -select aa, bb, unique1, unique1 - from tenk1 right join b_star on aa = unique1 - where bb < bb and bb is null; - --- --- regression test: check handling of empty-FROM subquery underneath outer join --- -explain (costs off) -select * from int8_tbl i1 left join (int8_tbl i2 join - (select 123 as x) ss on i2.q1 = x) on i1.q2 = i2.q2 -order by 1, 2; - -select * from int8_tbl i1 left join (int8_tbl i2 join - (select 123 as x) ss on i2.q1 = x) on i1.q2 = i2.q2 -order by 1, 2; - --- --- regression test: check a case where join_clause_is_movable_into() gives --- an imprecise result, causing an assertion failure --- -select count(*) -from - (select t3.tenthous as x1, coalesce(t1.stringu1, t2.stringu1) as x2 - from tenk1 t1 - left join tenk1 t2 on t1.unique1 = t2.unique1 - join tenk1 t3 on t1.unique2 = t3.unique2) ss, - tenk1 t4, - tenk1 t5 -where t4.thousand = t5.unique1 and ss.x1 = t4.tenthous and ss.x2 = t5.stringu1; - --- --- regression test: check a case where we formerly missed including an EC --- enforcement clause because it was expected to be handled at scan level --- -explain (costs off) -select a.f1, b.f1, t.thousand, t.tenthous from - tenk1 t, - (select sum(f1)+1 as f1 from int4_tbl i4a) a, - (select sum(f1) as f1 from int4_tbl i4b) b -where b.f1 = t.thousand and a.f1 = b.f1 and (a.f1+b.f1+999) = t.tenthous; - -select a.f1, b.f1, t.thousand, t.tenthous from - tenk1 t, - (select sum(f1)+1 as f1 from int4_tbl i4a) a, - (select sum(f1) as f1 from int4_tbl i4b) b -where b.f1 = t.thousand and a.f1 = b.f1 and (a.f1+b.f1+999) = t.tenthous; - --- --- check a case where we formerly got confused by conflicting sort orders --- in redundant merge join path keys --- -explain (costs off) -select * from - j1_tbl full join - (select * from j2_tbl order by j2_tbl.i desc, j2_tbl.k asc) j2_tbl - on j1_tbl.i = j2_tbl.i and j1_tbl.i = j2_tbl.k; - -select * from - j1_tbl full join - (select * from j2_tbl order by j2_tbl.i desc, j2_tbl.k asc) j2_tbl - on j1_tbl.i = j2_tbl.i and j1_tbl.i = j2_tbl.k; - --- --- a different check for handling of redundant sort keys in merge joins --- -explain (costs off) -select count(*) from - (select * from tenk1 x order by x.thousand, x.twothousand, x.fivethous) x - left join - (select * from tenk1 y order by y.unique2) y - on x.thousand = y.unique2 and x.twothousand = y.hundred and x.fivethous = y.unique2; - -select count(*) from - (select * from tenk1 x order by x.thousand, x.twothousand, x.fivethous) x - left join - (select * from tenk1 y order by y.unique2) y - on x.thousand = y.unique2 and x.twothousand = y.hundred and x.fivethous = y.unique2; - - --- --- Clean up --- - -DROP TABLE t1; -DROP TABLE t2; -DROP TABLE t3; - -DROP TABLE J1_TBL; -DROP TABLE J2_TBL; - --- Both DELETE and UPDATE allow the specification of additional tables --- to "join" against to determine which rows should be modified. - -CREATE TEMP TABLE t1 (a int, b int); -CREATE TEMP TABLE t2 (a int, b int); -CREATE TEMP TABLE t3 (x int, y int); - -INSERT INTO t1 VALUES (5, 10); -INSERT INTO t1 VALUES (15, 20); -INSERT INTO t1 VALUES (100, 100); -INSERT INTO t1 VALUES (200, 1000); -INSERT INTO t2 VALUES (200, 2000); -INSERT INTO t3 VALUES (5, 20); -INSERT INTO t3 VALUES (6, 7); -INSERT INTO t3 VALUES (7, 8); -INSERT INTO t3 VALUES (500, 100); - -DELETE FROM t3 USING t1 table1 WHERE t3.x = table1.a; -SELECT * FROM t3; -DELETE FROM t3 USING t1 JOIN t2 USING (a) WHERE t3.x > t1.a; -SELECT * FROM t3; -DELETE FROM t3 USING t3 t3_other WHERE t3.x = t3_other.x AND t3.y = t3_other.y; -SELECT * FROM t3; - --- Test join against inheritance tree - -create temp table t2a () inherits (t2); - -insert into t2a values (200, 2001); - -select * from t1 left join t2 on (t1.a = t2.a); - --- Test matching of column name with wrong alias - -select t1.x from t1 join t3 on (t1.a = t3.x); - --- --- regression test for 8.1 merge right join bug --- - -CREATE TEMP TABLE tt1 ( tt1_id int4, joincol int4 ); -INSERT INTO tt1 VALUES (1, 11); -INSERT INTO tt1 VALUES (2, NULL); - -CREATE TEMP TABLE tt2 ( tt2_id int4, joincol int4 ); -INSERT INTO tt2 VALUES (21, 11); -INSERT INTO tt2 VALUES (22, 11); - -set enable_hashjoin to off; -set enable_nestloop to off; - --- these should give the same results - -select tt1.*, tt2.* from tt1 left join tt2 on tt1.joincol = tt2.joincol; - -select tt1.*, tt2.* from tt2 right join tt1 on tt1.joincol = tt2.joincol; - -reset enable_hashjoin; -reset enable_nestloop; - --- --- regression test for bug #13908 (hash join with skew tuples & nbatch increase) --- - -set work_mem to '64kB'; -set enable_mergejoin to off; -set enable_memoize to off; - -explain (costs off) -select count(*) from tenk1 a, tenk1 b - where a.hundred = b.thousand and (b.fivethous % 10) < 10; -select count(*) from tenk1 a, tenk1 b - where a.hundred = b.thousand and (b.fivethous % 10) < 10; - -reset work_mem; -reset enable_mergejoin; -reset enable_memoize; - --- --- regression test for 8.2 bug with improper re-ordering of left joins --- - -create temp table tt3(f1 int, f2 text); -insert into tt3 select x, repeat('xyzzy', 100) from generate_series(1,10000) x; -create index tt3i on tt3(f1); -analyze tt3; - -create temp table tt4(f1 int); -insert into tt4 values (0),(1),(9999); -analyze tt4; - -SELECT a.f1 -FROM tt4 a -LEFT JOIN ( - SELECT b.f1 - FROM tt3 b LEFT JOIN tt3 c ON (b.f1 = c.f1) - WHERE c.f1 IS NULL -) AS d ON (a.f1 = d.f1) -WHERE d.f1 IS NULL; - --- --- regression test for proper handling of outer joins within antijoins --- - -create temp table tt4x(c1 int, c2 int, c3 int); - -explain (costs off) -select * from tt4x t1 -where not exists ( - select 1 from tt4x t2 - left join tt4x t3 on t2.c3 = t3.c1 - left join ( select t5.c1 as c1 - from tt4x t4 left join tt4x t5 on t4.c2 = t5.c1 - ) a1 on t3.c2 = a1.c1 - where t1.c1 = t2.c2 -); - --- --- regression test for problems of the sort depicted in bug #3494 --- - -create temp table tt5(f1 int, f2 int); -create temp table tt6(f1 int, f2 int); - -insert into tt5 values(1, 10); -insert into tt5 values(1, 11); - -insert into tt6 values(1, 9); -insert into tt6 values(1, 2); -insert into tt6 values(2, 9); - -select * from tt5,tt6 where tt5.f1 = tt6.f1 and tt5.f1 = tt5.f2 - tt6.f2; - --- --- regression test for problems of the sort depicted in bug #3588 --- - -create temp table xx (pkxx int); -create temp table yy (pkyy int, pkxx int); - -insert into xx values (1); -insert into xx values (2); -insert into xx values (3); - -insert into yy values (101, 1); -insert into yy values (201, 2); -insert into yy values (301, NULL); - -select yy.pkyy as yy_pkyy, yy.pkxx as yy_pkxx, yya.pkyy as yya_pkyy, - xxa.pkxx as xxa_pkxx, xxb.pkxx as xxb_pkxx -from yy - left join (SELECT * FROM yy where pkyy = 101) as yya ON yy.pkyy = yya.pkyy - left join xx xxa on yya.pkxx = xxa.pkxx - left join xx xxb on coalesce (xxa.pkxx, 1) = xxb.pkxx; - --- --- regression test for improper pushing of constants across outer-join clauses --- (as seen in early 8.2.x releases) --- - -create temp table zt1 (f1 int primary key); -create temp table zt2 (f2 int primary key); -create temp table zt3 (f3 int primary key); -insert into zt1 values(53); -insert into zt2 values(53); - -select * from - zt2 left join zt3 on (f2 = f3) - left join zt1 on (f3 = f1) -where f2 = 53; - -create temp view zv1 as select *,'dummy'::text AS junk from zt1; - -select * from - zt2 left join zt3 on (f2 = f3) - left join zv1 on (f3 = f1) -where f2 = 53; - --- --- regression test for improper extraction of OR indexqual conditions --- (as seen in early 8.3.x releases) --- - -select a.unique2, a.ten, b.tenthous, b.unique2, b.hundred -from tenk1 a left join tenk1 b on a.unique2 = b.tenthous -where a.unique1 = 42 and - ((b.unique2 is null and a.ten = 2) or b.hundred = 3); - --- --- test proper positioning of one-time quals in EXISTS (8.4devel bug) --- -prepare foo(bool) as - select count(*) from tenk1 a left join tenk1 b - on (a.unique2 = b.unique1 and exists - (select 1 from tenk1 c where c.thousand = b.unique2 and $1)); -execute foo(true); -execute foo(false); - --- --- test for sane behavior with noncanonical merge clauses, per bug #4926 --- - -begin; - -set enable_mergejoin = 1; -set enable_hashjoin = 0; -set enable_nestloop = 0; - -create temp table a (i integer); -create temp table b (x integer, y integer); - -select * from a left join b on i = x and i = y and x = i; - -rollback; - --- --- test handling of merge clauses using record_ops --- -begin; - -create type mycomptype as (id int, v bigint); - -create temp table tidv (idv mycomptype); -create index on tidv (idv); - -explain (costs off) -select a.idv, b.idv from tidv a, tidv b where a.idv = b.idv; - -set enable_mergejoin = 0; -set enable_hashjoin = 0; - -explain (costs off) -select a.idv, b.idv from tidv a, tidv b where a.idv = b.idv; - -rollback; - --- --- test NULL behavior of whole-row Vars, per bug #5025 --- -select t1.q2, count(t2.*) -from int8_tbl t1 left join int8_tbl t2 on (t1.q2 = t2.q1) -group by t1.q2 order by 1; - -select t1.q2, count(t2.*) -from int8_tbl t1 left join (select * from int8_tbl) t2 on (t1.q2 = t2.q1) -group by t1.q2 order by 1; - -select t1.q2, count(t2.*) -from int8_tbl t1 left join (select * from int8_tbl offset 0) t2 on (t1.q2 = t2.q1) -group by t1.q2 order by 1; - -select t1.q2, count(t2.*) -from int8_tbl t1 left join - (select q1, case when q2=1 then 1 else q2 end as q2 from int8_tbl) t2 - on (t1.q2 = t2.q1) -group by t1.q2 order by 1; - --- --- test incorrect failure to NULL pulled-up subexpressions --- -begin; - -create temp table a ( - code char not null, - constraint a_pk primary key (code) -); -create temp table b ( - a char not null, - num integer not null, - constraint b_pk primary key (a, num) -); -create temp table c ( - name char not null, - a char, - constraint c_pk primary key (name) -); - -insert into a (code) values ('p'); -insert into a (code) values ('q'); -insert into b (a, num) values ('p', 1); -insert into b (a, num) values ('p', 2); -insert into c (name, a) values ('A', 'p'); -insert into c (name, a) values ('B', 'q'); -insert into c (name, a) values ('C', null); - -select c.name, ss.code, ss.b_cnt, ss.const -from c left join - (select a.code, coalesce(b_grp.cnt, 0) as b_cnt, -1 as const - from a left join - (select count(1) as cnt, b.a from b group by b.a) as b_grp - on a.code = b_grp.a - ) as ss - on (c.a = ss.code) -order by c.name; - -rollback; - --- --- test incorrect handling of placeholders that only appear in targetlists, --- per bug #6154 --- -SELECT * FROM -( SELECT 1 as key1 ) sub1 -LEFT JOIN -( SELECT sub3.key3, sub4.value2, COALESCE(sub4.value2, 66) as value3 FROM - ( SELECT 1 as key3 ) sub3 - LEFT JOIN - ( SELECT sub5.key5, COALESCE(sub6.value1, 1) as value2 FROM - ( SELECT 1 as key5 ) sub5 - LEFT JOIN - ( SELECT 2 as key6, 42 as value1 ) sub6 - ON sub5.key5 = sub6.key6 - ) sub4 - ON sub4.key5 = sub3.key3 -) sub2 -ON sub1.key1 = sub2.key3; - --- test the path using join aliases, too -SELECT * FROM -( SELECT 1 as key1 ) sub1 -LEFT JOIN -( SELECT sub3.key3, value2, COALESCE(value2, 66) as value3 FROM - ( SELECT 1 as key3 ) sub3 - LEFT JOIN - ( SELECT sub5.key5, COALESCE(sub6.value1, 1) as value2 FROM - ( SELECT 1 as key5 ) sub5 - LEFT JOIN - ( SELECT 2 as key6, 42 as value1 ) sub6 - ON sub5.key5 = sub6.key6 - ) sub4 - ON sub4.key5 = sub3.key3 -) sub2 -ON sub1.key1 = sub2.key3; - --- --- test case where a PlaceHolderVar is used as a nestloop parameter --- - -EXPLAIN (COSTS OFF) -SELECT qq, unique1 - FROM - ( SELECT COALESCE(q1, 0) AS qq FROM int8_tbl a ) AS ss1 - FULL OUTER JOIN - ( SELECT COALESCE(q2, -1) AS qq FROM int8_tbl b ) AS ss2 - USING (qq) - INNER JOIN tenk1 c ON qq = unique2; - -SELECT qq, unique1 - FROM - ( SELECT COALESCE(q1, 0) AS qq FROM int8_tbl a ) AS ss1 - FULL OUTER JOIN - ( SELECT COALESCE(q2, -1) AS qq FROM int8_tbl b ) AS ss2 - USING (qq) - INNER JOIN tenk1 c ON qq = unique2; - --- --- nested nestloops can require nested PlaceHolderVars --- - -create temp table nt1 ( - id int primary key, - a1 boolean, - a2 boolean -); -create temp table nt2 ( - id int primary key, - nt1_id int, - b1 boolean, - b2 boolean, - foreign key (nt1_id) references nt1(id) -); -create temp table nt3 ( - id int primary key, - nt2_id int, - c1 boolean, - foreign key (nt2_id) references nt2(id) -); - -insert into nt1 values (1,true,true); -insert into nt1 values (2,true,false); -insert into nt1 values (3,false,false); -insert into nt2 values (1,1,true,true); -insert into nt2 values (2,2,true,false); -insert into nt2 values (3,3,false,false); -insert into nt3 values (1,1,true); -insert into nt3 values (2,2,false); -insert into nt3 values (3,3,true); - -explain (costs off) -select nt3.id -from nt3 as nt3 - left join - (select nt2.*, (nt2.b1 and ss1.a3) AS b3 - from nt2 as nt2 - left join - (select nt1.*, (nt1.id is not null) as a3 from nt1) as ss1 - on ss1.id = nt2.nt1_id - ) as ss2 - on ss2.id = nt3.nt2_id -where nt3.id = 1 and ss2.b3; - -select nt3.id -from nt3 as nt3 - left join - (select nt2.*, (nt2.b1 and ss1.a3) AS b3 - from nt2 as nt2 - left join - (select nt1.*, (nt1.id is not null) as a3 from nt1) as ss1 - on ss1.id = nt2.nt1_id - ) as ss2 - on ss2.id = nt3.nt2_id -where nt3.id = 1 and ss2.b3; - --- --- test case where a PlaceHolderVar is propagated into a subquery --- - -explain (costs off) -select * from - int8_tbl t1 left join - (select q1 as x, 42 as y from int8_tbl t2) ss - on t1.q2 = ss.x -where - 1 = (select 1 from int8_tbl t3 where ss.y is not null limit 1) -order by 1,2; - -select * from - int8_tbl t1 left join - (select q1 as x, 42 as y from int8_tbl t2) ss - on t1.q2 = ss.x -where - 1 = (select 1 from int8_tbl t3 where ss.y is not null limit 1) -order by 1,2; - --- --- variant where a PlaceHolderVar is needed at a join, but not above the join --- - -explain (costs off) -select * from - int4_tbl as i41, - lateral - (select 1 as x from - (select i41.f1 as lat, - i42.f1 as loc from - int8_tbl as i81, int4_tbl as i42) as ss1 - right join int4_tbl as i43 on (i43.f1 > 1) - where ss1.loc = ss1.lat) as ss2 -where i41.f1 > 0; - -select * from - int4_tbl as i41, - lateral - (select 1 as x from - (select i41.f1 as lat, - i42.f1 as loc from - int8_tbl as i81, int4_tbl as i42) as ss1 - right join int4_tbl as i43 on (i43.f1 > 1) - where ss1.loc = ss1.lat) as ss2 -where i41.f1 > 0; - --- --- test the corner cases FULL JOIN ON TRUE and FULL JOIN ON FALSE --- -select * from int4_tbl a full join int4_tbl b on true; -select * from int4_tbl a full join int4_tbl b on false; - --- --- test for ability to use a cartesian join when necessary --- - -create temp table q1 as select 1 as q1; -create temp table q2 as select 0 as q2; -analyze q1; -analyze q2; - -explain (costs off) -select * from - tenk1 join int4_tbl on f1 = twothousand, - q1, q2 -where q1 = thousand or q2 = thousand; - -explain (costs off) -select * from - tenk1 join int4_tbl on f1 = twothousand, - q1, q2 -where thousand = (q1 + q2); - --- --- test ability to generate a suitable plan for a star-schema query --- - -explain (costs off) -select * from - tenk1, int8_tbl a, int8_tbl b -where thousand = a.q1 and tenthous = b.q1 and a.q2 = 1 and b.q2 = 2; - --- --- test a corner case in which we shouldn't apply the star-schema optimization --- - -explain (costs off) -select t1.unique2, t1.stringu1, t2.unique1, t2.stringu2 from - tenk1 t1 - inner join int4_tbl i1 - left join (select v1.x2, v2.y1, 11 AS d1 - from (select 1,0 from onerow) v1(x1,x2) - left join (select 3,1 from onerow) v2(y1,y2) - on v1.x1 = v2.y2) subq1 - on (i1.f1 = subq1.x2) - on (t1.unique2 = subq1.d1) - left join tenk1 t2 - on (subq1.y1 = t2.unique1) -where t1.unique2 < 42 and t1.stringu1 > t2.stringu2; - -select t1.unique2, t1.stringu1, t2.unique1, t2.stringu2 from - tenk1 t1 - inner join int4_tbl i1 - left join (select v1.x2, v2.y1, 11 AS d1 - from (select 1,0 from onerow) v1(x1,x2) - left join (select 3,1 from onerow) v2(y1,y2) - on v1.x1 = v2.y2) subq1 - on (i1.f1 = subq1.x2) - on (t1.unique2 = subq1.d1) - left join tenk1 t2 - on (subq1.y1 = t2.unique1) -where t1.unique2 < 42 and t1.stringu1 > t2.stringu2; - --- variant that isn't quite a star-schema case - -select ss1.d1 from - tenk1 as t1 - inner join tenk1 as t2 - on t1.tenthous = t2.ten - inner join - int8_tbl as i8 - left join int4_tbl as i4 - inner join (select 64::information_schema.cardinal_number as d1 - from tenk1 t3, - lateral (select abs(t3.unique1) + random()) ss0(x) - where t3.fivethous < 0) as ss1 - on i4.f1 = ss1.d1 - on i8.q1 = i4.f1 - on t1.tenthous = ss1.d1 -where t1.unique1 < i4.f1; - --- this variant is foldable by the remove-useless-RESULT-RTEs code - -explain (costs off) -select t1.unique2, t1.stringu1, t2.unique1, t2.stringu2 from - tenk1 t1 - inner join int4_tbl i1 - left join (select v1.x2, v2.y1, 11 AS d1 - from (values(1,0)) v1(x1,x2) - left join (values(3,1)) v2(y1,y2) - on v1.x1 = v2.y2) subq1 - on (i1.f1 = subq1.x2) - on (t1.unique2 = subq1.d1) - left join tenk1 t2 - on (subq1.y1 = t2.unique1) -where t1.unique2 < 42 and t1.stringu1 > t2.stringu2; - -select t1.unique2, t1.stringu1, t2.unique1, t2.stringu2 from - tenk1 t1 - inner join int4_tbl i1 - left join (select v1.x2, v2.y1, 11 AS d1 - from (values(1,0)) v1(x1,x2) - left join (values(3,1)) v2(y1,y2) - on v1.x1 = v2.y2) subq1 - on (i1.f1 = subq1.x2) - on (t1.unique2 = subq1.d1) - left join tenk1 t2 - on (subq1.y1 = t2.unique1) -where t1.unique2 < 42 and t1.stringu1 > t2.stringu2; - --- Here's a variant that we can't fold too aggressively, though, --- or we end up with noplace to evaluate the lateral PHV -explain (verbose, costs off) -select * from - (select 1 as x) ss1 left join (select 2 as y) ss2 on (true), - lateral (select ss2.y as z limit 1) ss3; -select * from - (select 1 as x) ss1 left join (select 2 as y) ss2 on (true), - lateral (select ss2.y as z limit 1) ss3; - --- Test proper handling of appendrel PHVs during useless-RTE removal -explain (costs off) -select * from - (select 0 as z) as t1 - left join - (select true as a) as t2 - on true, - lateral (select true as b - union all - select a as b) as t3 -where b; - -select * from - (select 0 as z) as t1 - left join - (select true as a) as t2 - on true, - lateral (select true as b - union all - select a as b) as t3 -where b; - --- --- test inlining of immutable functions --- -create function f_immutable_int4(i integer) returns integer as -$$ begin return i; end; $$ language plpgsql immutable; - --- check optimization of function scan with join -explain (costs off) -select unique1 from tenk1, (select * from f_immutable_int4(1) x) x -where x = unique1; - -explain (verbose, costs off) -select unique1, x.* -from tenk1, (select *, random() from f_immutable_int4(1) x) x -where x = unique1; - -explain (costs off) -select unique1 from tenk1, f_immutable_int4(1) x where x = unique1; - -explain (costs off) -select unique1 from tenk1, lateral f_immutable_int4(1) x where x = unique1; - -explain (costs off) -select unique1 from tenk1, lateral f_immutable_int4(1) x where x in (select 17); - -explain (costs off) -select unique1, x from tenk1 join f_immutable_int4(1) x on unique1 = x; - -explain (costs off) -select unique1, x from tenk1 left join f_immutable_int4(1) x on unique1 = x; - -explain (costs off) -select unique1, x from tenk1 right join f_immutable_int4(1) x on unique1 = x; - -explain (costs off) -select unique1, x from tenk1 full join f_immutable_int4(1) x on unique1 = x; - --- check that pullup of a const function allows further const-folding -explain (costs off) -select unique1 from tenk1, f_immutable_int4(1) x where x = 42; - --- test inlining of immutable functions with PlaceHolderVars -explain (costs off) -select nt3.id -from nt3 as nt3 - left join - (select nt2.*, (nt2.b1 or i4 = 42) AS b3 - from nt2 as nt2 - left join - f_immutable_int4(0) i4 - on i4 = nt2.nt1_id - ) as ss2 - on ss2.id = nt3.nt2_id -where nt3.id = 1 and ss2.b3; - -drop function f_immutable_int4(int); - --- test inlining when function returns composite - -create function mki8(bigint, bigint) returns int8_tbl as -$$select row($1,$2)::int8_tbl$$ language sql; - -create function mki4(int) returns int4_tbl as -$$select row($1)::int4_tbl$$ language sql; - -explain (verbose, costs off) -select * from mki8(1,2); -select * from mki8(1,2); - -explain (verbose, costs off) -select * from mki4(42); -select * from mki4(42); - -drop function mki8(bigint, bigint); -drop function mki4(int); - --- --- test extraction of restriction OR clauses from join OR clause --- (we used to only do this for indexable clauses) --- - -explain (costs off) -select * from tenk1 a join tenk1 b on - (a.unique1 = 1 and b.unique1 = 2) or (a.unique2 = 3 and b.hundred = 4); -explain (costs off) -select * from tenk1 a join tenk1 b on - (a.unique1 = 1 and b.unique1 = 2) or (a.unique2 = 3 and b.ten = 4); -explain (costs off) -select * from tenk1 a join tenk1 b on - (a.unique1 = 1 and b.unique1 = 2) or - ((a.unique2 = 3 or a.unique2 = 7) and b.hundred = 4); - --- --- test placement of movable quals in a parameterized join tree --- - -explain (costs off) -select * from tenk1 t1 left join - (tenk1 t2 join tenk1 t3 on t2.thousand = t3.unique2) - on t1.hundred = t2.hundred and t1.ten = t3.ten -where t1.unique1 = 1; - -explain (costs off) -select * from tenk1 t1 left join - (tenk1 t2 join tenk1 t3 on t2.thousand = t3.unique2) - on t1.hundred = t2.hundred and t1.ten + t2.ten = t3.ten -where t1.unique1 = 1; - -explain (costs off) -select count(*) from - tenk1 a join tenk1 b on a.unique1 = b.unique2 - left join tenk1 c on a.unique2 = b.unique1 and c.thousand = a.thousand - join int4_tbl on b.thousand = f1; - -select count(*) from - tenk1 a join tenk1 b on a.unique1 = b.unique2 - left join tenk1 c on a.unique2 = b.unique1 and c.thousand = a.thousand - join int4_tbl on b.thousand = f1; - -explain (costs off) -select b.unique1 from - tenk1 a join tenk1 b on a.unique1 = b.unique2 - left join tenk1 c on b.unique1 = 42 and c.thousand = a.thousand - join int4_tbl i1 on b.thousand = f1 - right join int4_tbl i2 on i2.f1 = b.tenthous - order by 1; - -select b.unique1 from - tenk1 a join tenk1 b on a.unique1 = b.unique2 - left join tenk1 c on b.unique1 = 42 and c.thousand = a.thousand - join int4_tbl i1 on b.thousand = f1 - right join int4_tbl i2 on i2.f1 = b.tenthous - order by 1; - -explain (costs off) -select * from -( - select unique1, q1, coalesce(unique1, -1) + q1 as fault - from int8_tbl left join tenk1 on (q2 = unique2) -) ss -where fault = 122 -order by fault; - -select * from -( - select unique1, q1, coalesce(unique1, -1) + q1 as fault - from int8_tbl left join tenk1 on (q2 = unique2) -) ss -where fault = 122 -order by fault; - -explain (costs off) -select * from -(values (1, array[10,20]), (2, array[20,30])) as v1(v1x,v1ys) -left join (values (1, 10), (2, 20)) as v2(v2x,v2y) on v2x = v1x -left join unnest(v1ys) as u1(u1y) on u1y = v2y; - -select * from -(values (1, array[10,20]), (2, array[20,30])) as v1(v1x,v1ys) -left join (values (1, 10), (2, 20)) as v2(v2x,v2y) on v2x = v1x -left join unnest(v1ys) as u1(u1y) on u1y = v2y; - --- --- test handling of potential equivalence clauses above outer joins --- - -explain (costs off) -select q1, unique2, thousand, hundred - from int8_tbl a left join tenk1 b on q1 = unique2 - where coalesce(thousand,123) = q1 and q1 = coalesce(hundred,123); - -select q1, unique2, thousand, hundred - from int8_tbl a left join tenk1 b on q1 = unique2 - where coalesce(thousand,123) = q1 and q1 = coalesce(hundred,123); - -explain (costs off) -select f1, unique2, case when unique2 is null then f1 else 0 end - from int4_tbl a left join tenk1 b on f1 = unique2 - where (case when unique2 is null then f1 else 0 end) = 0; - -select f1, unique2, case when unique2 is null then f1 else 0 end - from int4_tbl a left join tenk1 b on f1 = unique2 - where (case when unique2 is null then f1 else 0 end) = 0; - --- --- another case with equivalence clauses above outer joins (bug #8591) --- - -explain (costs off) -select a.unique1, b.unique1, c.unique1, coalesce(b.twothousand, a.twothousand) - from tenk1 a left join tenk1 b on b.thousand = a.unique1 left join tenk1 c on c.unique2 = coalesce(b.twothousand, a.twothousand) - where a.unique2 < 10 and coalesce(b.twothousand, a.twothousand) = 44; - -select a.unique1, b.unique1, c.unique1, coalesce(b.twothousand, a.twothousand) - from tenk1 a left join tenk1 b on b.thousand = a.unique1 left join tenk1 c on c.unique2 = coalesce(b.twothousand, a.twothousand) - where a.unique2 < 10 and coalesce(b.twothousand, a.twothousand) = 44; - --- --- check handling of join aliases when flattening multiple levels of subquery --- - -explain (verbose, costs off) -select foo1.join_key as foo1_id, foo3.join_key AS foo3_id, bug_field from - (values (0),(1)) foo1(join_key) -left join - (select join_key, bug_field from - (select ss1.join_key, ss1.bug_field from - (select f1 as join_key, 666 as bug_field from int4_tbl i1) ss1 - ) foo2 - left join - (select unique2 as join_key from tenk1 i2) ss2 - using (join_key) - ) foo3 -using (join_key); - -select foo1.join_key as foo1_id, foo3.join_key AS foo3_id, bug_field from - (values (0),(1)) foo1(join_key) -left join - (select join_key, bug_field from - (select ss1.join_key, ss1.bug_field from - (select f1 as join_key, 666 as bug_field from int4_tbl i1) ss1 - ) foo2 - left join - (select unique2 as join_key from tenk1 i2) ss2 - using (join_key) - ) foo3 -using (join_key); - --- --- test successful handling of nested outer joins with degenerate join quals --- - -explain (verbose, costs off) -select t1.* from - text_tbl t1 - left join (select *, '***'::text as d1 from int8_tbl i8b1) b1 - left join int8_tbl i8 - left join (select *, null::int as d2 from int8_tbl i8b2) b2 - on (i8.q1 = b2.q1) - on (b2.d2 = b1.q2) - on (t1.f1 = b1.d1) - left join int4_tbl i4 - on (i8.q2 = i4.f1); - -select t1.* from - text_tbl t1 - left join (select *, '***'::text as d1 from int8_tbl i8b1) b1 - left join int8_tbl i8 - left join (select *, null::int as d2 from int8_tbl i8b2) b2 - on (i8.q1 = b2.q1) - on (b2.d2 = b1.q2) - on (t1.f1 = b1.d1) - left join int4_tbl i4 - on (i8.q2 = i4.f1); - -explain (verbose, costs off) -select t1.* from - text_tbl t1 - left join (select *, '***'::text as d1 from int8_tbl i8b1) b1 - left join int8_tbl i8 - left join (select *, null::int as d2 from int8_tbl i8b2, int4_tbl i4b2) b2 - on (i8.q1 = b2.q1) - on (b2.d2 = b1.q2) - on (t1.f1 = b1.d1) - left join int4_tbl i4 - on (i8.q2 = i4.f1); - -select t1.* from - text_tbl t1 - left join (select *, '***'::text as d1 from int8_tbl i8b1) b1 - left join int8_tbl i8 - left join (select *, null::int as d2 from int8_tbl i8b2, int4_tbl i4b2) b2 - on (i8.q1 = b2.q1) - on (b2.d2 = b1.q2) - on (t1.f1 = b1.d1) - left join int4_tbl i4 - on (i8.q2 = i4.f1); - -explain (verbose, costs off) -select t1.* from - text_tbl t1 - left join (select *, '***'::text as d1 from int8_tbl i8b1) b1 - left join int8_tbl i8 - left join (select *, null::int as d2 from int8_tbl i8b2, int4_tbl i4b2 - where q1 = f1) b2 - on (i8.q1 = b2.q1) - on (b2.d2 = b1.q2) - on (t1.f1 = b1.d1) - left join int4_tbl i4 - on (i8.q2 = i4.f1); - -select t1.* from - text_tbl t1 - left join (select *, '***'::text as d1 from int8_tbl i8b1) b1 - left join int8_tbl i8 - left join (select *, null::int as d2 from int8_tbl i8b2, int4_tbl i4b2 - where q1 = f1) b2 - on (i8.q1 = b2.q1) - on (b2.d2 = b1.q2) - on (t1.f1 = b1.d1) - left join int4_tbl i4 - on (i8.q2 = i4.f1); - -explain (verbose, costs off) -select * from - text_tbl t1 - inner join int8_tbl i8 - on i8.q2 = 456 - right join text_tbl t2 - on t1.f1 = 'doh!' - left join int4_tbl i4 - on i8.q1 = i4.f1; - -select * from - text_tbl t1 - inner join int8_tbl i8 - on i8.q2 = 456 - right join text_tbl t2 - on t1.f1 = 'doh!' - left join int4_tbl i4 - on i8.q1 = i4.f1; - --- --- test for appropriate join order in the presence of lateral references --- - -explain (verbose, costs off) -select * from - text_tbl t1 - left join int8_tbl i8 - on i8.q2 = 123, - lateral (select i8.q1, t2.f1 from text_tbl t2 limit 1) as ss -where t1.f1 = ss.f1; - -select * from - text_tbl t1 - left join int8_tbl i8 - on i8.q2 = 123, - lateral (select i8.q1, t2.f1 from text_tbl t2 limit 1) as ss -where t1.f1 = ss.f1; - -explain (verbose, costs off) -select * from - text_tbl t1 - left join int8_tbl i8 - on i8.q2 = 123, - lateral (select i8.q1, t2.f1 from text_tbl t2 limit 1) as ss1, - lateral (select ss1.* from text_tbl t3 limit 1) as ss2 -where t1.f1 = ss2.f1; - -select * from - text_tbl t1 - left join int8_tbl i8 - on i8.q2 = 123, - lateral (select i8.q1, t2.f1 from text_tbl t2 limit 1) as ss1, - lateral (select ss1.* from text_tbl t3 limit 1) as ss2 -where t1.f1 = ss2.f1; - -explain (verbose, costs off) -select 1 from - text_tbl as tt1 - inner join text_tbl as tt2 on (tt1.f1 = 'foo') - left join text_tbl as tt3 on (tt3.f1 = 'foo') - left join text_tbl as tt4 on (tt3.f1 = tt4.f1), - lateral (select tt4.f1 as c0 from text_tbl as tt5 limit 1) as ss1 -where tt1.f1 = ss1.c0; - -select 1 from - text_tbl as tt1 - inner join text_tbl as tt2 on (tt1.f1 = 'foo') - left join text_tbl as tt3 on (tt3.f1 = 'foo') - left join text_tbl as tt4 on (tt3.f1 = tt4.f1), - lateral (select tt4.f1 as c0 from text_tbl as tt5 limit 1) as ss1 -where tt1.f1 = ss1.c0; - --- --- check a case in which a PlaceHolderVar forces join order --- - -explain (verbose, costs off) -select ss2.* from - int4_tbl i41 - left join int8_tbl i8 - join (select i42.f1 as c1, i43.f1 as c2, 42 as c3 - from int4_tbl i42, int4_tbl i43) ss1 - on i8.q1 = ss1.c2 - on i41.f1 = ss1.c1, - lateral (select i41.*, i8.*, ss1.* from text_tbl limit 1) ss2 -where ss1.c2 = 0; - -select ss2.* from - int4_tbl i41 - left join int8_tbl i8 - join (select i42.f1 as c1, i43.f1 as c2, 42 as c3 - from int4_tbl i42, int4_tbl i43) ss1 - on i8.q1 = ss1.c2 - on i41.f1 = ss1.c1, - lateral (select i41.*, i8.*, ss1.* from text_tbl limit 1) ss2 -where ss1.c2 = 0; - --- --- test successful handling of full join underneath left join (bug #14105) --- - -explain (costs off) -select * from - (select 1 as id) as xx - left join - (tenk1 as a1 full join (select 1 as id) as yy on (a1.unique1 = yy.id)) - on (xx.id = coalesce(yy.id)); - -select * from - (select 1 as id) as xx - left join - (tenk1 as a1 full join (select 1 as id) as yy on (a1.unique1 = yy.id)) - on (xx.id = coalesce(yy.id)); - --- --- test ability to push constants through outer join clauses --- - -explain (costs off) - select * from int4_tbl a left join tenk1 b on f1 = unique2 where f1 = 0; - -explain (costs off) - select * from tenk1 a full join tenk1 b using(unique2) where unique2 = 42; - --- --- test that quals attached to an outer join have correct semantics, --- specifically that they don't re-use expressions computed below the join; --- we force a mergejoin so that coalesce(b.q1, 1) appears as a join input --- - -set enable_hashjoin to off; -set enable_nestloop to off; - -explain (verbose, costs off) - select a.q2, b.q1 - from int8_tbl a left join int8_tbl b on a.q2 = coalesce(b.q1, 1) - where coalesce(b.q1, 1) > 0; -select a.q2, b.q1 - from int8_tbl a left join int8_tbl b on a.q2 = coalesce(b.q1, 1) - where coalesce(b.q1, 1) > 0; - -reset enable_hashjoin; -reset enable_nestloop; - --- --- test join removal --- - -begin; - -CREATE TEMP TABLE a (id int PRIMARY KEY, b_id int); -CREATE TEMP TABLE b (id int PRIMARY KEY, c_id int); -CREATE TEMP TABLE c (id int PRIMARY KEY); -CREATE TEMP TABLE d (a int, b int); -INSERT INTO a VALUES (0, 0), (1, NULL); -INSERT INTO b VALUES (0, 0), (1, NULL); -INSERT INTO c VALUES (0), (1); -INSERT INTO d VALUES (1,3), (2,2), (3,1); - --- all three cases should be optimizable into a simple seqscan -explain (costs off) SELECT a.* FROM a LEFT JOIN b ON a.b_id = b.id; -explain (costs off) SELECT b.* FROM b LEFT JOIN c ON b.c_id = c.id; -explain (costs off) - SELECT a.* FROM a LEFT JOIN (b left join c on b.c_id = c.id) - ON (a.b_id = b.id); - --- check optimization of outer join within another special join -explain (costs off) -select id from a where id in ( - select b.id from b left join c on b.id = c.id -); - --- check that join removal works for a left join when joining a subquery --- that is guaranteed to be unique by its GROUP BY clause -explain (costs off) -select d.* from d left join (select * from b group by b.id, b.c_id) s - on d.a = s.id and d.b = s.c_id; - --- similarly, but keying off a DISTINCT clause -explain (costs off) -select d.* from d left join (select distinct * from b) s - on d.a = s.id and d.b = s.c_id; - --- join removal is not possible when the GROUP BY contains a column that is --- not in the join condition. (Note: as of 9.6, we notice that b.id is a --- primary key and so drop b.c_id from the GROUP BY of the resulting plan; --- but this happens too late for join removal in the outer plan level.) -explain (costs off) -select d.* from d left join (select * from b group by b.id, b.c_id) s - on d.a = s.id; - --- similarly, but keying off a DISTINCT clause -explain (costs off) -select d.* from d left join (select distinct * from b) s - on d.a = s.id; - --- check join removal works when uniqueness of the join condition is enforced --- by a UNION -explain (costs off) -select d.* from d left join (select id from a union select id from b) s - on d.a = s.id; - --- check join removal with a cross-type comparison operator -explain (costs off) -select i8.* from int8_tbl i8 left join (select f1 from int4_tbl group by f1) i4 - on i8.q1 = i4.f1; - --- check join removal with lateral references -explain (costs off) -select 1 from (select a.id FROM a left join b on a.b_id = b.id) q, - lateral generate_series(1, q.id) gs(i) where q.id = gs.i; - -rollback; - -create temp table parent (k int primary key, pd int); -create temp table child (k int unique, cd int); -insert into parent values (1, 10), (2, 20), (3, 30); -insert into child values (1, 100), (4, 400); - --- this case is optimizable -select p.* from parent p left join child c on (p.k = c.k); -explain (costs off) - select p.* from parent p left join child c on (p.k = c.k); - --- this case is not -select p.*, linked from parent p - left join (select c.*, true as linked from child c) as ss - on (p.k = ss.k); -explain (costs off) - select p.*, linked from parent p - left join (select c.*, true as linked from child c) as ss - on (p.k = ss.k); - --- check for a 9.0rc1 bug: join removal breaks pseudoconstant qual handling -select p.* from - parent p left join child c on (p.k = c.k) - where p.k = 1 and p.k = 2; -explain (costs off) -select p.* from - parent p left join child c on (p.k = c.k) - where p.k = 1 and p.k = 2; - -select p.* from - (parent p left join child c on (p.k = c.k)) join parent x on p.k = x.k - where p.k = 1 and p.k = 2; -explain (costs off) -select p.* from - (parent p left join child c on (p.k = c.k)) join parent x on p.k = x.k - where p.k = 1 and p.k = 2; - --- bug 5255: this is not optimizable by join removal -begin; - -CREATE TEMP TABLE a (id int PRIMARY KEY); -CREATE TEMP TABLE b (id int PRIMARY KEY, a_id int); -INSERT INTO a VALUES (0), (1); -INSERT INTO b VALUES (0, 0), (1, NULL); - -SELECT * FROM b LEFT JOIN a ON (b.a_id = a.id) WHERE (a.id IS NULL OR a.id > 0); -SELECT b.* FROM b LEFT JOIN a ON (b.a_id = a.id) WHERE (a.id IS NULL OR a.id > 0); - -rollback; - --- another join removal bug: this is not optimizable, either -begin; - -create temp table innertab (id int8 primary key, dat1 int8); -insert into innertab values(123, 42); - -SELECT * FROM - (SELECT 1 AS x) ss1 - LEFT JOIN - (SELECT q1, q2, COALESCE(dat1, q1) AS y - FROM int8_tbl LEFT JOIN innertab ON q2 = id) ss2 - ON true; - -rollback; - --- another join removal bug: we must clean up correctly when removing a PHV -begin; - -create temp table uniquetbl (f1 text unique); - -explain (costs off) -select t1.* from - uniquetbl as t1 - left join (select *, '***'::text as d1 from uniquetbl) t2 - on t1.f1 = t2.f1 - left join uniquetbl t3 - on t2.d1 = t3.f1; - -explain (costs off) -select t0.* -from - text_tbl t0 - left join - (select case t1.ten when 0 then 'doh!'::text else null::text end as case1, - t1.stringu2 - from tenk1 t1 - join int4_tbl i4 ON i4.f1 = t1.unique2 - left join uniquetbl u1 ON u1.f1 = t1.string4) ss - on t0.f1 = ss.case1 -where ss.stringu2 !~* ss.case1; - -select t0.* -from - text_tbl t0 - left join - (select case t1.ten when 0 then 'doh!'::text else null::text end as case1, - t1.stringu2 - from tenk1 t1 - join int4_tbl i4 ON i4.f1 = t1.unique2 - left join uniquetbl u1 ON u1.f1 = t1.string4) ss - on t0.f1 = ss.case1 -where ss.stringu2 !~* ss.case1; - -rollback; - --- test case to expose miscomputation of required relid set for a PHV -explain (verbose, costs off) -select i8.*, ss.v, t.unique2 - from int8_tbl i8 - left join int4_tbl i4 on i4.f1 = 1 - left join lateral (select i4.f1 + 1 as v) as ss on true - left join tenk1 t on t.unique2 = ss.v -where q2 = 456; - -select i8.*, ss.v, t.unique2 - from int8_tbl i8 - left join int4_tbl i4 on i4.f1 = 1 - left join lateral (select i4.f1 + 1 as v) as ss on true - left join tenk1 t on t.unique2 = ss.v -where q2 = 456; - --- and check a related issue where we miscompute required relids for --- a PHV that's been translated to a child rel -create temp table parttbl (a integer primary key) partition by range (a); -create temp table parttbl1 partition of parttbl for values from (1) to (100); -insert into parttbl values (11), (12); -explain (costs off) -select * from - (select *, 12 as phv from parttbl) as ss - right join int4_tbl on true -where ss.a = ss.phv and f1 = 0; - -select * from - (select *, 12 as phv from parttbl) as ss - right join int4_tbl on true -where ss.a = ss.phv and f1 = 0; - --- bug #8444: we've historically allowed duplicate aliases within aliased JOINs - -select * from - int8_tbl x join (int4_tbl x cross join int4_tbl y) j on q1 = f1; -- error -select * from - int8_tbl x join (int4_tbl x cross join int4_tbl y) j on q1 = y.f1; -- error -select * from - int8_tbl x join (int4_tbl x cross join int4_tbl y(ff)) j on q1 = f1; -- ok - --- --- Test hints given on incorrect column references are useful --- - -select t1.uunique1 from - tenk1 t1 join tenk2 t2 on t1.two = t2.two; -- error, prefer "t1" suggestion -select t2.uunique1 from - tenk1 t1 join tenk2 t2 on t1.two = t2.two; -- error, prefer "t2" suggestion -select uunique1 from - tenk1 t1 join tenk2 t2 on t1.two = t2.two; -- error, suggest both at once - --- --- Take care to reference the correct RTE --- - -select atts.relid::regclass, s.* from pg_stats s join - pg_attribute a on s.attname = a.attname and s.tablename = - a.attrelid::regclass::text join (select unnest(indkey) attnum, - indexrelid from pg_index i) atts on atts.attnum = a.attnum where - schemaname != 'pg_catalog'; - --- --- Test LATERAL --- - -select unique2, x.* -from tenk1 a, lateral (select * from int4_tbl b where f1 = a.unique1) x; -explain (costs off) - select unique2, x.* - from tenk1 a, lateral (select * from int4_tbl b where f1 = a.unique1) x; -select unique2, x.* -from int4_tbl x, lateral (select unique2 from tenk1 where f1 = unique1) ss; -explain (costs off) - select unique2, x.* - from int4_tbl x, lateral (select unique2 from tenk1 where f1 = unique1) ss; -explain (costs off) - select unique2, x.* - from int4_tbl x cross join lateral (select unique2 from tenk1 where f1 = unique1) ss; -select unique2, x.* -from int4_tbl x left join lateral (select unique1, unique2 from tenk1 where f1 = unique1) ss on true; -explain (costs off) - select unique2, x.* - from int4_tbl x left join lateral (select unique1, unique2 from tenk1 where f1 = unique1) ss on true; - --- check scoping of lateral versus parent references --- the first of these should return int8_tbl.q2, the second int8_tbl.q1 -select *, (select r from (select q1 as q2) x, (select q2 as r) y) from int8_tbl; -select *, (select r from (select q1 as q2) x, lateral (select q2 as r) y) from int8_tbl; - --- lateral with function in FROM -select count(*) from tenk1 a, lateral generate_series(1,two) g; -explain (costs off) - select count(*) from tenk1 a, lateral generate_series(1,two) g; -explain (costs off) - select count(*) from tenk1 a cross join lateral generate_series(1,two) g; --- don't need the explicit LATERAL keyword for functions -explain (costs off) - select count(*) from tenk1 a, generate_series(1,two) g; - --- lateral with UNION ALL subselect -explain (costs off) - select * from generate_series(100,200) g, - lateral (select * from int8_tbl a where g = q1 union all - select * from int8_tbl b where g = q2) ss; -select * from generate_series(100,200) g, - lateral (select * from int8_tbl a where g = q1 union all - select * from int8_tbl b where g = q2) ss; - --- lateral with VALUES -explain (costs off) - select count(*) from tenk1 a, - tenk1 b join lateral (values(a.unique1)) ss(x) on b.unique2 = ss.x; -select count(*) from tenk1 a, - tenk1 b join lateral (values(a.unique1)) ss(x) on b.unique2 = ss.x; - --- lateral with VALUES, no flattening possible -explain (costs off) - select count(*) from tenk1 a, - tenk1 b join lateral (values(a.unique1),(-1)) ss(x) on b.unique2 = ss.x; -select count(*) from tenk1 a, - tenk1 b join lateral (values(a.unique1),(-1)) ss(x) on b.unique2 = ss.x; - --- lateral injecting a strange outer join condition -explain (costs off) - select * from int8_tbl a, - int8_tbl x left join lateral (select a.q1 from int4_tbl y) ss(z) - on x.q2 = ss.z - order by a.q1, a.q2, x.q1, x.q2, ss.z; -select * from int8_tbl a, - int8_tbl x left join lateral (select a.q1 from int4_tbl y) ss(z) - on x.q2 = ss.z - order by a.q1, a.q2, x.q1, x.q2, ss.z; - --- lateral reference to a join alias variable -select * from (select f1/2 as x from int4_tbl) ss1 join int4_tbl i4 on x = f1, - lateral (select x) ss2(y); -select * from (select f1 as x from int4_tbl) ss1 join int4_tbl i4 on x = f1, - lateral (values(x)) ss2(y); -select * from ((select f1/2 as x from int4_tbl) ss1 join int4_tbl i4 on x = f1) j, - lateral (select x) ss2(y); - --- lateral references requiring pullup -select * from (values(1)) x(lb), - lateral generate_series(lb,4) x4; -select * from (select f1/1000000000 from int4_tbl) x(lb), - lateral generate_series(lb,4) x4; -select * from (values(1)) x(lb), - lateral (values(lb)) y(lbcopy); -select * from (values(1)) x(lb), - lateral (select lb from int4_tbl) y(lbcopy); -select * from - int8_tbl x left join (select q1,coalesce(q2,0) q2 from int8_tbl) y on x.q2 = y.q1, - lateral (values(x.q1,y.q1,y.q2)) v(xq1,yq1,yq2); -select * from - int8_tbl x left join (select q1,coalesce(q2,0) q2 from int8_tbl) y on x.q2 = y.q1, - lateral (select x.q1,y.q1,y.q2) v(xq1,yq1,yq2); -select x.* from - int8_tbl x left join (select q1,coalesce(q2,0) q2 from int8_tbl) y on x.q2 = y.q1, - lateral (select x.q1,y.q1,y.q2) v(xq1,yq1,yq2); -select v.* from - (int8_tbl x left join (select q1,coalesce(q2,0) q2 from int8_tbl) y on x.q2 = y.q1) - left join int4_tbl z on z.f1 = x.q2, - lateral (select x.q1,y.q1 union all select x.q2,y.q2) v(vx,vy); -select v.* from - (int8_tbl x left join (select q1,(select coalesce(q2,0)) q2 from int8_tbl) y on x.q2 = y.q1) - left join int4_tbl z on z.f1 = x.q2, - lateral (select x.q1,y.q1 union all select x.q2,y.q2) v(vx,vy); -select v.* from - (int8_tbl x left join (select q1,(select coalesce(q2,0)) q2 from int8_tbl) y on x.q2 = y.q1) - left join int4_tbl z on z.f1 = x.q2, - lateral (select x.q1,y.q1 from onerow union all select x.q2,y.q2 from onerow) v(vx,vy); - -explain (verbose, costs off) -select * from - int8_tbl a left join - lateral (select *, a.q2 as x from int8_tbl b) ss on a.q2 = ss.q1; -select * from - int8_tbl a left join - lateral (select *, a.q2 as x from int8_tbl b) ss on a.q2 = ss.q1; -explain (verbose, costs off) -select * from - int8_tbl a left join - lateral (select *, coalesce(a.q2, 42) as x from int8_tbl b) ss on a.q2 = ss.q1; -select * from - int8_tbl a left join - lateral (select *, coalesce(a.q2, 42) as x from int8_tbl b) ss on a.q2 = ss.q1; - --- lateral can result in join conditions appearing below their --- real semantic level -explain (verbose, costs off) -select * from int4_tbl i left join - lateral (select * from int2_tbl j where i.f1 = j.f1) k on true; -select * from int4_tbl i left join - lateral (select * from int2_tbl j where i.f1 = j.f1) k on true; -explain (verbose, costs off) -select * from int4_tbl i left join - lateral (select coalesce(i) from int2_tbl j where i.f1 = j.f1) k on true; -select * from int4_tbl i left join - lateral (select coalesce(i) from int2_tbl j where i.f1 = j.f1) k on true; -explain (verbose, costs off) -select * from int4_tbl a, - lateral ( - select * from int4_tbl b left join int8_tbl c on (b.f1 = q1 and a.f1 = q2) - ) ss; -select * from int4_tbl a, - lateral ( - select * from int4_tbl b left join int8_tbl c on (b.f1 = q1 and a.f1 = q2) - ) ss; - --- lateral reference in a PlaceHolderVar evaluated at join level -explain (verbose, costs off) -select * from - int8_tbl a left join lateral - (select b.q1 as bq1, c.q1 as cq1, least(a.q1,b.q1,c.q1) from - int8_tbl b cross join int8_tbl c) ss - on a.q2 = ss.bq1; -select * from - int8_tbl a left join lateral - (select b.q1 as bq1, c.q1 as cq1, least(a.q1,b.q1,c.q1) from - int8_tbl b cross join int8_tbl c) ss - on a.q2 = ss.bq1; - --- case requiring nested PlaceHolderVars -explain (verbose, costs off) -select * from - int8_tbl c left join ( - int8_tbl a left join (select q1, coalesce(q2,42) as x from int8_tbl b) ss1 - on a.q2 = ss1.q1 - cross join - lateral (select q1, coalesce(ss1.x,q2) as y from int8_tbl d) ss2 - ) on c.q2 = ss2.q1, - lateral (select ss2.y offset 0) ss3; - --- case that breaks the old ph_may_need optimization -explain (verbose, costs off) -select c.*,a.*,ss1.q1,ss2.q1,ss3.* from - int8_tbl c left join ( - int8_tbl a left join - (select q1, coalesce(q2,f1) as x from int8_tbl b, int4_tbl b2 - where q1 < f1) ss1 - on a.q2 = ss1.q1 - cross join - lateral (select q1, coalesce(ss1.x,q2) as y from int8_tbl d) ss2 - ) on c.q2 = ss2.q1, - lateral (select * from int4_tbl i where ss2.y > f1) ss3; - --- check processing of postponed quals (bug #9041) -explain (verbose, costs off) -select * from - (select 1 as x offset 0) x cross join (select 2 as y offset 0) y - left join lateral ( - select * from (select 3 as z offset 0) z where z.z = x.x - ) zz on zz.z = y.y; - --- check dummy rels with lateral references (bug #15694) -explain (verbose, costs off) -select * from int8_tbl i8 left join lateral - (select *, i8.q2 from int4_tbl where false) ss on true; -explain (verbose, costs off) -select * from int8_tbl i8 left join lateral - (select *, i8.q2 from int4_tbl i1, int4_tbl i2 where false) ss on true; - --- check handling of nested appendrels inside LATERAL -select * from - ((select 2 as v) union all (select 3 as v)) as q1 - cross join lateral - ((select * from - ((select 4 as v) union all (select 5 as v)) as q3) - union all - (select q1.v) - ) as q2; - --- check the number of columns specified -SELECT * FROM (int8_tbl i cross join int4_tbl j) ss(a,b,c,d); - --- check we don't try to do a unique-ified semijoin with LATERAL -explain (verbose, costs off) -select * from - (values (0,9998), (1,1000)) v(id,x), - lateral (select f1 from int4_tbl - where f1 = any (select unique1 from tenk1 - where unique2 = v.x offset 0)) ss; -select * from - (values (0,9998), (1,1000)) v(id,x), - lateral (select f1 from int4_tbl - where f1 = any (select unique1 from tenk1 - where unique2 = v.x offset 0)) ss; - --- check proper extParam/allParam handling (this isn't exactly a LATERAL issue, --- but we can make the test case much more compact with LATERAL) -explain (verbose, costs off) -select * from (values (0), (1)) v(id), -lateral (select * from int8_tbl t1, - lateral (select * from - (select * from int8_tbl t2 - where q1 = any (select q2 from int8_tbl t3 - where q2 = (select greatest(t1.q1,t2.q2)) - and (select v.id=0)) offset 0) ss2) ss - where t1.q1 = ss.q2) ss0; - -select * from (values (0), (1)) v(id), -lateral (select * from int8_tbl t1, - lateral (select * from - (select * from int8_tbl t2 - where q1 = any (select q2 from int8_tbl t3 - where q2 = (select greatest(t1.q1,t2.q2)) - and (select v.id=0)) offset 0) ss2) ss - where t1.q1 = ss.q2) ss0; - --- test some error cases where LATERAL should have been used but wasn't -select f1,g from int4_tbl a, (select f1 as g) ss; -select f1,g from int4_tbl a, (select a.f1 as g) ss; -select f1,g from int4_tbl a cross join (select f1 as g) ss; -select f1,g from int4_tbl a cross join (select a.f1 as g) ss; --- SQL:2008 says the left table is in scope but illegal to access here -select f1,g from int4_tbl a right join lateral generate_series(0, a.f1) g on true; -select f1,g from int4_tbl a full join lateral generate_series(0, a.f1) g on true; --- check we complain about ambiguous table references -select * from - int8_tbl x cross join (int4_tbl x cross join lateral (select x.f1) ss); --- LATERAL can be used to put an aggregate into the FROM clause of its query -select 1 from tenk1 a, lateral (select max(a.unique1) from int4_tbl b) ss; - --- check behavior of LATERAL in UPDATE/DELETE - -create temp table xx1 as select f1 as x1, -f1 as x2 from int4_tbl; - --- error, can't do this: -update xx1 set x2 = f1 from (select * from int4_tbl where f1 = x1) ss; -update xx1 set x2 = f1 from (select * from int4_tbl where f1 = xx1.x1) ss; --- can't do it even with LATERAL: -update xx1 set x2 = f1 from lateral (select * from int4_tbl where f1 = x1) ss; --- we might in future allow something like this, but for now it's an error: -update xx1 set x2 = f1 from xx1, lateral (select * from int4_tbl where f1 = x1) ss; - --- also errors: -delete from xx1 using (select * from int4_tbl where f1 = x1) ss; -delete from xx1 using (select * from int4_tbl where f1 = xx1.x1) ss; -delete from xx1 using lateral (select * from int4_tbl where f1 = x1) ss; - --- --- test LATERAL reference propagation down a multi-level inheritance hierarchy --- produced for a multi-level partitioned table hierarchy. --- -create table join_pt1 (a int, b int, c varchar) partition by range(a); -create table join_pt1p1 partition of join_pt1 for values from (0) to (100) partition by range(b); -create table join_pt1p2 partition of join_pt1 for values from (100) to (200); -create table join_pt1p1p1 partition of join_pt1p1 for values from (0) to (100); -insert into join_pt1 values (1, 1, 'x'), (101, 101, 'y'); -create table join_ut1 (a int, b int, c varchar); -insert into join_ut1 values (101, 101, 'y'), (2, 2, 'z'); -explain (verbose, costs off) -select t1.b, ss.phv from join_ut1 t1 left join lateral - (select t2.a as t2a, t3.a t3a, least(t1.a, t2.a, t3.a) phv - from join_pt1 t2 join join_ut1 t3 on t2.a = t3.b) ss - on t1.a = ss.t2a order by t1.a; -select t1.b, ss.phv from join_ut1 t1 left join lateral - (select t2.a as t2a, t3.a t3a, least(t1.a, t2.a, t3.a) phv - from join_pt1 t2 join join_ut1 t3 on t2.a = t3.b) ss - on t1.a = ss.t2a order by t1.a; - -drop table join_pt1; -drop table join_ut1; - --- --- test estimation behavior with multi-column foreign key and constant qual --- - -begin; - -create table fkest (x integer, x10 integer, x10b integer, x100 integer); -insert into fkest select x, x/10, x/10, x/100 from generate_series(1,1000) x; -create unique index on fkest(x, x10, x100); -analyze fkest; - -explain (costs off) -select * from fkest f1 - join fkest f2 on (f1.x = f2.x and f1.x10 = f2.x10b and f1.x100 = f2.x100) - join fkest f3 on f1.x = f3.x - where f1.x100 = 2; - -alter table fkest add constraint fk - foreign key (x, x10b, x100) references fkest (x, x10, x100); - -explain (costs off) -select * from fkest f1 - join fkest f2 on (f1.x = f2.x and f1.x10 = f2.x10b and f1.x100 = f2.x100) - join fkest f3 on f1.x = f3.x - where f1.x100 = 2; - -rollback; - --- --- test that foreign key join estimation performs sanely for outer joins --- - -begin; - -create table fkest (a int, b int, c int unique, primary key(a,b)); -create table fkest1 (a int, b int, primary key(a,b)); - -insert into fkest select x/10, x%10, x from generate_series(1,1000) x; -insert into fkest1 select x/10, x%10 from generate_series(1,1000) x; - -alter table fkest1 - add constraint fkest1_a_b_fkey foreign key (a,b) references fkest; - -analyze fkest; -analyze fkest1; - -explain (costs off) -select * -from fkest f - left join fkest1 f1 on f.a = f1.a and f.b = f1.b - left join fkest1 f2 on f.a = f2.a and f.b = f2.b - left join fkest1 f3 on f.a = f3.a and f.b = f3.b -where f.c = 1; - -rollback; - --- --- test planner's ability to mark joins as unique --- - -create table j1 (id int primary key); -create table j2 (id int primary key); -create table j3 (id int); - -insert into j1 values(1),(2),(3); -insert into j2 values(1),(2),(3); -insert into j3 values(1),(1); - -analyze j1; -analyze j2; -analyze j3; - --- ensure join is properly marked as unique -explain (verbose, costs off) -select * from j1 inner join j2 on j1.id = j2.id; - --- ensure join is not unique when not an equi-join -explain (verbose, costs off) -select * from j1 inner join j2 on j1.id > j2.id; - --- ensure non-unique rel is not chosen as inner -explain (verbose, costs off) -select * from j1 inner join j3 on j1.id = j3.id; - --- ensure left join is marked as unique -explain (verbose, costs off) -select * from j1 left join j2 on j1.id = j2.id; - --- ensure right join is marked as unique -explain (verbose, costs off) -select * from j1 right join j2 on j1.id = j2.id; - --- ensure full join is marked as unique -explain (verbose, costs off) -select * from j1 full join j2 on j1.id = j2.id; - --- a clauseless (cross) join can't be unique -explain (verbose, costs off) -select * from j1 cross join j2; - --- ensure a natural join is marked as unique -explain (verbose, costs off) -select * from j1 natural join j2; - --- ensure a distinct clause allows the inner to become unique -explain (verbose, costs off) -select * from j1 -inner join (select distinct id from j3) j3 on j1.id = j3.id; - --- ensure group by clause allows the inner to become unique -explain (verbose, costs off) -select * from j1 -inner join (select id from j3 group by id) j3 on j1.id = j3.id; - -drop table j1; -drop table j2; -drop table j3; - --- test more complex permutations of unique joins - -create table j1 (id1 int, id2 int, primary key(id1,id2)); -create table j2 (id1 int, id2 int, primary key(id1,id2)); -create table j3 (id1 int, id2 int, primary key(id1,id2)); - -insert into j1 values(1,1),(1,2); -insert into j2 values(1,1); -insert into j3 values(1,1); - -analyze j1; -analyze j2; -analyze j3; - --- ensure there's no unique join when not all columns which are part of the --- unique index are seen in the join clause -explain (verbose, costs off) -select * from j1 -inner join j2 on j1.id1 = j2.id1; - --- ensure proper unique detection with multiple join quals -explain (verbose, costs off) -select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2; - --- ensure we don't detect the join to be unique when quals are not part of the --- join condition -explain (verbose, costs off) -select * from j1 -inner join j2 on j1.id1 = j2.id1 where j1.id2 = 1; - --- as above, but for left joins. -explain (verbose, costs off) -select * from j1 -left join j2 on j1.id1 = j2.id1 where j1.id2 = 1; - --- validate logic in merge joins which skips mark and restore. --- it should only do this if all quals which were used to detect the unique --- are present as join quals, and not plain quals. -set enable_nestloop to 0; -set enable_hashjoin to 0; -set enable_sort to 0; - --- create indexes that will be preferred over the PKs to perform the join -create index j1_id1_idx on j1 (id1) where id1 % 1000 = 1; -create index j2_id1_idx on j2 (id1) where id1 % 1000 = 1; - --- need an additional row in j2, if we want j2_id1_idx to be preferred -insert into j2 values(1,2); -analyze j2; - -explain (costs off) select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2 -where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1; - -select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2 -where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1; - --- Exercise array keys mark/restore B-Tree code -explain (costs off) select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2 -where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1 and j2.id1 = any (array[1]); - -select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2 -where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1 and j2.id1 = any (array[1]); - --- Exercise array keys "find extreme element" B-Tree code -explain (costs off) select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2 -where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1 and j2.id1 >= any (array[1,5]); - -select * from j1 -inner join j2 on j1.id1 = j2.id1 and j1.id2 = j2.id2 -where j1.id1 % 1000 = 1 and j2.id1 % 1000 = 1 and j2.id1 >= any (array[1,5]); - -reset enable_nestloop; -reset enable_hashjoin; -reset enable_sort; - -drop table j1; -drop table j2; -drop table j3; - --- check that semijoin inner is not seen as unique for a portion of the outerrel -explain (verbose, costs off) -select t1.unique1, t2.hundred -from onek t1, tenk1 t2 -where exists (select 1 from tenk1 t3 - where t3.thousand = t1.unique1 and t3.tenthous = t2.hundred) - and t1.unique1 < 1; - --- ... unless it actually is unique -create table j3 as select unique1, tenthous from onek; -vacuum analyze j3; -create unique index on j3(unique1, tenthous); - -explain (verbose, costs off) -select t1.unique1, t2.hundred -from onek t1, tenk1 t2 -where exists (select 1 from j3 - where j3.unique1 = t1.unique1 and j3.tenthous = t2.hundred) - and t1.unique1 < 1; - -drop table j3; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjoin_hash.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjoin_hash.sql deleted file mode 100644 index 77dbc182d5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjoin_hash.sql +++ /dev/null @@ -1,558 +0,0 @@ --- --- exercises for the hash join code --- - -begin; - -set local min_parallel_table_scan_size = 0; -set local parallel_setup_cost = 0; -set local enable_hashjoin = on; - --- Extract bucket and batch counts from an explain analyze plan. In --- general we can't make assertions about how many batches (or --- buckets) will be required because it can vary, but we can in some --- special cases and we can check for growth. -create or replace function find_hash(node json) -returns json language plpgsql -as -$$ -declare - x json; - child json; -begin - if node->>'Node Type' = 'Hash' then - return node; - else - for child in select json_array_elements(node->'Plans') - loop - x := find_hash(child); - if x is not null then - return x; - end if; - end loop; - return null; - end if; -end; -$$; -create or replace function hash_join_batches(query text) -returns table (original int, final int) language plpgsql -as -$$ -declare - whole_plan json; - hash_node json; -begin - for whole_plan in - execute 'explain (analyze, format ''json'') ' || query - loop - hash_node := find_hash(json_extract_path(whole_plan, '0', 'Plan')); - original := hash_node->>'Original Hash Batches'; - final := hash_node->>'Hash Batches'; - return next; - end loop; -end; -$$; - --- Make a simple relation with well distributed keys and correctly --- estimated size. -create table simple as - select generate_series(1, 20000) AS id, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; -alter table simple set (parallel_workers = 2); -analyze simple; - --- Make a relation whose size we will under-estimate. We want stats --- to say 1000 rows, but actually there are 20,000 rows. -create table bigger_than_it_looks as - select generate_series(1, 20000) as id, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; -alter table bigger_than_it_looks set (autovacuum_enabled = 'false'); -alter table bigger_than_it_looks set (parallel_workers = 2); -analyze bigger_than_it_looks; -update pg_class set reltuples = 1000 where relname = 'bigger_than_it_looks'; - --- Make a relation whose size we underestimate and that also has a --- kind of skew that breaks our batching scheme. We want stats to say --- 2 rows, but actually there are 20,000 rows with the same key. -create table extremely_skewed (id int, t text); -alter table extremely_skewed set (autovacuum_enabled = 'false'); -alter table extremely_skewed set (parallel_workers = 2); -analyze extremely_skewed; -insert into extremely_skewed - select 42 as id, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' - from generate_series(1, 20000); -update pg_class - set reltuples = 2, relpages = pg_relation_size('extremely_skewed') / 8192 - where relname = 'extremely_skewed'; - --- Make a relation with a couple of enormous tuples. -create table wide as select generate_series(1, 2) as id, rpad('', 320000, 'x') as t; -alter table wide set (parallel_workers = 2); - --- The "optimal" case: the hash table fits in memory; we plan for 1 --- batch, we stick to that number, and peak memory usage stays within --- our work_mem budget - --- non-parallel -savepoint settings; -set local max_parallel_workers_per_gather = 0; -set local work_mem = '4MB'; -set local hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from simple r join simple s using (id); -select count(*) from simple r join simple s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- parallel with parallel-oblivious hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '4MB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = off; -explain (costs off) - select count(*) from simple r join simple s using (id); -select count(*) from simple r join simple s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- parallel with parallel-aware hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '4MB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = on; -explain (costs off) - select count(*) from simple r join simple s using (id); -select count(*) from simple r join simple s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- The "good" case: batches required, but we plan the right number; we --- plan for some number of batches, and we stick to that number, and --- peak memory usage says within our work_mem budget - --- non-parallel -savepoint settings; -set local max_parallel_workers_per_gather = 0; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from simple r join simple s using (id); -select count(*) from simple r join simple s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- parallel with parallel-oblivious hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = off; -explain (costs off) - select count(*) from simple r join simple s using (id); -select count(*) from simple r join simple s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- parallel with parallel-aware hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '192kB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = on; -explain (costs off) - select count(*) from simple r join simple s using (id); -select count(*) from simple r join simple s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- The "bad" case: during execution we need to increase number of --- batches; in this case we plan for 1 batch, and increase at least a --- couple of times, and peak memory usage stays within our work_mem --- budget - --- non-parallel -savepoint settings; -set local max_parallel_workers_per_gather = 0; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) FROM simple r JOIN bigger_than_it_looks s USING (id); -select count(*) FROM simple r JOIN bigger_than_it_looks s USING (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) FROM simple r JOIN bigger_than_it_looks s USING (id); -$$); -rollback to settings; - --- parallel with parallel-oblivious hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = off; -explain (costs off) - select count(*) from simple r join bigger_than_it_looks s using (id); -select count(*) from simple r join bigger_than_it_looks s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join bigger_than_it_looks s using (id); -$$); -rollback to settings; - --- parallel with parallel-aware hash join -savepoint settings; -set local max_parallel_workers_per_gather = 1; -set local work_mem = '192kB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = on; -explain (costs off) - select count(*) from simple r join bigger_than_it_looks s using (id); -select count(*) from simple r join bigger_than_it_looks s using (id); -select original > 1 as initially_multibatch, final > original as increased_batches - from hash_join_batches( -$$ - select count(*) from simple r join bigger_than_it_looks s using (id); -$$); -rollback to settings; - --- The "ugly" case: increasing the number of batches during execution --- doesn't help, so stop trying to fit in work_mem and hope for the --- best; in this case we plan for 1 batch, increases just once and --- then stop increasing because that didn't help at all, so we blow --- right through the work_mem budget and hope for the best... - --- non-parallel -savepoint settings; -set local max_parallel_workers_per_gather = 0; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from simple r join extremely_skewed s using (id); -select count(*) from simple r join extremely_skewed s using (id); -select * from hash_join_batches( -$$ - select count(*) from simple r join extremely_skewed s using (id); -$$); -rollback to settings; - --- parallel with parallel-oblivious hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = off; -explain (costs off) - select count(*) from simple r join extremely_skewed s using (id); -select count(*) from simple r join extremely_skewed s using (id); -select * from hash_join_batches( -$$ - select count(*) from simple r join extremely_skewed s using (id); -$$); -rollback to settings; - --- parallel with parallel-aware hash join -savepoint settings; -set local max_parallel_workers_per_gather = 1; -set local work_mem = '128kB'; -set local hash_mem_multiplier = 1.0; -set local enable_parallel_hash = on; -explain (costs off) - select count(*) from simple r join extremely_skewed s using (id); -select count(*) from simple r join extremely_skewed s using (id); -select * from hash_join_batches( -$$ - select count(*) from simple r join extremely_skewed s using (id); -$$); -rollback to settings; - --- A couple of other hash join tests unrelated to work_mem management. - --- Check that EXPLAIN ANALYZE has data even if the leader doesn't participate -savepoint settings; -set local max_parallel_workers_per_gather = 2; -set local work_mem = '4MB'; -set local hash_mem_multiplier = 1.0; -set local parallel_leader_participation = off; -select * from hash_join_batches( -$$ - select count(*) from simple r join simple s using (id); -$$); -rollback to settings; - --- Exercise rescans. We'll turn off parallel_leader_participation so --- that we can check that instrumentation comes back correctly. - -create table join_foo as select generate_series(1, 3) as id, 'xxxxx'::text as t; -alter table join_foo set (parallel_workers = 0); -create table join_bar as select generate_series(1, 10000) as id, 'xxxxx'::text as t; -alter table join_bar set (parallel_workers = 2); - --- multi-batch with rescan, parallel-oblivious -savepoint settings; -set enable_parallel_hash = off; -set parallel_leader_participation = off; -set min_parallel_table_scan_size = 0; -set parallel_setup_cost = 0; -set parallel_tuple_cost = 0; -set max_parallel_workers_per_gather = 2; -set enable_material = off; -set enable_mergejoin = off; -set work_mem = '64kB'; -set hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select final > 1 as multibatch - from hash_join_batches( -$$ - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -$$); -rollback to settings; - --- single-batch with rescan, parallel-oblivious -savepoint settings; -set enable_parallel_hash = off; -set parallel_leader_participation = off; -set min_parallel_table_scan_size = 0; -set parallel_setup_cost = 0; -set parallel_tuple_cost = 0; -set max_parallel_workers_per_gather = 2; -set enable_material = off; -set enable_mergejoin = off; -set work_mem = '4MB'; -set hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select final > 1 as multibatch - from hash_join_batches( -$$ - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -$$); -rollback to settings; - --- multi-batch with rescan, parallel-aware -savepoint settings; -set enable_parallel_hash = on; -set parallel_leader_participation = off; -set min_parallel_table_scan_size = 0; -set parallel_setup_cost = 0; -set parallel_tuple_cost = 0; -set max_parallel_workers_per_gather = 2; -set enable_material = off; -set enable_mergejoin = off; -set work_mem = '64kB'; -set hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select final > 1 as multibatch - from hash_join_batches( -$$ - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -$$); -rollback to settings; - --- single-batch with rescan, parallel-aware -savepoint settings; -set enable_parallel_hash = on; -set parallel_leader_participation = off; -set min_parallel_table_scan_size = 0; -set parallel_setup_cost = 0; -set parallel_tuple_cost = 0; -set max_parallel_workers_per_gather = 2; -set enable_material = off; -set enable_mergejoin = off; -set work_mem = '4MB'; -set hash_mem_multiplier = 1.0; -explain (costs off) - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -select final > 1 as multibatch - from hash_join_batches( -$$ - select count(*) from join_foo - left join (select b1.id, b1.t from join_bar b1 join join_bar b2 using (id)) ss - on join_foo.id < ss.id + 1 and join_foo.id > ss.id - 1; -$$); -rollback to settings; - --- A full outer join where every record is matched. - --- non-parallel -savepoint settings; -set local max_parallel_workers_per_gather = 0; -explain (costs off) - select count(*) from simple r full outer join simple s using (id); -select count(*) from simple r full outer join simple s using (id); -rollback to settings; - --- parallelism not possible with parallel-oblivious outer hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -explain (costs off) - select count(*) from simple r full outer join simple s using (id); -select count(*) from simple r full outer join simple s using (id); -rollback to settings; - --- An full outer join where every record is not matched. - --- non-parallel -savepoint settings; -set local max_parallel_workers_per_gather = 0; -explain (costs off) - select count(*) from simple r full outer join simple s on (r.id = 0 - s.id); -select count(*) from simple r full outer join simple s on (r.id = 0 - s.id); -rollback to settings; - --- parallelism not possible with parallel-oblivious outer hash join -savepoint settings; -set local max_parallel_workers_per_gather = 2; -explain (costs off) - select count(*) from simple r full outer join simple s on (r.id = 0 - s.id); -select count(*) from simple r full outer join simple s on (r.id = 0 - s.id); -rollback to settings; - --- exercise special code paths for huge tuples (note use of non-strict --- expression and left join required to get the detoasted tuple into --- the hash table) - --- parallel with parallel-aware hash join (hits ExecParallelHashLoadTuple and --- sts_puttuple oversized tuple cases because it's multi-batch) -savepoint settings; -set max_parallel_workers_per_gather = 2; -set enable_parallel_hash = on; -set work_mem = '128kB'; -set hash_mem_multiplier = 1.0; -explain (costs off) - select length(max(s.t)) - from wide left join (select id, coalesce(t, '') || '' as t from wide) s using (id); -select length(max(s.t)) -from wide left join (select id, coalesce(t, '') || '' as t from wide) s using (id); -select final > 1 as multibatch - from hash_join_batches( -$$ - select length(max(s.t)) - from wide left join (select id, coalesce(t, '') || '' as t from wide) s using (id); -$$); -rollback to settings; - -rollback; - - --- Verify that hash key expressions reference the correct --- nodes. Hashjoin's hashkeys need to reference its outer plan, Hash's --- need to reference Hash's outer plan (which is below HashJoin's --- inner plan). It's not trivial to verify that the references are --- correct (we don't display the hashkeys themselves), but if the --- hashkeys contain subplan references, those will be displayed. Force --- subplans to appear just about everywhere. --- --- Bug report: --- https://www.postgresql.org/message-id/CAPpHfdvGVegF_TKKRiBrSmatJL2dR9uwFCuR%2BteQ_8tEXU8mxg%40mail.gmail.com --- -BEGIN; -SET LOCAL enable_sort = OFF; -- avoid mergejoins -SET LOCAL from_collapse_limit = 1; -- allows easy changing of join order - -CREATE TABLE hjtest_1 (a text, b int, id int, c bool); -CREATE TABLE hjtest_2 (a bool, id int, b text, c int); - -INSERT INTO hjtest_1(a, b, id, c) VALUES ('text', 2, 1, false); -- matches -INSERT INTO hjtest_1(a, b, id, c) VALUES ('text', 1, 2, false); -- fails id join condition -INSERT INTO hjtest_1(a, b, id, c) VALUES ('text', 20, 1, false); -- fails < 50 -INSERT INTO hjtest_1(a, b, id, c) VALUES ('text', 1, 1, false); -- fails (SELECT hjtest_1.b * 5) = (SELECT hjtest_2.c*5) - -INSERT INTO hjtest_2(a, id, b, c) VALUES (true, 1, 'another', 2); -- matches -INSERT INTO hjtest_2(a, id, b, c) VALUES (true, 3, 'another', 7); -- fails id join condition -INSERT INTO hjtest_2(a, id, b, c) VALUES (true, 1, 'another', 90); -- fails < 55 -INSERT INTO hjtest_2(a, id, b, c) VALUES (true, 1, 'another', 3); -- fails (SELECT hjtest_1.b * 5) = (SELECT hjtest_2.c*5) -INSERT INTO hjtest_2(a, id, b, c) VALUES (true, 1, 'text', 1); -- fails hjtest_1.a <> hjtest_2.b; - -EXPLAIN (COSTS OFF, VERBOSE) -SELECT hjtest_1.a a1, hjtest_2.a a2,hjtest_1.tableoid::regclass t1, hjtest_2.tableoid::regclass t2 -FROM hjtest_1, hjtest_2 -WHERE - hjtest_1.id = (SELECT 1 WHERE hjtest_2.id = 1) - AND (SELECT hjtest_1.b * 5) = (SELECT hjtest_2.c*5) - AND (SELECT hjtest_1.b * 5) < 50 - AND (SELECT hjtest_2.c * 5) < 55 - AND hjtest_1.a <> hjtest_2.b; - -SELECT hjtest_1.a a1, hjtest_2.a a2,hjtest_1.tableoid::regclass t1, hjtest_2.tableoid::regclass t2 -FROM hjtest_1, hjtest_2 -WHERE - hjtest_1.id = (SELECT 1 WHERE hjtest_2.id = 1) - AND (SELECT hjtest_1.b * 5) = (SELECT hjtest_2.c*5) - AND (SELECT hjtest_1.b * 5) < 50 - AND (SELECT hjtest_2.c * 5) < 55 - AND hjtest_1.a <> hjtest_2.b; - -EXPLAIN (COSTS OFF, VERBOSE) -SELECT hjtest_1.a a1, hjtest_2.a a2,hjtest_1.tableoid::regclass t1, hjtest_2.tableoid::regclass t2 -FROM hjtest_2, hjtest_1 -WHERE - hjtest_1.id = (SELECT 1 WHERE hjtest_2.id = 1) - AND (SELECT hjtest_1.b * 5) = (SELECT hjtest_2.c*5) - AND (SELECT hjtest_1.b * 5) < 50 - AND (SELECT hjtest_2.c * 5) < 55 - AND hjtest_1.a <> hjtest_2.b; - -SELECT hjtest_1.a a1, hjtest_2.a a2,hjtest_1.tableoid::regclass t1, hjtest_2.tableoid::regclass t2 -FROM hjtest_2, hjtest_1 -WHERE - hjtest_1.id = (SELECT 1 WHERE hjtest_2.id = 1) - AND (SELECT hjtest_1.b * 5) = (SELECT hjtest_2.c*5) - AND (SELECT hjtest_1.b * 5) < 50 - AND (SELECT hjtest_2.c * 5) < 55 - AND hjtest_1.a <> hjtest_2.b; - -ROLLBACK; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjson.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjson.sql deleted file mode 100644 index e366c6f51b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjson.sql +++ /dev/null @@ -1,852 +0,0 @@ --- Strings. -SELECT '""'::json; -- OK. -SELECT $$''$$::json; -- ERROR, single quotes are not allowed -SELECT '"abc"'::json; -- OK -SELECT '"abc'::json; -- ERROR, quotes not closed -SELECT '"abc -def"'::json; -- ERROR, unescaped newline in string constant -SELECT '"\n\"\\"'::json; -- OK, legal escapes -SELECT '"\v"'::json; -- ERROR, not a valid JSON escape --- see json_encoding test for input with unicode escapes - --- Numbers. -SELECT '1'::json; -- OK -SELECT '0'::json; -- OK -SELECT '01'::json; -- ERROR, not valid according to JSON spec -SELECT '0.1'::json; -- OK -SELECT '9223372036854775808'::json; -- OK, even though it's too large for int8 -SELECT '1e100'::json; -- OK -SELECT '1.3e100'::json; -- OK -SELECT '1f2'::json; -- ERROR -SELECT '0.x1'::json; -- ERROR -SELECT '1.3ex100'::json; -- ERROR - --- Arrays. -SELECT '[]'::json; -- OK -SELECT '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'::json; -- OK -SELECT '[1,2]'::json; -- OK -SELECT '[1,2,]'::json; -- ERROR, trailing comma -SELECT '[1,2'::json; -- ERROR, no closing bracket -SELECT '[1,[2]'::json; -- ERROR, no closing bracket - --- Objects. -SELECT '{}'::json; -- OK -SELECT '{"abc"}'::json; -- ERROR, no value -SELECT '{"abc":1}'::json; -- OK -SELECT '{1:"abc"}'::json; -- ERROR, keys must be strings -SELECT '{"abc",1}'::json; -- ERROR, wrong separator -SELECT '{"abc"=1}'::json; -- ERROR, totally wrong separator -SELECT '{"abc"::1}'::json; -- ERROR, another wrong separator -SELECT '{"abc":1,"def":2,"ghi":[3,4],"hij":{"klm":5,"nop":[6]}}'::json; -- OK -SELECT '{"abc":1:2}'::json; -- ERROR, colon in wrong spot -SELECT '{"abc":1,3}'::json; -- ERROR, no value - --- Recursion. -SET max_stack_depth = '100kB'; -SELECT repeat('[', 10000)::json; -SELECT repeat('{"a":', 10000)::json; -RESET max_stack_depth; - --- Miscellaneous stuff. -SELECT 'true'::json; -- OK -SELECT 'false'::json; -- OK -SELECT 'null'::json; -- OK -SELECT ' true '::json; -- OK, even with extra whitespace -SELECT 'true false'::json; -- ERROR, too many values -SELECT 'true, false'::json; -- ERROR, too many values -SELECT 'truf'::json; -- ERROR, not a keyword -SELECT 'trues'::json; -- ERROR, not a keyword -SELECT ''::json; -- ERROR, no value -SELECT ' '::json; -- ERROR, no value - --- Multi-line JSON input to check ERROR reporting -SELECT '{ - "one": 1, - "two":"two", - "three": - true}'::json; -- OK -SELECT '{ - "one": 1, - "two":,"two", -- ERROR extraneous comma before field "two" - "three": - true}'::json; -SELECT '{ - "one": 1, - "two":"two", - "averyveryveryveryveryveryveryveryveryverylongfieldname":}'::json; --- ERROR missing value for last field - ---constructors --- array_to_json - -SELECT array_to_json(array(select 1 as a)); -SELECT array_to_json(array_agg(q),false) from (select x as b, x * 2 as c from generate_series(1,3) x) q; -SELECT array_to_json(array_agg(q),true) from (select x as b, x * 2 as c from generate_series(1,3) x) q; -SELECT array_to_json(array_agg(q),false) - FROM ( SELECT $$a$$ || x AS b, y AS c, - ARRAY[ROW(x.*,ARRAY[1,2,3]), - ROW(y.*,ARRAY[4,5,6])] AS z - FROM generate_series(1,2) x, - generate_series(4,5) y) q; -SELECT array_to_json(array_agg(x),false) from generate_series(5,10) x; -SELECT array_to_json('{{1,5},{99,100}}'::int[]); - --- row_to_json -SELECT row_to_json(row(1,'foo')); - -SELECT row_to_json(q) -FROM (SELECT $$a$$ || x AS b, - y AS c, - ARRAY[ROW(x.*,ARRAY[1,2,3]), - ROW(y.*,ARRAY[4,5,6])] AS z - FROM generate_series(1,2) x, - generate_series(4,5) y) q; - -SELECT row_to_json(q,true) -FROM (SELECT $$a$$ || x AS b, - y AS c, - ARRAY[ROW(x.*,ARRAY[1,2,3]), - ROW(y.*,ARRAY[4,5,6])] AS z - FROM generate_series(1,2) x, - generate_series(4,5) y) q; - -CREATE TEMP TABLE rows AS -SELECT x, 'txt' || x as y -FROM generate_series(1,3) AS x; - -SELECT row_to_json(q,true) -FROM rows q; - -SELECT row_to_json(row((select array_agg(x) as d from generate_series(5,10) x)),false); - --- anyarray column - -analyze rows; - -select attname, to_json(histogram_bounds) histogram_bounds -from pg_stats -where tablename = 'rows' and - schemaname = pg_my_temp_schema()::regnamespace::text -order by 1; - --- to_json, timestamps - -select to_json(timestamp '2014-05-28 12:22:35.614298'); - -BEGIN; -SET LOCAL TIME ZONE 10.5; -select to_json(timestamptz '2014-05-28 12:22:35.614298-04'); -SET LOCAL TIME ZONE -8; -select to_json(timestamptz '2014-05-28 12:22:35.614298-04'); -COMMIT; - -select to_json(date '2014-05-28'); - -select to_json(date 'Infinity'); -select to_json(date '-Infinity'); -select to_json(timestamp 'Infinity'); -select to_json(timestamp '-Infinity'); -select to_json(timestamptz 'Infinity'); -select to_json(timestamptz '-Infinity'); - ---json_agg - -SELECT json_agg(q) - FROM ( SELECT $$a$$ || x AS b, y AS c, - ARRAY[ROW(x.*,ARRAY[1,2,3]), - ROW(y.*,ARRAY[4,5,6])] AS z - FROM generate_series(1,2) x, - generate_series(4,5) y) q; - -SELECT json_agg(q ORDER BY x, y) - FROM rows q; - -UPDATE rows SET x = NULL WHERE x = 1; - -SELECT json_agg(q ORDER BY x NULLS FIRST, y) - FROM rows q; - --- non-numeric output -SELECT row_to_json(q) -FROM (SELECT 'NaN'::float8 AS "float8field") q; - -SELECT row_to_json(q) -FROM (SELECT 'Infinity'::float8 AS "float8field") q; - -SELECT row_to_json(q) -FROM (SELECT '-Infinity'::float8 AS "float8field") q; - --- json input -SELECT row_to_json(q) -FROM (SELECT '{"a":1,"b": [2,3,4,"d","e","f"],"c":{"p":1,"q":2}}'::json AS "jsonfield") q; - - --- json extraction functions - -CREATE TEMP TABLE test_json ( - json_type text, - test_json json -); - -INSERT INTO test_json VALUES -('scalar','"a scalar"'), -('array','["zero", "one","two",null,"four","five", [1,2,3],{"f1":9}]'), -('object','{"field1":"val1","field2":"val2","field3":null, "field4": 4, "field5": [1,2,3], "field6": {"f1":9}}'); - -SELECT test_json -> 'x' -FROM test_json -WHERE json_type = 'scalar'; - -SELECT test_json -> 'x' -FROM test_json -WHERE json_type = 'array'; - -SELECT test_json -> 'x' -FROM test_json -WHERE json_type = 'object'; - -SELECT test_json->'field2' -FROM test_json -WHERE json_type = 'object'; - -SELECT test_json->>'field2' -FROM test_json -WHERE json_type = 'object'; - -SELECT test_json -> 2 -FROM test_json -WHERE json_type = 'scalar'; - -SELECT test_json -> 2 -FROM test_json -WHERE json_type = 'array'; - -SELECT test_json -> -1 -FROM test_json -WHERE json_type = 'array'; - -SELECT test_json -> 2 -FROM test_json -WHERE json_type = 'object'; - -SELECT test_json->>2 -FROM test_json -WHERE json_type = 'array'; - -SELECT test_json ->> 6 FROM test_json WHERE json_type = 'array'; -SELECT test_json ->> 7 FROM test_json WHERE json_type = 'array'; - -SELECT test_json ->> 'field4' FROM test_json WHERE json_type = 'object'; -SELECT test_json ->> 'field5' FROM test_json WHERE json_type = 'object'; -SELECT test_json ->> 'field6' FROM test_json WHERE json_type = 'object'; - -SELECT json_object_keys(test_json) -FROM test_json -WHERE json_type = 'scalar'; - -SELECT json_object_keys(test_json) -FROM test_json -WHERE json_type = 'array'; - -SELECT json_object_keys(test_json) -FROM test_json -WHERE json_type = 'object'; - --- test extending object_keys resultset - initial resultset size is 256 - -select count(*) from - (select json_object_keys(json_object(array_agg(g))) - from (select unnest(array['f'||n,n::text])as g - from generate_series(1,300) as n) x ) y; - --- nulls - -select (test_json->'field3') is null as expect_false -from test_json -where json_type = 'object'; - -select (test_json->>'field3') is null as expect_true -from test_json -where json_type = 'object'; - -select (test_json->3) is null as expect_false -from test_json -where json_type = 'array'; - -select (test_json->>3) is null as expect_true -from test_json -where json_type = 'array'; - --- corner cases - -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json -> null::text; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json -> null::int; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json -> 1; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json -> -1; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json -> 'z'; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json -> ''; -select '[{"b": "c"}, {"b": "cc"}]'::json -> 1; -select '[{"b": "c"}, {"b": "cc"}]'::json -> 3; -select '[{"b": "c"}, {"b": "cc"}]'::json -> 'z'; -select '{"a": "c", "b": null}'::json -> 'b'; -select '"foo"'::json -> 1; -select '"foo"'::json -> 'z'; - -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json ->> null::text; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json ->> null::int; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json ->> 1; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json ->> 'z'; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json ->> ''; -select '[{"b": "c"}, {"b": "cc"}]'::json ->> 1; -select '[{"b": "c"}, {"b": "cc"}]'::json ->> 3; -select '[{"b": "c"}, {"b": "cc"}]'::json ->> 'z'; -select '{"a": "c", "b": null}'::json ->> 'b'; -select '"foo"'::json ->> 1; -select '"foo"'::json ->> 'z'; - --- array length - -SELECT json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]'); - -SELECT json_array_length('[]'); - -SELECT json_array_length('{"f1":1,"f2":[5,6]}'); - -SELECT json_array_length('4'); - --- each - -select json_each('{"f1":[1,2,3],"f2":{"f3":1},"f4":null}'); -select * from json_each('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":99,"f6":"stringy"}') q; - -select json_each_text('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":"null"}'); -select * from json_each_text('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":99,"f6":"stringy"}') q; - --- extract_path, extract_path_as_text - -select json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f4','f6'); -select json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f2'); -select json_extract_path('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',0::text); -select json_extract_path('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',1::text); -select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f4','f6'); -select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f2'); -select json_extract_path_text('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',0::text); -select json_extract_path_text('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',1::text); - --- extract_path nulls - -select json_extract_path('{"f2":{"f3":1},"f4":{"f5":null,"f6":"stringy"}}','f4','f5') is null as expect_false; -select json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":null,"f6":"stringy"}}','f4','f5') is null as expect_true; -select json_extract_path('{"f2":{"f3":1},"f4":[0,1,2,null]}','f4','3') is null as expect_false; -select json_extract_path_text('{"f2":{"f3":1},"f4":[0,1,2,null]}','f4','3') is null as expect_true; - --- extract_path operators - -select '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::json#>array['f4','f6']; -select '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::json#>array['f2']; -select '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::json#>array['f2','0']; -select '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::json#>array['f2','1']; - -select '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::json#>>array['f4','f6']; -select '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::json#>>array['f2']; -select '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::json#>>array['f2','0']; -select '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::json#>>array['f2','1']; - --- corner cases for same -select '{"a": {"b":{"c": "foo"}}}'::json #> '{}'; -select '[1,2,3]'::json #> '{}'; -select '"foo"'::json #> '{}'; -select '42'::json #> '{}'; -select 'null'::json #> '{}'; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a']; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a', null]; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a', '']; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a','b']; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a','b','c']; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a','b','c','d']; -select '{"a": {"b":{"c": "foo"}}}'::json #> array['a','z','c']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json #> array['a','1','b']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json #> array['a','z','b']; -select '[{"b": "c"}, {"b": "cc"}]'::json #> array['1','b']; -select '[{"b": "c"}, {"b": "cc"}]'::json #> array['z','b']; -select '[{"b": "c"}, {"b": null}]'::json #> array['1','b']; -select '"foo"'::json #> array['z']; -select '42'::json #> array['f2']; -select '42'::json #> array['0']; - -select '{"a": {"b":{"c": "foo"}}}'::json #>> '{}'; -select '[1,2,3]'::json #>> '{}'; -select '"foo"'::json #>> '{}'; -select '42'::json #>> '{}'; -select 'null'::json #>> '{}'; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a']; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a', null]; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a', '']; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a','b']; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a','b','c']; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a','b','c','d']; -select '{"a": {"b":{"c": "foo"}}}'::json #>> array['a','z','c']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json #>> array['a','1','b']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::json #>> array['a','z','b']; -select '[{"b": "c"}, {"b": "cc"}]'::json #>> array['1','b']; -select '[{"b": "c"}, {"b": "cc"}]'::json #>> array['z','b']; -select '[{"b": "c"}, {"b": null}]'::json #>> array['1','b']; -select '"foo"'::json #>> array['z']; -select '42'::json #>> array['f2']; -select '42'::json #>> array['0']; - --- array_elements - -select json_array_elements('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]'); -select * from json_array_elements('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]') q; -select json_array_elements_text('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]'); -select * from json_array_elements_text('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]') q; - --- populate_record -create type jpop as (a text, b int, c timestamp); - -CREATE DOMAIN js_int_not_null AS int NOT NULL; -CREATE DOMAIN js_int_array_1d AS int[] CHECK(array_length(VALUE, 1) = 3); -CREATE DOMAIN js_int_array_2d AS int[][] CHECK(array_length(VALUE, 2) = 3); - -create type j_unordered_pair as (x int, y int); -create domain j_ordered_pair as j_unordered_pair check((value).x <= (value).y); - -CREATE TYPE jsrec AS ( - i int, - ia _int4, - ia1 int[], - ia2 int[][], - ia3 int[][][], - ia1d js_int_array_1d, - ia2d js_int_array_2d, - t text, - ta text[], - c char(10), - ca char(10)[], - ts timestamp, - js json, - jsb jsonb, - jsa json[], - rec jpop, - reca jpop[] -); - -CREATE TYPE jsrec_i_not_null AS ( - i js_int_not_null -); - -select * from json_populate_record(null::jpop,'{"a":"blurfl","x":43.2}') q; -select * from json_populate_record(row('x',3,'2012-12-31 15:30:56')::jpop,'{"a":"blurfl","x":43.2}') q; - -select * from json_populate_record(null::jpop,'{"a":"blurfl","x":43.2}') q; -select * from json_populate_record(row('x',3,'2012-12-31 15:30:56')::jpop,'{"a":"blurfl","x":43.2}') q; - -select * from json_populate_record(null::jpop,'{"a":[100,200,false],"x":43.2}') q; -select * from json_populate_record(row('x',3,'2012-12-31 15:30:56')::jpop,'{"a":[100,200,false],"x":43.2}') q; -select * from json_populate_record(row('x',3,'2012-12-31 15:30:56')::jpop,'{"c":[100,200,false],"x":43.2}') q; - -select * from json_populate_record(row('x',3,'2012-12-31 15:30:56')::jpop,'{}') q; - -SELECT i FROM json_populate_record(NULL::jsrec_i_not_null, '{"x": 43.2}') q; -SELECT i FROM json_populate_record(NULL::jsrec_i_not_null, '{"i": null}') q; -SELECT i FROM json_populate_record(NULL::jsrec_i_not_null, '{"i": 12345}') q; - -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": null}') q; -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": 123}') q; -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": [1, "2", null, 4]}') q; -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": [[1, 2], [3, 4]]}') q; -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": [[1], 2]}') q; -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": [[1], [2, 3]]}') q; -SELECT ia FROM json_populate_record(NULL::jsrec, '{"ia": "{1,2,3}"}') q; - -SELECT ia1 FROM json_populate_record(NULL::jsrec, '{"ia1": null}') q; -SELECT ia1 FROM json_populate_record(NULL::jsrec, '{"ia1": 123}') q; -SELECT ia1 FROM json_populate_record(NULL::jsrec, '{"ia1": [1, "2", null, 4]}') q; -SELECT ia1 FROM json_populate_record(NULL::jsrec, '{"ia1": [[1, 2, 3]]}') q; - -SELECT ia1d FROM json_populate_record(NULL::jsrec, '{"ia1d": null}') q; -SELECT ia1d FROM json_populate_record(NULL::jsrec, '{"ia1d": 123}') q; -SELECT ia1d FROM json_populate_record(NULL::jsrec, '{"ia1d": [1, "2", null, 4]}') q; -SELECT ia1d FROM json_populate_record(NULL::jsrec, '{"ia1d": [1, "2", null]}') q; - -SELECT ia2 FROM json_populate_record(NULL::jsrec, '{"ia2": [1, "2", null, 4]}') q; -SELECT ia2 FROM json_populate_record(NULL::jsrec, '{"ia2": [[1, 2], [null, 4]]}') q; -SELECT ia2 FROM json_populate_record(NULL::jsrec, '{"ia2": [[], []]}') q; -SELECT ia2 FROM json_populate_record(NULL::jsrec, '{"ia2": [[1, 2], [3]]}') q; -SELECT ia2 FROM json_populate_record(NULL::jsrec, '{"ia2": [[1, 2], 3, 4]}') q; - -SELECT ia2d FROM json_populate_record(NULL::jsrec, '{"ia2d": [[1, "2"], [null, 4]]}') q; -SELECT ia2d FROM json_populate_record(NULL::jsrec, '{"ia2d": [[1, "2", 3], [null, 5, 6]]}') q; - -SELECT ia3 FROM json_populate_record(NULL::jsrec, '{"ia3": [1, "2", null, 4]}') q; -SELECT ia3 FROM json_populate_record(NULL::jsrec, '{"ia3": [[1, 2], [null, 4]]}') q; -SELECT ia3 FROM json_populate_record(NULL::jsrec, '{"ia3": [ [[], []], [[], []], [[], []] ]}') q; -SELECT ia3 FROM json_populate_record(NULL::jsrec, '{"ia3": [ [[1, 2]], [[3, 4]] ]}') q; -SELECT ia3 FROM json_populate_record(NULL::jsrec, '{"ia3": [ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]}') q; -SELECT ia3 FROM json_populate_record(NULL::jsrec, '{"ia3": [ [[1, 2], [3, 4]], [[5, 6], [7, 8], [9, 10]] ]}') q; - -SELECT ta FROM json_populate_record(NULL::jsrec, '{"ta": null}') q; -SELECT ta FROM json_populate_record(NULL::jsrec, '{"ta": 123}') q; -SELECT ta FROM json_populate_record(NULL::jsrec, '{"ta": [1, "2", null, 4]}') q; -SELECT ta FROM json_populate_record(NULL::jsrec, '{"ta": [[1, 2, 3], {"k": "v"}]}') q; - -SELECT c FROM json_populate_record(NULL::jsrec, '{"c": null}') q; -SELECT c FROM json_populate_record(NULL::jsrec, '{"c": "aaa"}') q; -SELECT c FROM json_populate_record(NULL::jsrec, '{"c": "aaaaaaaaaa"}') q; -SELECT c FROM json_populate_record(NULL::jsrec, '{"c": "aaaaaaaaaaaaa"}') q; - -SELECT ca FROM json_populate_record(NULL::jsrec, '{"ca": null}') q; -SELECT ca FROM json_populate_record(NULL::jsrec, '{"ca": 123}') q; -SELECT ca FROM json_populate_record(NULL::jsrec, '{"ca": [1, "2", null, 4]}') q; -SELECT ca FROM json_populate_record(NULL::jsrec, '{"ca": ["aaaaaaaaaaaaaaaa"]}') q; -SELECT ca FROM json_populate_record(NULL::jsrec, '{"ca": [[1, 2, 3], {"k": "v"}]}') q; - -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": null}') q; -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": true}') q; -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": 123.45}') q; -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": "123.45"}') q; -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": "abc"}') q; -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": [123, "123", null, {"key": "value"}]}') q; -SELECT js FROM json_populate_record(NULL::jsrec, '{"js": {"a": "bbb", "b": null, "c": 123.45}}') q; - -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": null}') q; -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": true}') q; -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": 123.45}') q; -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": "123.45"}') q; -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": "abc"}') q; -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": [123, "123", null, {"key": "value"}]}') q; -SELECT jsb FROM json_populate_record(NULL::jsrec, '{"jsb": {"a": "bbb", "b": null, "c": 123.45}}') q; - -SELECT jsa FROM json_populate_record(NULL::jsrec, '{"jsa": null}') q; -SELECT jsa FROM json_populate_record(NULL::jsrec, '{"jsa": 123}') q; -SELECT jsa FROM json_populate_record(NULL::jsrec, '{"jsa": [1, "2", null, 4]}') q; -SELECT jsa FROM json_populate_record(NULL::jsrec, '{"jsa": ["aaa", null, [1, 2, "3", {}], { "k" : "v" }]}') q; - -SELECT rec FROM json_populate_record(NULL::jsrec, '{"rec": 123}') q; -SELECT rec FROM json_populate_record(NULL::jsrec, '{"rec": [1, 2]}') q; -SELECT rec FROM json_populate_record(NULL::jsrec, '{"rec": {"a": "abc", "c": "01.02.2003", "x": 43.2}}') q; -SELECT rec FROM json_populate_record(NULL::jsrec, '{"rec": "(abc,42,01.02.2003)"}') q; - -SELECT reca FROM json_populate_record(NULL::jsrec, '{"reca": 123}') q; -SELECT reca FROM json_populate_record(NULL::jsrec, '{"reca": [1, 2]}') q; -SELECT reca FROM json_populate_record(NULL::jsrec, '{"reca": [{"a": "abc", "b": 456}, null, {"c": "01.02.2003", "x": 43.2}]}') q; -SELECT reca FROM json_populate_record(NULL::jsrec, '{"reca": ["(abc,42,01.02.2003)"]}') q; -SELECT reca FROM json_populate_record(NULL::jsrec, '{"reca": "{\"(abc,42,01.02.2003)\"}"}') q; - -SELECT rec FROM json_populate_record( - row(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - row('x',3,'2012-12-31 15:30:56')::jpop,NULL)::jsrec, - '{"rec": {"a": "abc", "c": "01.02.2003", "x": 43.2}}' -) q; - --- anonymous record type -SELECT json_populate_record(null::record, '{"x": 0, "y": 1}'); -SELECT json_populate_record(row(1,2), '{"f1": 0, "f2": 1}'); -SELECT * FROM - json_populate_record(null::record, '{"x": 776}') AS (x int, y int); - --- composite domain -SELECT json_populate_record(null::j_ordered_pair, '{"x": 0, "y": 1}'); -SELECT json_populate_record(row(1,2)::j_ordered_pair, '{"x": 0}'); -SELECT json_populate_record(row(1,2)::j_ordered_pair, '{"x": 1, "y": 0}'); - --- populate_recordset - -select * from json_populate_recordset(null::jpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(row('def',99,null)::jpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(null::jpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(row('def',99,null)::jpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(row('def',99,null)::jpop,'[{"a":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(row('def',99,null)::jpop,'[{"c":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; - -create type jpop2 as (a int, b json, c int, d int); -select * from json_populate_recordset(null::jpop2, '[{"a":2,"c":3,"b":{"z":4},"d":6}]') q; - -select * from json_populate_recordset(null::jpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(row('def',99,null)::jpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -select * from json_populate_recordset(row('def',99,null)::jpop,'[{"a":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; - --- anonymous record type -SELECT json_populate_recordset(null::record, '[{"x": 0, "y": 1}]'); -SELECT json_populate_recordset(row(1,2), '[{"f1": 0, "f2": 1}]'); -SELECT i, json_populate_recordset(row(i,50), '[{"f1":"42"},{"f2":"43"}]') -FROM (VALUES (1),(2)) v(i); -SELECT * FROM - json_populate_recordset(null::record, '[{"x": 776}]') AS (x int, y int); - --- empty array is a corner case -SELECT json_populate_recordset(null::record, '[]'); -SELECT json_populate_recordset(row(1,2), '[]'); -SELECT * FROM json_populate_recordset(NULL::jpop,'[]') q; -SELECT * FROM - json_populate_recordset(null::record, '[]') AS (x int, y int); - --- composite domain -SELECT json_populate_recordset(null::j_ordered_pair, '[{"x": 0, "y": 1}]'); -SELECT json_populate_recordset(row(1,2)::j_ordered_pair, '[{"x": 0}, {"y": 3}]'); -SELECT json_populate_recordset(row(1,2)::j_ordered_pair, '[{"x": 1, "y": 0}]'); - --- negative cases where the wrong record type is supplied -select * from json_populate_recordset(row(0::int),'[{"a":"1","b":"2"},{"a":"3"}]') q (a text, b text); -select * from json_populate_recordset(row(0::int,0::int),'[{"a":"1","b":"2"},{"a":"3"}]') q (a text, b text); -select * from json_populate_recordset(row(0::int,0::int,0::int),'[{"a":"1","b":"2"},{"a":"3"}]') q (a text, b text); -select * from json_populate_recordset(row(1000000000::int,50::int),'[{"b":"2"},{"a":"3"}]') q (a text, b text); - --- test type info caching in json_populate_record() -CREATE TEMP TABLE jspoptest (js json); - -INSERT INTO jspoptest -SELECT '{ - "jsa": [1, "2", null, 4], - "rec": {"a": "abc", "c": "01.02.2003", "x": 43.2}, - "reca": [{"a": "abc", "b": 456}, null, {"c": "01.02.2003", "x": 43.2}] -}'::json -FROM generate_series(1, 3); - -SELECT (json_populate_record(NULL::jsrec, js)).* FROM jspoptest; - -DROP TYPE jsrec; -DROP TYPE jsrec_i_not_null; -DROP DOMAIN js_int_not_null; -DROP DOMAIN js_int_array_1d; -DROP DOMAIN js_int_array_2d; -DROP DOMAIN j_ordered_pair; -DROP TYPE j_unordered_pair; - ---json_typeof() function -select value, json_typeof(value) - from (values (json '123.4'), - (json '-1'), - (json '"foo"'), - (json 'true'), - (json 'false'), - (json 'null'), - (json '[1, 2, 3]'), - (json '[]'), - (json '{"x":"foo", "y":123}'), - (json '{}'), - (NULL::json)) - as data(value); - --- json_build_array, json_build_object, json_object_agg - -SELECT json_build_array('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}'); -SELECT json_build_array('a', NULL); -- ok -SELECT json_build_array(VARIADIC NULL::text[]); -- ok -SELECT json_build_array(VARIADIC '{}'::text[]); -- ok -SELECT json_build_array(VARIADIC '{a,b,c}'::text[]); -- ok -SELECT json_build_array(VARIADIC ARRAY['a', NULL]::text[]); -- ok -SELECT json_build_array(VARIADIC '{1,2,3,4}'::text[]); -- ok -SELECT json_build_array(VARIADIC '{1,2,3,4}'::int[]); -- ok -SELECT json_build_array(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok - -SELECT json_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}'); - -SELECT json_build_object( - 'a', json_build_object('b',false,'c',99), - 'd', json_build_object('e',array[9,8,7]::int[], - 'f', (select row_to_json(r) from ( select relkind, oid::regclass as name from pg_class where relname = 'pg_class') r))); -SELECT json_build_object('{a,b,c}'::text[]); -- error -SELECT json_build_object('{a,b,c}'::text[], '{d,e,f}'::text[]); -- error, key cannot be array -SELECT json_build_object('a', 'b', 'c'); -- error -SELECT json_build_object(NULL, 'a'); -- error, key cannot be NULL -SELECT json_build_object('a', NULL); -- ok -SELECT json_build_object(VARIADIC NULL::text[]); -- ok -SELECT json_build_object(VARIADIC '{}'::text[]); -- ok -SELECT json_build_object(VARIADIC '{a,b,c}'::text[]); -- error -SELECT json_build_object(VARIADIC ARRAY['a', NULL]::text[]); -- ok -SELECT json_build_object(VARIADIC ARRAY[NULL, 'a']::text[]); -- error, key cannot be NULL -SELECT json_build_object(VARIADIC '{1,2,3,4}'::text[]); -- ok -SELECT json_build_object(VARIADIC '{1,2,3,4}'::int[]); -- ok -SELECT json_build_object(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok - --- empty objects/arrays -SELECT json_build_array(); - -SELECT json_build_object(); - --- make sure keys are quoted -SELECT json_build_object(1,2); - --- keys must be scalar and not null -SELECT json_build_object(null,2); - -SELECT json_build_object(r,2) FROM (SELECT 1 AS a, 2 AS b) r; - -SELECT json_build_object(json '{"a":1,"b":2}', 3); - -SELECT json_build_object('{1,2,3}'::int[], 3); - -CREATE TEMP TABLE foo (serial_num int, name text, type text); -INSERT INTO foo VALUES (847001,'t15','GE1043'); -INSERT INTO foo VALUES (847002,'t16','GE1043'); -INSERT INTO foo VALUES (847003,'sub-alpha','GESS90'); - -SELECT json_build_object('turbines',json_object_agg(serial_num,json_build_object('name',name,'type',type))) -FROM foo; - -SELECT json_object_agg(name, type) FROM foo; - -INSERT INTO foo VALUES (999999, NULL, 'bar'); -SELECT json_object_agg(name, type) FROM foo; - --- json_object - --- empty object, one dimension -SELECT json_object('{}'); - --- empty object, two dimensions -SELECT json_object('{}', '{}'); - --- one dimension -SELECT json_object('{a,1,b,2,3,NULL,"d e f","a b c"}'); - --- same but with two dimensions -SELECT json_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}'); - --- odd number error -SELECT json_object('{a,b,c}'); - --- one column error -SELECT json_object('{{a},{b}}'); - --- too many columns error -SELECT json_object('{{a,b,c},{b,c,d}}'); - --- too many dimensions error -SELECT json_object('{{{a,b},{c,d}},{{b,c},{d,e}}}'); - ---two argument form of json_object - -select json_object('{a,b,c,"d e f"}','{1,2,3,"a b c"}'); - --- too many dimensions -SELECT json_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}', '{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}'); - --- mismatched dimensions - -select json_object('{a,b,c,"d e f",g}','{1,2,3,"a b c"}'); - -select json_object('{a,b,c,"d e f"}','{1,2,3,"a b c",g}'); - --- null key error - -select json_object('{a,b,NULL,"d e f"}','{1,2,3,"a b c"}'); - --- empty key is allowed - -select json_object('{a,b,"","d e f"}','{1,2,3,"a b c"}'); - - --- json_to_record and json_to_recordset - -select * from json_to_record('{"a":1,"b":"foo","c":"bar"}') - as x(a int, b text, d text); - -select * from json_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]') - as x(a int, b text, c boolean); - -select * from json_to_recordset('[{"a":1,"b":{"d":"foo"},"c":true},{"a":2,"c":false,"b":{"d":"bar"}}]') - as x(a int, b json, c boolean); - -select *, c is null as c_is_null -from json_to_record('{"a":1, "b":{"c":16, "d":2}, "x":8, "ca": ["1 2", 3], "ia": [[1,2],[3,4]], "r": {"a": "aaa", "b": 123}}'::json) - as t(a int, b json, c text, x int, ca char(5)[], ia int[][], r jpop); - -select *, c is null as c_is_null -from json_to_recordset('[{"a":1, "b":{"c":16, "d":2}, "x":8}]'::json) - as t(a int, b json, c text, x int); - -select * from json_to_record('{"ia": null}') as x(ia _int4); -select * from json_to_record('{"ia": 123}') as x(ia _int4); -select * from json_to_record('{"ia": [1, "2", null, 4]}') as x(ia _int4); -select * from json_to_record('{"ia": [[1, 2], [3, 4]]}') as x(ia _int4); -select * from json_to_record('{"ia": [[1], 2]}') as x(ia _int4); -select * from json_to_record('{"ia": [[1], [2, 3]]}') as x(ia _int4); - -select * from json_to_record('{"ia2": [1, 2, 3]}') as x(ia2 int[][]); -select * from json_to_record('{"ia2": [[1, 2], [3, 4]]}') as x(ia2 int4[][]); -select * from json_to_record('{"ia2": [[[1], [2], [3]]]}') as x(ia2 int4[][]); - -select * from json_to_record('{"out": {"key": 1}}') as x(out json); -select * from json_to_record('{"out": [{"key": 1}]}') as x(out json); -select * from json_to_record('{"out": "{\"key\": 1}"}') as x(out json); -select * from json_to_record('{"out": {"key": 1}}') as x(out jsonb); -select * from json_to_record('{"out": [{"key": 1}]}') as x(out jsonb); -select * from json_to_record('{"out": "{\"key\": 1}"}') as x(out jsonb); - --- json_strip_nulls - -select json_strip_nulls(null); - -select json_strip_nulls('1'); - -select json_strip_nulls('"a string"'); - -select json_strip_nulls('null'); - -select json_strip_nulls('[1,2,null,3,4]'); - -select json_strip_nulls('{"a":1,"b":null,"c":[2,null,3],"d":{"e":4,"f":null}}'); - -select json_strip_nulls('[1,{"a":1,"b":null,"c":2},3]'); - --- an empty object is not null and should not be stripped -select json_strip_nulls('{"a": {"b": null, "c": null}, "d": {} }'); - --- json to tsvector -select to_tsvector('{"a": "aaa bbb ddd ccc", "b": ["eee fff ggg"], "c": {"d": "hhh iii"}}'::json); - --- json to tsvector with config -select to_tsvector('simple', '{"a": "aaa bbb ddd ccc", "b": ["eee fff ggg"], "c": {"d": "hhh iii"}}'::json); - --- json to tsvector with stop words -select to_tsvector('english', '{"a": "aaa in bbb ddd ccc", "b": ["the eee fff ggg"], "c": {"d": "hhh. iii"}}'::json); - --- json to tsvector with numeric values -select to_tsvector('english', '{"a": "aaa in bbb ddd ccc", "b": 123, "c": 456}'::json); - --- json_to_tsvector -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"all"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"key"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"string"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"numeric"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"boolean"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '["string", "numeric"]'); - -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"all"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"key"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"string"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"numeric"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '"boolean"'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '["string", "numeric"]'); - --- to_tsvector corner cases -select to_tsvector('""'::json); -select to_tsvector('{}'::json); -select to_tsvector('[]'::json); -select to_tsvector('null'::json); - --- json_to_tsvector corner cases -select json_to_tsvector('""'::json, '"all"'); -select json_to_tsvector('{}'::json, '"all"'); -select json_to_tsvector('[]'::json, '"all"'); -select json_to_tsvector('null'::json, '"all"'); - -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '""'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '{}'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '[]'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, 'null'); -select json_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::json, '["all", null]'); - --- ts_headline for json -select ts_headline('{"a": "aaa bbb", "b": {"c": "ccc ddd fff", "c1": "ccc1 ddd1"}, "d": ["ggg hhh", "iii jjj"]}'::json, tsquery('bbb & ddd & hhh')); -select ts_headline('english', '{"a": "aaa bbb", "b": {"c": "ccc ddd fff"}, "d": ["ggg hhh", "iii jjj"]}'::json, tsquery('bbb & ddd & hhh')); -select ts_headline('{"a": "aaa bbb", "b": {"c": "ccc ddd fff", "c1": "ccc1 ddd1"}, "d": ["ggg hhh", "iii jjj"]}'::json, tsquery('bbb & ddd & hhh'), 'StartSel = <, StopSel = >'); -select ts_headline('english', '{"a": "aaa bbb", "b": {"c": "ccc ddd fff", "c1": "ccc1 ddd1"}, "d": ["ggg hhh", "iii jjj"]}'::json, tsquery('bbb & ddd & hhh'), 'StartSel = <, StopSel = >'); - --- corner cases for ts_headline with json -select ts_headline('null'::json, tsquery('aaa & bbb')); -select ts_headline('{}'::json, tsquery('aaa & bbb')); -select ts_headline('[]'::json, tsquery('aaa & bbb')); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjsonb.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjsonb.sql deleted file mode 100644 index 8d25966267..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjsonb.sql +++ /dev/null @@ -1,1494 +0,0 @@ --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR - -CREATE TABLE testjsonb ( - j jsonb -); - -\set filename :abs_srcdir '/data/jsonb.data' -COPY testjsonb FROM :'filename'; - --- Strings. -SELECT '""'::jsonb; -- OK. -SELECT $$''$$::jsonb; -- ERROR, single quotes are not allowed -SELECT '"abc"'::jsonb; -- OK -SELECT '"abc'::jsonb; -- ERROR, quotes not closed -SELECT '"abc -def"'::jsonb; -- ERROR, unescaped newline in string constant -SELECT '"\n\"\\"'::jsonb; -- OK, legal escapes -SELECT '"\v"'::jsonb; -- ERROR, not a valid JSON escape --- see json_encoding test for input with unicode escapes - --- Numbers. -SELECT '1'::jsonb; -- OK -SELECT '0'::jsonb; -- OK -SELECT '01'::jsonb; -- ERROR, not valid according to JSON spec -SELECT '0.1'::jsonb; -- OK -SELECT '9223372036854775808'::jsonb; -- OK, even though it's too large for int8 -SELECT '1e100'::jsonb; -- OK -SELECT '1.3e100'::jsonb; -- OK -SELECT '1f2'::jsonb; -- ERROR -SELECT '0.x1'::jsonb; -- ERROR -SELECT '1.3ex100'::jsonb; -- ERROR - --- Arrays. -SELECT '[]'::jsonb; -- OK -SELECT '[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]'::jsonb; -- OK -SELECT '[1,2]'::jsonb; -- OK -SELECT '[1,2,]'::jsonb; -- ERROR, trailing comma -SELECT '[1,2'::jsonb; -- ERROR, no closing bracket -SELECT '[1,[2]'::jsonb; -- ERROR, no closing bracket - --- Objects. -SELECT '{}'::jsonb; -- OK -SELECT '{"abc"}'::jsonb; -- ERROR, no value -SELECT '{"abc":1}'::jsonb; -- OK -SELECT '{1:"abc"}'::jsonb; -- ERROR, keys must be strings -SELECT '{"abc",1}'::jsonb; -- ERROR, wrong separator -SELECT '{"abc"=1}'::jsonb; -- ERROR, totally wrong separator -SELECT '{"abc"::1}'::jsonb; -- ERROR, another wrong separator -SELECT '{"abc":1,"def":2,"ghi":[3,4],"hij":{"klm":5,"nop":[6]}}'::jsonb; -- OK -SELECT '{"abc":1:2}'::jsonb; -- ERROR, colon in wrong spot -SELECT '{"abc":1,3}'::jsonb; -- ERROR, no value - --- Recursion. -SET max_stack_depth = '100kB'; -SELECT repeat('[', 10000)::jsonb; -SELECT repeat('{"a":', 10000)::jsonb; -RESET max_stack_depth; - --- Miscellaneous stuff. -SELECT 'true'::jsonb; -- OK -SELECT 'false'::jsonb; -- OK -SELECT 'null'::jsonb; -- OK -SELECT ' true '::jsonb; -- OK, even with extra whitespace -SELECT 'true false'::jsonb; -- ERROR, too many values -SELECT 'true, false'::jsonb; -- ERROR, too many values -SELECT 'truf'::jsonb; -- ERROR, not a keyword -SELECT 'trues'::jsonb; -- ERROR, not a keyword -SELECT ''::jsonb; -- ERROR, no value -SELECT ' '::jsonb; -- ERROR, no value - --- Multi-line JSON input to check ERROR reporting -SELECT '{ - "one": 1, - "two":"two", - "three": - true}'::jsonb; -- OK -SELECT '{ - "one": 1, - "two":,"two", -- ERROR extraneous comma before field "two" - "three": - true}'::jsonb; -SELECT '{ - "one": 1, - "two":"two", - "averyveryveryveryveryveryveryveryveryverylongfieldname":}'::jsonb; --- ERROR missing value for last field - --- make sure jsonb is passed through json generators without being escaped -SELECT array_to_json(ARRAY [jsonb '{"a":1}', jsonb '{"b":[2,3]}']); - --- anyarray column - -CREATE TEMP TABLE rows AS -SELECT x, 'txt' || x as y -FROM generate_series(1,3) AS x; - -analyze rows; - -select attname, to_jsonb(histogram_bounds) histogram_bounds -from pg_stats -where tablename = 'rows' and - schemaname = pg_my_temp_schema()::regnamespace::text -order by 1; - --- to_jsonb, timestamps - -select to_jsonb(timestamp '2014-05-28 12:22:35.614298'); - -BEGIN; -SET LOCAL TIME ZONE 10.5; -select to_jsonb(timestamptz '2014-05-28 12:22:35.614298-04'); -SET LOCAL TIME ZONE -8; -select to_jsonb(timestamptz '2014-05-28 12:22:35.614298-04'); -COMMIT; - -select to_jsonb(date '2014-05-28'); - -select to_jsonb(date 'Infinity'); -select to_jsonb(date '-Infinity'); -select to_jsonb(timestamp 'Infinity'); -select to_jsonb(timestamp '-Infinity'); -select to_jsonb(timestamptz 'Infinity'); -select to_jsonb(timestamptz '-Infinity'); - ---jsonb_agg - -SELECT jsonb_agg(q) - FROM ( SELECT $$a$$ || x AS b, y AS c, - ARRAY[ROW(x.*,ARRAY[1,2,3]), - ROW(y.*,ARRAY[4,5,6])] AS z - FROM generate_series(1,2) x, - generate_series(4,5) y) q; - -SELECT jsonb_agg(q ORDER BY x, y) - FROM rows q; - -UPDATE rows SET x = NULL WHERE x = 1; - -SELECT jsonb_agg(q ORDER BY x NULLS FIRST, y) - FROM rows q; - --- jsonb extraction functions -CREATE TEMP TABLE test_jsonb ( - json_type text, - test_json jsonb -); - -INSERT INTO test_jsonb VALUES -('scalar','"a scalar"'), -('array','["zero", "one","two",null,"four","five", [1,2,3],{"f1":9}]'), -('object','{"field1":"val1","field2":"val2","field3":null, "field4": 4, "field5": [1,2,3], "field6": {"f1":9}}'); - -SELECT test_json -> 'x' FROM test_jsonb WHERE json_type = 'scalar'; -SELECT test_json -> 'x' FROM test_jsonb WHERE json_type = 'array'; -SELECT test_json -> 'x' FROM test_jsonb WHERE json_type = 'object'; -SELECT test_json -> 'field2' FROM test_jsonb WHERE json_type = 'object'; - -SELECT test_json ->> 'field2' FROM test_jsonb WHERE json_type = 'scalar'; -SELECT test_json ->> 'field2' FROM test_jsonb WHERE json_type = 'array'; -SELECT test_json ->> 'field2' FROM test_jsonb WHERE json_type = 'object'; - -SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'scalar'; -SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'array'; -SELECT test_json -> 9 FROM test_jsonb WHERE json_type = 'array'; -SELECT test_json -> 2 FROM test_jsonb WHERE json_type = 'object'; - -SELECT test_json ->> 6 FROM test_jsonb WHERE json_type = 'array'; -SELECT test_json ->> 7 FROM test_jsonb WHERE json_type = 'array'; - -SELECT test_json ->> 'field4' FROM test_jsonb WHERE json_type = 'object'; -SELECT test_json ->> 'field5' FROM test_jsonb WHERE json_type = 'object'; -SELECT test_json ->> 'field6' FROM test_jsonb WHERE json_type = 'object'; - -SELECT test_json ->> 2 FROM test_jsonb WHERE json_type = 'scalar'; -SELECT test_json ->> 2 FROM test_jsonb WHERE json_type = 'array'; -SELECT test_json ->> 2 FROM test_jsonb WHERE json_type = 'object'; - -SELECT jsonb_object_keys(test_json) FROM test_jsonb WHERE json_type = 'scalar'; -SELECT jsonb_object_keys(test_json) FROM test_jsonb WHERE json_type = 'array'; -SELECT jsonb_object_keys(test_json) FROM test_jsonb WHERE json_type = 'object'; - --- nulls -SELECT (test_json->'field3') IS NULL AS expect_false FROM test_jsonb WHERE json_type = 'object'; -SELECT (test_json->>'field3') IS NULL AS expect_true FROM test_jsonb WHERE json_type = 'object'; -SELECT (test_json->3) IS NULL AS expect_false FROM test_jsonb WHERE json_type = 'array'; -SELECT (test_json->>3) IS NULL AS expect_true FROM test_jsonb WHERE json_type = 'array'; - --- corner cases -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> null::text; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> null::int; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> 1; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> 'z'; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb -> ''; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 1; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 3; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb -> 'z'; -select '{"a": "c", "b": null}'::jsonb -> 'b'; -select '"foo"'::jsonb -> 1; -select '"foo"'::jsonb -> 'z'; - -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> null::text; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> null::int; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> 1; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> 'z'; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb ->> ''; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb ->> 1; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb ->> 3; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb ->> 'z'; -select '{"a": "c", "b": null}'::jsonb ->> 'b'; -select '"foo"'::jsonb ->> 1; -select '"foo"'::jsonb ->> 'z'; - --- equality and inequality -SELECT '{"x":"y"}'::jsonb = '{"x":"y"}'::jsonb; -SELECT '{"x":"y"}'::jsonb = '{"x":"z"}'::jsonb; - -SELECT '{"x":"y"}'::jsonb <> '{"x":"y"}'::jsonb; -SELECT '{"x":"y"}'::jsonb <> '{"x":"z"}'::jsonb; - --- containment -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b"}'); -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b", "c":null}'); -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b", "g":null}'); -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"g":null}'); -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"c"}'); -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b"}'); -SELECT jsonb_contains('{"a":"b", "b":1, "c":null}', '{"a":"b", "c":"q"}'); -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b"}'; -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b", "c":null}'; -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b", "g":null}'; -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"g":null}'; -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"c"}'; -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b"}'; -SELECT '{"a":"b", "b":1, "c":null}'::jsonb @> '{"a":"b", "c":"q"}'; - -SELECT '[1,2]'::jsonb @> '[1,2,2]'::jsonb; -SELECT '[1,1,2]'::jsonb @> '[1,2,2]'::jsonb; -SELECT '[[1,2]]'::jsonb @> '[[1,2,2]]'::jsonb; -SELECT '[1,2,2]'::jsonb <@ '[1,2]'::jsonb; -SELECT '[1,2,2]'::jsonb <@ '[1,1,2]'::jsonb; -SELECT '[[1,2,2]]'::jsonb <@ '[[1,2]]'::jsonb; - -SELECT jsonb_contained('{"a":"b"}', '{"a":"b", "b":1, "c":null}'); -SELECT jsonb_contained('{"a":"b", "c":null}', '{"a":"b", "b":1, "c":null}'); -SELECT jsonb_contained('{"a":"b", "g":null}', '{"a":"b", "b":1, "c":null}'); -SELECT jsonb_contained('{"g":null}', '{"a":"b", "b":1, "c":null}'); -SELECT jsonb_contained('{"a":"c"}', '{"a":"b", "b":1, "c":null}'); -SELECT jsonb_contained('{"a":"b"}', '{"a":"b", "b":1, "c":null}'); -SELECT jsonb_contained('{"a":"b", "c":"q"}', '{"a":"b", "b":1, "c":null}'); -SELECT '{"a":"b"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -SELECT '{"a":"b", "c":null}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -SELECT '{"a":"b", "g":null}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -SELECT '{"g":null}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -SELECT '{"a":"c"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -SELECT '{"a":"b"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; -SELECT '{"a":"b", "c":"q"}'::jsonb <@ '{"a":"b", "b":1, "c":null}'; --- Raw scalar may contain another raw scalar, array may contain a raw scalar -SELECT '[5]'::jsonb @> '[5]'; -SELECT '5'::jsonb @> '5'; -SELECT '[5]'::jsonb @> '5'; --- But a raw scalar cannot contain an array -SELECT '5'::jsonb @> '[5]'; --- In general, one thing should always contain itself. Test array containment: -SELECT '["9", ["7", "3"], 1]'::jsonb @> '["9", ["7", "3"], 1]'::jsonb; -SELECT '["9", ["7", "3"], ["1"]]'::jsonb @> '["9", ["7", "3"], ["1"]]'::jsonb; --- array containment string matching confusion bug -SELECT '{ "name": "Bob", "tags": [ "enim", "qui"]}'::jsonb @> '{"tags":["qu"]}'; - --- array length -SELECT jsonb_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]'); -SELECT jsonb_array_length('[]'); -SELECT jsonb_array_length('{"f1":1,"f2":[5,6]}'); -SELECT jsonb_array_length('4'); - --- each -SELECT jsonb_each('{"f1":[1,2,3],"f2":{"f3":1},"f4":null}'); -SELECT jsonb_each('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; -SELECT * FROM jsonb_each('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":99,"f6":"stringy"}') q; -SELECT * FROM jsonb_each('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; - -SELECT jsonb_each_text('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":"null"}'); -SELECT jsonb_each_text('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; -SELECT * FROM jsonb_each_text('{"f1":[1,2,3],"f2":{"f3":1},"f4":null,"f5":99,"f6":"stringy"}') q; -SELECT * FROM jsonb_each_text('{"a":{"b":"c","c":"b","1":"first"},"b":[1,2],"c":"cc","1":"first","n":null}'::jsonb) AS q; - --- exists -SELECT jsonb_exists('{"a":null, "b":"qq"}', 'a'); -SELECT jsonb_exists('{"a":null, "b":"qq"}', 'b'); -SELECT jsonb_exists('{"a":null, "b":"qq"}', 'c'); -SELECT jsonb_exists('{"a":"null", "b":"qq"}', 'a'); -SELECT jsonb '{"a":null, "b":"qq"}' ? 'a'; -SELECT jsonb '{"a":null, "b":"qq"}' ? 'b'; -SELECT jsonb '{"a":null, "b":"qq"}' ? 'c'; -SELECT jsonb '{"a":"null", "b":"qq"}' ? 'a'; --- array exists - array elements should behave as keys -SELECT count(*) from testjsonb WHERE j->'array' ? 'bar'; --- type sensitive array exists - should return no rows (since "exists" only --- matches strings that are either object keys or array elements) -SELECT count(*) from testjsonb WHERE j->'array' ? '5'::text; --- However, a raw scalar is *contained* within the array -SELECT count(*) from testjsonb WHERE j->'array' @> '5'::jsonb; - -SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['a','b']); -SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['b','a']); -SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['c','a']); -SELECT jsonb_exists_any('{"a":null, "b":"qq"}', ARRAY['c','d']); -SELECT jsonb_exists_any('{"a":null, "b":"qq"}', '{}'::text[]); -SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['a','b']; -SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['b','a']; -SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['c','a']; -SELECT jsonb '{"a":null, "b":"qq"}' ?| ARRAY['c','d']; -SELECT jsonb '{"a":null, "b":"qq"}' ?| '{}'::text[]; - -SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['a','b']); -SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['b','a']); -SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['c','a']); -SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['c','d']); -SELECT jsonb_exists_all('{"a":null, "b":"qq"}', '{}'::text[]); -SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['a','b']; -SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['b','a']; -SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['c','a']; -SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['c','d']; -SELECT jsonb '{"a":null, "b":"qq"}' ?& ARRAY['a','a', 'b', 'b', 'b']; -SELECT jsonb '{"a":null, "b":"qq"}' ?& '{}'::text[]; - --- typeof -SELECT jsonb_typeof('{}') AS object; -SELECT jsonb_typeof('{"c":3,"p":"o"}') AS object; -SELECT jsonb_typeof('[]') AS array; -SELECT jsonb_typeof('["a", 1]') AS array; -SELECT jsonb_typeof('null') AS "null"; -SELECT jsonb_typeof('1') AS number; -SELECT jsonb_typeof('-1') AS number; -SELECT jsonb_typeof('1.0') AS number; -SELECT jsonb_typeof('1e2') AS number; -SELECT jsonb_typeof('-1.0') AS number; -SELECT jsonb_typeof('true') AS boolean; -SELECT jsonb_typeof('false') AS boolean; -SELECT jsonb_typeof('"hello"') AS string; -SELECT jsonb_typeof('"true"') AS string; -SELECT jsonb_typeof('"1.0"') AS string; - --- jsonb_build_array, jsonb_build_object, jsonb_object_agg - -SELECT jsonb_build_array('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}'); -SELECT jsonb_build_array('a', NULL); -- ok -SELECT jsonb_build_array(VARIADIC NULL::text[]); -- ok -SELECT jsonb_build_array(VARIADIC '{}'::text[]); -- ok -SELECT jsonb_build_array(VARIADIC '{a,b,c}'::text[]); -- ok -SELECT jsonb_build_array(VARIADIC ARRAY['a', NULL]::text[]); -- ok -SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::text[]); -- ok -SELECT jsonb_build_array(VARIADIC '{1,2,3,4}'::int[]); -- ok -SELECT jsonb_build_array(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok - -SELECT jsonb_build_object('a',1,'b',1.2,'c',true,'d',null,'e',json '{"x": 3, "y": [1,2,3]}'); - -SELECT jsonb_build_object( - 'a', jsonb_build_object('b',false,'c',99), - 'd', jsonb_build_object('e',array[9,8,7]::int[], - 'f', (select row_to_json(r) from ( select relkind, oid::regclass as name from pg_class where relname = 'pg_class') r))); -SELECT jsonb_build_object('{a,b,c}'::text[]); -- error -SELECT jsonb_build_object('{a,b,c}'::text[], '{d,e,f}'::text[]); -- error, key cannot be array -SELECT jsonb_build_object('a', 'b', 'c'); -- error -SELECT jsonb_build_object(NULL, 'a'); -- error, key cannot be NULL -SELECT jsonb_build_object('a', NULL); -- ok -SELECT jsonb_build_object(VARIADIC NULL::text[]); -- ok -SELECT jsonb_build_object(VARIADIC '{}'::text[]); -- ok -SELECT jsonb_build_object(VARIADIC '{a,b,c}'::text[]); -- error -SELECT jsonb_build_object(VARIADIC ARRAY['a', NULL]::text[]); -- ok -SELECT jsonb_build_object(VARIADIC ARRAY[NULL, 'a']::text[]); -- error, key cannot be NULL -SELECT jsonb_build_object(VARIADIC '{1,2,3,4}'::text[]); -- ok -SELECT jsonb_build_object(VARIADIC '{1,2,3,4}'::int[]); -- ok -SELECT jsonb_build_object(VARIADIC '{{1,4},{2,5},{3,6}}'::int[][]); -- ok - --- empty objects/arrays -SELECT jsonb_build_array(); - -SELECT jsonb_build_object(); - --- make sure keys are quoted -SELECT jsonb_build_object(1,2); - --- keys must be scalar and not null -SELECT jsonb_build_object(null,2); - -SELECT jsonb_build_object(r,2) FROM (SELECT 1 AS a, 2 AS b) r; - -SELECT jsonb_build_object(json '{"a":1,"b":2}', 3); - -SELECT jsonb_build_object('{1,2,3}'::int[], 3); - --- handling of NULL values -SELECT jsonb_object_agg(1, NULL::jsonb); -SELECT jsonb_object_agg(NULL, '{"a":1}'); - -CREATE TEMP TABLE foo (serial_num int, name text, type text); -INSERT INTO foo VALUES (847001,'t15','GE1043'); -INSERT INTO foo VALUES (847002,'t16','GE1043'); -INSERT INTO foo VALUES (847003,'sub-alpha','GESS90'); - -SELECT jsonb_build_object('turbines',jsonb_object_agg(serial_num,jsonb_build_object('name',name,'type',type))) -FROM foo; - -SELECT jsonb_object_agg(name, type) FROM foo; - -INSERT INTO foo VALUES (999999, NULL, 'bar'); -SELECT jsonb_object_agg(name, type) FROM foo; - --- jsonb_object - --- empty object, one dimension -SELECT jsonb_object('{}'); - --- empty object, two dimensions -SELECT jsonb_object('{}', '{}'); - --- one dimension -SELECT jsonb_object('{a,1,b,2,3,NULL,"d e f","a b c"}'); - --- same but with two dimensions -SELECT jsonb_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}'); - --- odd number error -SELECT jsonb_object('{a,b,c}'); - --- one column error -SELECT jsonb_object('{{a},{b}}'); - --- too many columns error -SELECT jsonb_object('{{a,b,c},{b,c,d}}'); - --- too many dimensions error -SELECT jsonb_object('{{{a,b},{c,d}},{{b,c},{d,e}}}'); - ---two argument form of jsonb_object - -select jsonb_object('{a,b,c,"d e f"}','{1,2,3,"a b c"}'); - --- too many dimensions -SELECT jsonb_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}', '{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}'); - --- mismatched dimensions - -select jsonb_object('{a,b,c,"d e f",g}','{1,2,3,"a b c"}'); - -select jsonb_object('{a,b,c,"d e f"}','{1,2,3,"a b c",g}'); - --- null key error - -select jsonb_object('{a,b,NULL,"d e f"}','{1,2,3,"a b c"}'); - --- empty key is allowed - -select jsonb_object('{a,b,"","d e f"}','{1,2,3,"a b c"}'); - - - --- extract_path, extract_path_as_text -SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f4','f6'); -SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f2'); -SELECT jsonb_extract_path('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',0::text); -SELECT jsonb_extract_path('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',1::text); -SELECT jsonb_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f4','f6'); -SELECT jsonb_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','f2'); -SELECT jsonb_extract_path_text('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',0::text); -SELECT jsonb_extract_path_text('{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}','f2',1::text); - --- extract_path nulls -SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":{"f5":null,"f6":"stringy"}}','f4','f5') IS NULL AS expect_false; -SELECT jsonb_extract_path_text('{"f2":{"f3":1},"f4":{"f5":null,"f6":"stringy"}}','f4','f5') IS NULL AS expect_true; -SELECT jsonb_extract_path('{"f2":{"f3":1},"f4":[0,1,2,null]}','f4','3') IS NULL AS expect_false; -SELECT jsonb_extract_path_text('{"f2":{"f3":1},"f4":[0,1,2,null]}','f4','3') IS NULL AS expect_true; - --- extract_path operators -SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f4','f6']; -SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f2']; -SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f2','0']; -SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>array['f2','1']; - -SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f4','f6']; -SELECT '{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f2']; -SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f2','0']; -SELECT '{"f2":["f3",1],"f4":{"f5":99,"f6":"stringy"}}'::jsonb#>>array['f2','1']; - --- corner cases for same -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> '{}'; -select '[1,2,3]'::jsonb #> '{}'; -select '"foo"'::jsonb #> '{}'; -select '42'::jsonb #> '{}'; -select 'null'::jsonb #> '{}'; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a', null]; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a', '']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','b']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','b','c']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','b','c','d']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #> array['a','z','c']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #> array['a','1','b']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #> array['a','z','b']; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb #> array['1','b']; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb #> array['z','b']; -select '[{"b": "c"}, {"b": null}]'::jsonb #> array['1','b']; -select '"foo"'::jsonb #> array['z']; -select '42'::jsonb #> array['f2']; -select '42'::jsonb #> array['0']; - -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> '{}'; -select '[1,2,3]'::jsonb #>> '{}'; -select '"foo"'::jsonb #>> '{}'; -select '42'::jsonb #>> '{}'; -select 'null'::jsonb #>> '{}'; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a', null]; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a', '']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','b']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','b','c']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','b','c','d']; -select '{"a": {"b":{"c": "foo"}}}'::jsonb #>> array['a','z','c']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #>> array['a','1','b']; -select '{"a": [{"b": "c"}, {"b": "cc"}]}'::jsonb #>> array['a','z','b']; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb #>> array['1','b']; -select '[{"b": "c"}, {"b": "cc"}]'::jsonb #>> array['z','b']; -select '[{"b": "c"}, {"b": null}]'::jsonb #>> array['1','b']; -select '"foo"'::jsonb #>> array['z']; -select '42'::jsonb #>> array['f2']; -select '42'::jsonb #>> array['0']; - --- array_elements -SELECT jsonb_array_elements('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false]'); -SELECT * FROM jsonb_array_elements('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false]') q; -SELECT jsonb_array_elements_text('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]'); -SELECT * FROM jsonb_array_elements_text('[1,true,[1,[2,3]],null,{"f1":1,"f2":[7,8,9]},false,"stringy"]') q; - --- populate_record -CREATE TYPE jbpop AS (a text, b int, c timestamp); - -CREATE DOMAIN jsb_int_not_null AS int NOT NULL; -CREATE DOMAIN jsb_int_array_1d AS int[] CHECK(array_length(VALUE, 1) = 3); -CREATE DOMAIN jsb_int_array_2d AS int[][] CHECK(array_length(VALUE, 2) = 3); - -create type jb_unordered_pair as (x int, y int); -create domain jb_ordered_pair as jb_unordered_pair check((value).x <= (value).y); - -CREATE TYPE jsbrec AS ( - i int, - ia _int4, - ia1 int[], - ia2 int[][], - ia3 int[][][], - ia1d jsb_int_array_1d, - ia2d jsb_int_array_2d, - t text, - ta text[], - c char(10), - ca char(10)[], - ts timestamp, - js json, - jsb jsonb, - jsa json[], - rec jbpop, - reca jbpop[] -); - -CREATE TYPE jsbrec_i_not_null AS ( - i jsb_int_not_null -); - -SELECT * FROM jsonb_populate_record(NULL::jbpop,'{"a":"blurfl","x":43.2}') q; -SELECT * FROM jsonb_populate_record(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"a":"blurfl","x":43.2}') q; - -SELECT * FROM jsonb_populate_record(NULL::jbpop,'{"a":"blurfl","x":43.2}') q; -SELECT * FROM jsonb_populate_record(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"a":"blurfl","x":43.2}') q; - -SELECT * FROM jsonb_populate_record(NULL::jbpop,'{"a":[100,200,false],"x":43.2}') q; -SELECT * FROM jsonb_populate_record(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"a":[100,200,false],"x":43.2}') q; -SELECT * FROM jsonb_populate_record(row('x',3,'2012-12-31 15:30:56')::jbpop,'{"c":[100,200,false],"x":43.2}') q; - -SELECT * FROM jsonb_populate_record(row('x',3,'2012-12-31 15:30:56')::jbpop, '{}') q; - -SELECT i FROM jsonb_populate_record(NULL::jsbrec_i_not_null, '{"x": 43.2}') q; -SELECT i FROM jsonb_populate_record(NULL::jsbrec_i_not_null, '{"i": null}') q; -SELECT i FROM jsonb_populate_record(NULL::jsbrec_i_not_null, '{"i": 12345}') q; - -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": null}') q; -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": 123}') q; -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": [1, "2", null, 4]}') q; -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": [[1, 2], [3, 4]]}') q; -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": [[1], 2]}') q; -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": [[1], [2, 3]]}') q; -SELECT ia FROM jsonb_populate_record(NULL::jsbrec, '{"ia": "{1,2,3}"}') q; - -SELECT ia1 FROM jsonb_populate_record(NULL::jsbrec, '{"ia1": null}') q; -SELECT ia1 FROM jsonb_populate_record(NULL::jsbrec, '{"ia1": 123}') q; -SELECT ia1 FROM jsonb_populate_record(NULL::jsbrec, '{"ia1": [1, "2", null, 4]}') q; -SELECT ia1 FROM jsonb_populate_record(NULL::jsbrec, '{"ia1": [[1, 2, 3]]}') q; - -SELECT ia1d FROM jsonb_populate_record(NULL::jsbrec, '{"ia1d": null}') q; -SELECT ia1d FROM jsonb_populate_record(NULL::jsbrec, '{"ia1d": 123}') q; -SELECT ia1d FROM jsonb_populate_record(NULL::jsbrec, '{"ia1d": [1, "2", null, 4]}') q; -SELECT ia1d FROM jsonb_populate_record(NULL::jsbrec, '{"ia1d": [1, "2", null]}') q; - -SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [1, "2", null, 4]}') q; -SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [[1, 2], [null, 4]]}') q; -SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [[], []]}') q; -SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [[1, 2], [3]]}') q; -SELECT ia2 FROM jsonb_populate_record(NULL::jsbrec, '{"ia2": [[1, 2], 3, 4]}') q; - -SELECT ia2d FROM jsonb_populate_record(NULL::jsbrec, '{"ia2d": [[1, "2"], [null, 4]]}') q; -SELECT ia2d FROM jsonb_populate_record(NULL::jsbrec, '{"ia2d": [[1, "2", 3], [null, 5, 6]]}') q; - -SELECT ia3 FROM jsonb_populate_record(NULL::jsbrec, '{"ia3": [1, "2", null, 4]}') q; -SELECT ia3 FROM jsonb_populate_record(NULL::jsbrec, '{"ia3": [[1, 2], [null, 4]]}') q; -SELECT ia3 FROM jsonb_populate_record(NULL::jsbrec, '{"ia3": [ [[], []], [[], []], [[], []] ]}') q; -SELECT ia3 FROM jsonb_populate_record(NULL::jsbrec, '{"ia3": [ [[1, 2]], [[3, 4]] ]}') q; -SELECT ia3 FROM jsonb_populate_record(NULL::jsbrec, '{"ia3": [ [[1, 2], [3, 4]], [[5, 6], [7, 8]] ]}') q; -SELECT ia3 FROM jsonb_populate_record(NULL::jsbrec, '{"ia3": [ [[1, 2], [3, 4]], [[5, 6], [7, 8], [9, 10]] ]}') q; - -SELECT ta FROM jsonb_populate_record(NULL::jsbrec, '{"ta": null}') q; -SELECT ta FROM jsonb_populate_record(NULL::jsbrec, '{"ta": 123}') q; -SELECT ta FROM jsonb_populate_record(NULL::jsbrec, '{"ta": [1, "2", null, 4]}') q; -SELECT ta FROM jsonb_populate_record(NULL::jsbrec, '{"ta": [[1, 2, 3], {"k": "v"}]}') q; - -SELECT c FROM jsonb_populate_record(NULL::jsbrec, '{"c": null}') q; -SELECT c FROM jsonb_populate_record(NULL::jsbrec, '{"c": "aaa"}') q; -SELECT c FROM jsonb_populate_record(NULL::jsbrec, '{"c": "aaaaaaaaaa"}') q; -SELECT c FROM jsonb_populate_record(NULL::jsbrec, '{"c": "aaaaaaaaaaaaa"}') q; - -SELECT ca FROM jsonb_populate_record(NULL::jsbrec, '{"ca": null}') q; -SELECT ca FROM jsonb_populate_record(NULL::jsbrec, '{"ca": 123}') q; -SELECT ca FROM jsonb_populate_record(NULL::jsbrec, '{"ca": [1, "2", null, 4]}') q; -SELECT ca FROM jsonb_populate_record(NULL::jsbrec, '{"ca": ["aaaaaaaaaaaaaaaa"]}') q; -SELECT ca FROM jsonb_populate_record(NULL::jsbrec, '{"ca": [[1, 2, 3], {"k": "v"}]}') q; - -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": null}') q; -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": true}') q; -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": 123.45}') q; -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": "123.45"}') q; -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": "abc"}') q; -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": [123, "123", null, {"key": "value"}]}') q; -SELECT js FROM jsonb_populate_record(NULL::jsbrec, '{"js": {"a": "bbb", "b": null, "c": 123.45}}') q; - -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": null}') q; -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": true}') q; -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": 123.45}') q; -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": "123.45"}') q; -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": "abc"}') q; -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": [123, "123", null, {"key": "value"}]}') q; -SELECT jsb FROM jsonb_populate_record(NULL::jsbrec, '{"jsb": {"a": "bbb", "b": null, "c": 123.45}}') q; - -SELECT jsa FROM jsonb_populate_record(NULL::jsbrec, '{"jsa": null}') q; -SELECT jsa FROM jsonb_populate_record(NULL::jsbrec, '{"jsa": 123}') q; -SELECT jsa FROM jsonb_populate_record(NULL::jsbrec, '{"jsa": [1, "2", null, 4]}') q; -SELECT jsa FROM jsonb_populate_record(NULL::jsbrec, '{"jsa": ["aaa", null, [1, 2, "3", {}], { "k" : "v" }]}') q; - -SELECT rec FROM jsonb_populate_record(NULL::jsbrec, '{"rec": 123}') q; -SELECT rec FROM jsonb_populate_record(NULL::jsbrec, '{"rec": [1, 2]}') q; -SELECT rec FROM jsonb_populate_record(NULL::jsbrec, '{"rec": {"a": "abc", "c": "01.02.2003", "x": 43.2}}') q; -SELECT rec FROM jsonb_populate_record(NULL::jsbrec, '{"rec": "(abc,42,01.02.2003)"}') q; - -SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": 123}') q; -SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": [1, 2]}') q; -SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": [{"a": "abc", "b": 456}, null, {"c": "01.02.2003", "x": 43.2}]}') q; -SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": ["(abc,42,01.02.2003)"]}') q; -SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": "{\"(abc,42,01.02.2003)\"}"}') q; - -SELECT rec FROM jsonb_populate_record( - row(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - row('x',3,'2012-12-31 15:30:56')::jbpop,NULL)::jsbrec, - '{"rec": {"a": "abc", "c": "01.02.2003", "x": 43.2}}' -) q; - --- anonymous record type -SELECT jsonb_populate_record(null::record, '{"x": 0, "y": 1}'); -SELECT jsonb_populate_record(row(1,2), '{"f1": 0, "f2": 1}'); -SELECT * FROM - jsonb_populate_record(null::record, '{"x": 776}') AS (x int, y int); - --- composite domain -SELECT jsonb_populate_record(null::jb_ordered_pair, '{"x": 0, "y": 1}'); -SELECT jsonb_populate_record(row(1,2)::jb_ordered_pair, '{"x": 0}'); -SELECT jsonb_populate_record(row(1,2)::jb_ordered_pair, '{"x": 1, "y": 0}'); - --- populate_recordset -SELECT * FROM jsonb_populate_recordset(NULL::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(row('def',99,NULL)::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(NULL::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(row('def',99,NULL)::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(row('def',99,NULL)::jbpop,'[{"a":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(row('def',99,NULL)::jbpop,'[{"c":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; - -SELECT * FROM jsonb_populate_recordset(NULL::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(row('def',99,NULL)::jbpop,'[{"a":"blurfl","x":43.2},{"b":3,"c":"2012-01-20 10:42:53"}]') q; -SELECT * FROM jsonb_populate_recordset(row('def',99,NULL)::jbpop,'[{"a":[100,200,300],"x":43.2},{"a":{"z":true},"b":3,"c":"2012-01-20 10:42:53"}]') q; - --- anonymous record type -SELECT jsonb_populate_recordset(null::record, '[{"x": 0, "y": 1}]'); -SELECT jsonb_populate_recordset(row(1,2), '[{"f1": 0, "f2": 1}]'); -SELECT i, jsonb_populate_recordset(row(i,50), '[{"f1":"42"},{"f2":"43"}]') -FROM (VALUES (1),(2)) v(i); -SELECT * FROM - jsonb_populate_recordset(null::record, '[{"x": 776}]') AS (x int, y int); - --- empty array is a corner case -SELECT jsonb_populate_recordset(null::record, '[]'); -SELECT jsonb_populate_recordset(row(1,2), '[]'); -SELECT * FROM jsonb_populate_recordset(NULL::jbpop,'[]') q; -SELECT * FROM - jsonb_populate_recordset(null::record, '[]') AS (x int, y int); - --- composite domain -SELECT jsonb_populate_recordset(null::jb_ordered_pair, '[{"x": 0, "y": 1}]'); -SELECT jsonb_populate_recordset(row(1,2)::jb_ordered_pair, '[{"x": 0}, {"y": 3}]'); -SELECT jsonb_populate_recordset(row(1,2)::jb_ordered_pair, '[{"x": 1, "y": 0}]'); - --- negative cases where the wrong record type is supplied -select * from jsonb_populate_recordset(row(0::int),'[{"a":"1","b":"2"},{"a":"3"}]') q (a text, b text); -select * from jsonb_populate_recordset(row(0::int,0::int),'[{"a":"1","b":"2"},{"a":"3"}]') q (a text, b text); -select * from jsonb_populate_recordset(row(0::int,0::int,0::int),'[{"a":"1","b":"2"},{"a":"3"}]') q (a text, b text); -select * from jsonb_populate_recordset(row(1000000000::int,50::int),'[{"b":"2"},{"a":"3"}]') q (a text, b text); - --- jsonb_to_record and jsonb_to_recordset - -select * from jsonb_to_record('{"a":1,"b":"foo","c":"bar"}') - as x(a int, b text, d text); - -select * from jsonb_to_recordset('[{"a":1,"b":"foo","d":false},{"a":2,"b":"bar","c":true}]') - as x(a int, b text, c boolean); - -select *, c is null as c_is_null -from jsonb_to_record('{"a":1, "b":{"c":16, "d":2}, "x":8, "ca": ["1 2", 3], "ia": [[1,2],[3,4]], "r": {"a": "aaa", "b": 123}}'::jsonb) - as t(a int, b jsonb, c text, x int, ca char(5)[], ia int[][], r jbpop); - -select *, c is null as c_is_null -from jsonb_to_recordset('[{"a":1, "b":{"c":16, "d":2}, "x":8}]'::jsonb) - as t(a int, b jsonb, c text, x int); - -select * from jsonb_to_record('{"ia": null}') as x(ia _int4); -select * from jsonb_to_record('{"ia": 123}') as x(ia _int4); -select * from jsonb_to_record('{"ia": [1, "2", null, 4]}') as x(ia _int4); -select * from jsonb_to_record('{"ia": [[1, 2], [3, 4]]}') as x(ia _int4); -select * from jsonb_to_record('{"ia": [[1], 2]}') as x(ia _int4); -select * from jsonb_to_record('{"ia": [[1], [2, 3]]}') as x(ia _int4); - -select * from jsonb_to_record('{"ia2": [1, 2, 3]}') as x(ia2 int[][]); -select * from jsonb_to_record('{"ia2": [[1, 2], [3, 4]]}') as x(ia2 int4[][]); -select * from jsonb_to_record('{"ia2": [[[1], [2], [3]]]}') as x(ia2 int4[][]); - -select * from jsonb_to_record('{"out": {"key": 1}}') as x(out json); -select * from jsonb_to_record('{"out": [{"key": 1}]}') as x(out json); -select * from jsonb_to_record('{"out": "{\"key\": 1}"}') as x(out json); -select * from jsonb_to_record('{"out": {"key": 1}}') as x(out jsonb); -select * from jsonb_to_record('{"out": [{"key": 1}]}') as x(out jsonb); -select * from jsonb_to_record('{"out": "{\"key\": 1}"}') as x(out jsonb); - --- test type info caching in jsonb_populate_record() -CREATE TEMP TABLE jsbpoptest (js jsonb); - -INSERT INTO jsbpoptest -SELECT '{ - "jsa": [1, "2", null, 4], - "rec": {"a": "abc", "c": "01.02.2003", "x": 43.2}, - "reca": [{"a": "abc", "b": 456}, null, {"c": "01.02.2003", "x": 43.2}] -}'::jsonb -FROM generate_series(1, 3); - -SELECT (jsonb_populate_record(NULL::jsbrec, js)).* FROM jsbpoptest; - -DROP TYPE jsbrec; -DROP TYPE jsbrec_i_not_null; -DROP DOMAIN jsb_int_not_null; -DROP DOMAIN jsb_int_array_1d; -DROP DOMAIN jsb_int_array_2d; -DROP DOMAIN jb_ordered_pair; -DROP TYPE jb_unordered_pair; - --- indexing -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC"}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC", "public":true}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"age":25}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}'; -SELECT count(*) FROM testjsonb WHERE j ? 'public'; -SELECT count(*) FROM testjsonb WHERE j ? 'bar'; -SELECT count(*) FROM testjsonb WHERE j ?| ARRAY['public','disabled']; -SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled']; -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null'; -SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.bar)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) || exists($.disabled)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)'; -SELECT count(*) FROM testjsonb WHERE j @? '$'; -SELECT count(*) FROM testjsonb WHERE j @? '$.public'; -SELECT count(*) FROM testjsonb WHERE j @? '$.bar'; - -CREATE INDEX jidx ON testjsonb USING gin (j); -SET enable_seqscan = off; - -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC"}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC", "public":true}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"age":25}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"array":["foo"]}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"array":["bar"]}'; --- exercise GIN_SEARCH_MODE_ALL -SELECT count(*) FROM testjsonb WHERE j @> '{}'; -SELECT count(*) FROM testjsonb WHERE j ? 'public'; -SELECT count(*) FROM testjsonb WHERE j ? 'bar'; -SELECT count(*) FROM testjsonb WHERE j ?| ARRAY['public','disabled']; -SELECT count(*) FROM testjsonb WHERE j ?& ARRAY['public','disabled']; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.wait == null))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.wait ? (@ == null))'; -SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "bar"'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.array[*] == "bar"))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array ? (@[*] == "bar"))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array[*] ? (@ == "bar"))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.bar)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) || exists($.disabled)'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.public) && exists($.disabled)'; -EXPLAIN (COSTS OFF) -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.array[*] == "bar")'; -SELECT count(*) FROM testjsonb WHERE j @? '$.array ? (@[*] == "bar")'; -SELECT count(*) FROM testjsonb WHERE j @? '$.array[*] ? (@ == "bar")'; -SELECT count(*) FROM testjsonb WHERE j @? '$'; -SELECT count(*) FROM testjsonb WHERE j @? '$.public'; -SELECT count(*) FROM testjsonb WHERE j @? '$.bar'; - --- array exists - array elements should behave as keys (for GIN index scans too) -CREATE INDEX jidx_array ON testjsonb USING gin((j->'array')); -SELECT count(*) from testjsonb WHERE j->'array' ? 'bar'; --- type sensitive array exists - should return no rows (since "exists" only --- matches strings that are either object keys or array elements) -SELECT count(*) from testjsonb WHERE j->'array' ? '5'::text; --- However, a raw scalar is *contained* within the array -SELECT count(*) from testjsonb WHERE j->'array' @> '5'::jsonb; - -RESET enable_seqscan; - -SELECT count(*) FROM (SELECT (jsonb_each(j)).key FROM testjsonb) AS wow; -SELECT key, count(*) FROM (SELECT (jsonb_each(j)).key FROM testjsonb) AS wow GROUP BY key ORDER BY count DESC, key; - --- sort/hash -SELECT count(distinct j) FROM testjsonb; -SET enable_hashagg = off; -SELECT count(*) FROM (SELECT j FROM (SELECT * FROM testjsonb UNION ALL SELECT * FROM testjsonb) js GROUP BY j) js2; -SET enable_hashagg = on; -SET enable_sort = off; -SELECT count(*) FROM (SELECT j FROM (SELECT * FROM testjsonb UNION ALL SELECT * FROM testjsonb) js GROUP BY j) js2; -SELECT distinct * FROM (values (jsonb '{}' || ''::text),('{}')) v(j); -SET enable_sort = on; - -RESET enable_hashagg; -RESET enable_sort; - -DROP INDEX jidx; -DROP INDEX jidx_array; --- btree -CREATE INDEX jidx ON testjsonb USING btree (j); -SET enable_seqscan = off; - -SELECT count(*) FROM testjsonb WHERE j > '{"p":1}'; -SELECT count(*) FROM testjsonb WHERE j = '{"pos":98, "line":371, "node":"CBA", "indexed":true}'; - ---gin path opclass -DROP INDEX jidx; -CREATE INDEX jidx ON testjsonb USING gin (j jsonb_path_ops); -SET enable_seqscan = off; - -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":null}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC"}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"wait":"CC", "public":true}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"age":25}'; -SELECT count(*) FROM testjsonb WHERE j @> '{"age":25.0}'; --- exercise GIN_SEARCH_MODE_ALL -SELECT count(*) FROM testjsonb WHERE j @> '{}'; - -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == null'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.wait == null))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.wait ? (@ == null))'; -SELECT count(*) FROM testjsonb WHERE j @@ '"CC" == $.wait'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.wait == "CC" && true == $.public'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.age == 25.0'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "foo"'; -SELECT count(*) FROM testjsonb WHERE j @@ '$.array[*] == "bar"'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($ ? (@.array[*] == "bar"))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array ? (@[*] == "bar"))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($.array[*] ? (@ == "bar"))'; -SELECT count(*) FROM testjsonb WHERE j @@ 'exists($)'; - -EXPLAIN (COSTS OFF) -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? (@ == null)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.wait ? ("CC" == @)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.wait == "CC" && true == @.public)'; -SELECT count(*) FROM testjsonb WHERE j @? '$.age ? (@ == 25)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.age == 25.0)'; -SELECT count(*) FROM testjsonb WHERE j @? '$ ? (@.array[*] == "bar")'; -SELECT count(*) FROM testjsonb WHERE j @? '$.array ? (@[*] == "bar")'; -SELECT count(*) FROM testjsonb WHERE j @? '$.array[*] ? (@ == "bar")'; -SELECT count(*) FROM testjsonb WHERE j @? '$'; -SELECT count(*) FROM testjsonb WHERE j @? '$.public'; -SELECT count(*) FROM testjsonb WHERE j @? '$.bar'; - -RESET enable_seqscan; -DROP INDEX jidx; - --- nested tests -SELECT '{"ff":{"a":12,"b":16}}'::jsonb; -SELECT '{"ff":{"a":12,"b":16},"qq":123}'::jsonb; -SELECT '{"aa":["a","aaa"],"qq":{"a":12,"b":16,"c":["c1","c2"],"d":{"d1":"d1","d2":"d2","d1":"d3"}}}'::jsonb; -SELECT '{"aa":["a","aaa"],"qq":{"a":"12","b":"16","c":["c1","c2"],"d":{"d1":"d1","d2":"d2"}}}'::jsonb; -SELECT '{"aa":["a","aaa"],"qq":{"a":"12","b":"16","c":["c1","c2",["c3"],{"c4":4}],"d":{"d1":"d1","d2":"d2"}}}'::jsonb; -SELECT '{"ff":["a","aaa"]}'::jsonb; - -SELECT - '{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'ff', - '{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'qq', - ('{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'Y') IS NULL AS f, - ('{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb ->> 'Y') IS NULL AS t, - '{"ff":{"a":12,"b":16},"qq":123,"x":[1,2],"Y":null}'::jsonb -> 'x'; - --- nested containment -SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[1,2]}'; -SELECT '{"a":[2,1],"c":"b"}'::jsonb @> '{"a":[1,2]}'; -SELECT '{"a":{"1":2},"c":"b"}'::jsonb @> '{"a":[1,2]}'; -SELECT '{"a":{"2":1},"c":"b"}'::jsonb @> '{"a":[1,2]}'; -SELECT '{"a":{"1":2},"c":"b"}'::jsonb @> '{"a":{"1":2}}'; -SELECT '{"a":{"2":1},"c":"b"}'::jsonb @> '{"a":{"1":2}}'; -SELECT '["a","b"]'::jsonb @> '["a","b","c","b"]'; -SELECT '["a","b","c","b"]'::jsonb @> '["a","b"]'; -SELECT '["a","b","c",[1,2]]'::jsonb @> '["a",[1,2]]'; -SELECT '["a","b","c",[1,2]]'::jsonb @> '["b",[1,2]]'; - -SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[1]}'; -SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[2]}'; -SELECT '{"a":[1,2],"c":"b"}'::jsonb @> '{"a":[3]}'; - -SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"c":3}]}'; -SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"x":4}]}'; -SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"x":4},3]}'; -SELECT '{"a":[1,2,{"c":3,"x":4}],"c":"b"}'::jsonb @> '{"a":[{"x":4},1]}'; - --- check some corner cases for indexed nested containment (bug #13756) -create temp table nestjsonb (j jsonb); -insert into nestjsonb (j) values ('{"a":[["b",{"x":1}],["b",{"x":2}]],"c":3}'); -insert into nestjsonb (j) values ('[[14,2,3]]'); -insert into nestjsonb (j) values ('[1,[14,2,3]]'); -create index on nestjsonb using gin(j jsonb_path_ops); - -set enable_seqscan = on; -set enable_bitmapscan = off; -select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb; -select * from nestjsonb where j @> '{"c":3}'; -select * from nestjsonb where j @> '[[14]]'; -set enable_seqscan = off; -set enable_bitmapscan = on; -select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb; -select * from nestjsonb where j @> '{"c":3}'; -select * from nestjsonb where j @> '[[14]]'; -reset enable_seqscan; -reset enable_bitmapscan; - --- nested object field / array index lookup -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'n'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'a'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'b'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'c'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'd'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'd' -> '1'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 'e'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb -> 0; --expecting error - -SELECT '["a","b","c",[1,2],null]'::jsonb -> 0; -SELECT '["a","b","c",[1,2],null]'::jsonb -> 1; -SELECT '["a","b","c",[1,2],null]'::jsonb -> 2; -SELECT '["a","b","c",[1,2],null]'::jsonb -> 3; -SELECT '["a","b","c",[1,2],null]'::jsonb -> 3 -> 1; -SELECT '["a","b","c",[1,2],null]'::jsonb -> 4; -SELECT '["a","b","c",[1,2],null]'::jsonb -> 5; -SELECT '["a","b","c",[1,2],null]'::jsonb -> -1; -SELECT '["a","b","c",[1,2],null]'::jsonb -> -5; -SELECT '["a","b","c",[1,2],null]'::jsonb -> -6; - ---nested path extraction -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{0}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{a}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,0}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,1}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,2}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,3}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,-1}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,-3}'; -SELECT '{"a":"b","c":[1,2,3]}'::jsonb #> '{c,-4}'; - -SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb #> '{0}'; -SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb #> '{3}'; -SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb #> '{4}'; -SELECT '[0,1,2,[3,4],{"5":"five"}]'::jsonb #> '{4,5}'; - ---nested exists -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'n'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'a'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'b'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'c'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'd'; -SELECT '{"n":null,"a":1,"b":[1,2],"c":{"1":2},"d":{"1":[2,3]}}'::jsonb ? 'e'; - --- jsonb_strip_nulls - -select jsonb_strip_nulls(null); - -select jsonb_strip_nulls('1'); - -select jsonb_strip_nulls('"a string"'); - -select jsonb_strip_nulls('null'); - -select jsonb_strip_nulls('[1,2,null,3,4]'); - -select jsonb_strip_nulls('{"a":1,"b":null,"c":[2,null,3],"d":{"e":4,"f":null}}'); - -select jsonb_strip_nulls('[1,{"a":1,"b":null,"c":2},3]'); - --- an empty object is not null and should not be stripped -select jsonb_strip_nulls('{"a": {"b": null, "c": null}, "d": {} }'); - - -select jsonb_pretty('{"a": "test", "b": [1, 2, 3], "c": "test3", "d":{"dd": "test4", "dd2":{"ddd": "test5"}}}'); -select jsonb_pretty('[{"f1":1,"f2":null},2,null,[[{"x":true},6,7],8],3]'); -select jsonb_pretty('{"a":["b", "c"], "d": {"e":"f"}}'); - -select jsonb_concat('{"d": "test", "a": [1, 2]}', '{"g": "test2", "c": {"c1":1, "c2":2}}'); - -select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"cq":"l", "b":"g", "fg":false}'; -select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"aq":"l"}'; -select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"aa":"l"}'; -select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{}'; - -select '["a", "b"]'::jsonb || '["c"]'; -select '["a", "b"]'::jsonb || '["c", "d"]'; -select '["c"]' || '["a", "b"]'::jsonb; - -select '["a", "b"]'::jsonb || '"c"'; -select '"c"' || '["a", "b"]'::jsonb; - -select '[]'::jsonb || '["a"]'::jsonb; -select '[]'::jsonb || '"a"'::jsonb; -select '"b"'::jsonb || '"a"'::jsonb; -select '{}'::jsonb || '{"a":"b"}'::jsonb; -select '[]'::jsonb || '{"a":"b"}'::jsonb; -select '{"a":"b"}'::jsonb || '[]'::jsonb; - -select '"a"'::jsonb || '{"a":1}'; -select '{"a":1}' || '"a"'::jsonb; - -select '[3]'::jsonb || '{}'::jsonb; -select '3'::jsonb || '[]'::jsonb; -select '3'::jsonb || '4'::jsonb; -select '3'::jsonb || '{}'::jsonb; - -select '["a", "b"]'::jsonb || '{"c":1}'; -select '{"c": 1}'::jsonb || '["a", "b"]'; - -select '{}'::jsonb || '{"cq":"l", "b":"g", "fg":false}'; - -select pg_column_size('{}'::jsonb || '{}'::jsonb) = pg_column_size('{}'::jsonb); -select pg_column_size('{"aa":1}'::jsonb || '{"b":2}'::jsonb) = pg_column_size('{"aa":1, "b":2}'::jsonb); -select pg_column_size('{"aa":1, "b":2}'::jsonb || '{}'::jsonb) = pg_column_size('{"aa":1, "b":2}'::jsonb); -select pg_column_size('{}'::jsonb || '{"aa":1, "b":2}'::jsonb) = pg_column_size('{"aa":1, "b":2}'::jsonb); - -select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'a'); -select jsonb_delete('{"a":null , "b":2, "c":3}'::jsonb, 'a'); -select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'b'); -select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'c'); -select jsonb_delete('{"a":1 , "b":2, "c":3}'::jsonb, 'd'); -select '{"a":1 , "b":2, "c":3}'::jsonb - 'a'; -select '{"a":null , "b":2, "c":3}'::jsonb - 'a'; -select '{"a":1 , "b":2, "c":3}'::jsonb - 'b'; -select '{"a":1 , "b":2, "c":3}'::jsonb - 'c'; -select '{"a":1 , "b":2, "c":3}'::jsonb - 'd'; -select pg_column_size('{"a":1 , "b":2, "c":3}'::jsonb - 'b') = pg_column_size('{"a":1, "b":2}'::jsonb); - -select '["a","b","c"]'::jsonb - 3; -select '["a","b","c"]'::jsonb - 2; -select '["a","b","c"]'::jsonb - 1; -select '["a","b","c"]'::jsonb - 0; -select '["a","b","c"]'::jsonb - -1; -select '["a","b","c"]'::jsonb - -2; -select '["a","b","c"]'::jsonb - -3; -select '["a","b","c"]'::jsonb - -4; - -select '{"a":1 , "b":2, "c":3}'::jsonb - '{b}'::text[]; -select '{"a":1 , "b":2, "c":3}'::jsonb - '{c,b}'::text[]; -select '{"a":1 , "b":2, "c":3}'::jsonb - '{}'::text[]; - -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{n}', '[1,2,3]'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '[1,2,3]'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,1,0}', '[1,2,3]'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,NULL,0}', '[1,2,3]'); - -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{n}', '{"1": 2}'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '{"1": 2}'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,1,0}', '{"1": 2}'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{d,NULL,0}', '{"1": 2}'); - -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '"test"'); -select jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb, '{b,-1}', '{"f": "test"}'); - -select jsonb_delete_path('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '{n}'); -select jsonb_delete_path('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '{b,-1}'); -select jsonb_delete_path('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '{d,1,0}'); - -select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb #- '{n}'; -select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb #- '{b,-1}'; -select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb #- '{b,-1e}'; -- invalid array subscript -select '{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}'::jsonb #- '{d,1,0}'; - - --- empty structure and error conditions for delete and replace - -select '"a"'::jsonb - 'a'; -- error -select '{}'::jsonb - 'a'; -select '[]'::jsonb - 'a'; -select '"a"'::jsonb - 1; -- error -select '{}'::jsonb - 1; -- error -select '[]'::jsonb - 1; -select '"a"'::jsonb #- '{a}'; -- error -select '{}'::jsonb #- '{a}'; -select '[]'::jsonb #- '{a}'; -select jsonb_set('"a"','{a}','"b"'); --error -select jsonb_set('{}','{a}','"b"', false); -select jsonb_set('[]','{1}','"b"', false); -select jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0}','[2,3,4]', false); - --- jsonb_set adding instead of replacing - --- prepend to array -select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{b,-33}','{"foo":123}'); --- append to array -select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{b,33}','{"foo":123}'); --- check nesting levels addition -select jsonb_set('{"a":1,"b":[4,5,[0,1,2],6,7],"c":{"d":4}}','{b,2,33}','{"foo":123}'); --- add new key -select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{c,e}','{"foo":123}'); --- adding doesn't do anything if elements before last aren't present -select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{x,-33}','{"foo":123}'); -select jsonb_set('{"a":1,"b":[0,1,2],"c":{"d":4}}','{x,y}','{"foo":123}'); --- add to empty object -select jsonb_set('{}','{x}','{"foo":123}'); ---add to empty array -select jsonb_set('[]','{0}','{"foo":123}'); -select jsonb_set('[]','{99}','{"foo":123}'); -select jsonb_set('[]','{-99}','{"foo":123}'); -select jsonb_set('{"a": [1, 2, 3]}', '{a, non_integer}', '"new_value"'); -select jsonb_set('{"a": {"b": [1, 2, 3]}}', '{a, b, non_integer}', '"new_value"'); -select jsonb_set('{"a": {"b": [1, 2, 3]}}', '{a, b, NULL}', '"new_value"'); - --- jsonb_set_lax - -\pset null NULL - --- pass though non nulls to jsonb_set -select jsonb_set_lax('{"a":1,"b":2}','{b}','5') ; -select jsonb_set_lax('{"a":1,"b":2}','{d}','6', true) ; --- using the default treatment -select jsonb_set_lax('{"a":1,"b":2}','{b}',null); -select jsonb_set_lax('{"a":1,"b":2}','{d}',null,true); --- errors -select jsonb_set_lax('{"a":1,"b":2}', '{b}', null, true, null); -select jsonb_set_lax('{"a":1,"b":2}', '{b}', null, true, 'no_such_treatment'); --- explicit treatments -select jsonb_set_lax('{"a":1,"b":2}', '{b}', null, null_value_treatment => 'raise_exception') as raise_exception; -select jsonb_set_lax('{"a":1,"b":2}', '{b}', null, null_value_treatment => 'return_target') as return_target; -select jsonb_set_lax('{"a":1,"b":2}', '{b}', null, null_value_treatment => 'delete_key') as delete_key; -select jsonb_set_lax('{"a":1,"b":2}', '{b}', null, null_value_treatment => 'use_json_null') as use_json_null; - -\pset null '' - --- jsonb_insert -select jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"'); -select jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"', true); -select jsonb_insert('{"a": {"b": {"c": [0, 1, "test1", "test2"]}}}', '{a, b, c, 2}', '"new_value"'); -select jsonb_insert('{"a": {"b": {"c": [0, 1, "test1", "test2"]}}}', '{a, b, c, 2}', '"new_value"', true); -select jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '{"b": "value"}'); -select jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '["value1", "value2"]'); - --- edge cases -select jsonb_insert('{"a": [0,1,2]}', '{a, 0}', '"new_value"'); -select jsonb_insert('{"a": [0,1,2]}', '{a, 0}', '"new_value"', true); -select jsonb_insert('{"a": [0,1,2]}', '{a, 2}', '"new_value"'); -select jsonb_insert('{"a": [0,1,2]}', '{a, 2}', '"new_value"', true); -select jsonb_insert('{"a": [0,1,2]}', '{a, -1}', '"new_value"'); -select jsonb_insert('{"a": [0,1,2]}', '{a, -1}', '"new_value"', true); -select jsonb_insert('[]', '{1}', '"new_value"'); -select jsonb_insert('[]', '{1}', '"new_value"', true); -select jsonb_insert('{"a": []}', '{a, 1}', '"new_value"'); -select jsonb_insert('{"a": []}', '{a, 1}', '"new_value"', true); -select jsonb_insert('{"a": [0,1,2]}', '{a, 10}', '"new_value"'); -select jsonb_insert('{"a": [0,1,2]}', '{a, -10}', '"new_value"'); - --- jsonb_insert should be able to insert new value for objects, but not to replace -select jsonb_insert('{"a": {"b": "value"}}', '{a, c}', '"new_value"'); -select jsonb_insert('{"a": {"b": "value"}}', '{a, c}', '"new_value"', true); - -select jsonb_insert('{"a": {"b": "value"}}', '{a, b}', '"new_value"'); -select jsonb_insert('{"a": {"b": "value"}}', '{a, b}', '"new_value"', true); - --- jsonb subscript -select ('123'::jsonb)['a']; -select ('123'::jsonb)[0]; -select ('123'::jsonb)[NULL]; -select ('{"a": 1}'::jsonb)['a']; -select ('{"a": 1}'::jsonb)[0]; -select ('{"a": 1}'::jsonb)['not_exist']; -select ('{"a": 1}'::jsonb)[NULL]; -select ('[1, "2", null]'::jsonb)['a']; -select ('[1, "2", null]'::jsonb)[0]; -select ('[1, "2", null]'::jsonb)['1']; -select ('[1, "2", null]'::jsonb)[1.0]; -select ('[1, "2", null]'::jsonb)[2]; -select ('[1, "2", null]'::jsonb)[3]; -select ('[1, "2", null]'::jsonb)[-2]; -select ('[1, "2", null]'::jsonb)[1]['a']; -select ('[1, "2", null]'::jsonb)[1][0]; -select ('{"a": 1, "b": "c", "d": [1, 2, 3]}'::jsonb)['b']; -select ('{"a": 1, "b": "c", "d": [1, 2, 3]}'::jsonb)['d']; -select ('{"a": 1, "b": "c", "d": [1, 2, 3]}'::jsonb)['d'][1]; -select ('{"a": 1, "b": "c", "d": [1, 2, 3]}'::jsonb)['d']['a']; -select ('{"a": {"a1": {"a2": "aaa"}}, "b": "bbb", "c": "ccc"}'::jsonb)['a']['a1']; -select ('{"a": {"a1": {"a2": "aaa"}}, "b": "bbb", "c": "ccc"}'::jsonb)['a']['a1']['a2']; -select ('{"a": {"a1": {"a2": "aaa"}}, "b": "bbb", "c": "ccc"}'::jsonb)['a']['a1']['a2']['a3']; -select ('{"a": ["a1", {"b1": ["aaa", "bbb", "ccc"]}], "b": "bb"}'::jsonb)['a'][1]['b1']; -select ('{"a": ["a1", {"b1": ["aaa", "bbb", "ccc"]}], "b": "bb"}'::jsonb)['a'][1]['b1'][2]; - --- slices are not supported -select ('{"a": 1}'::jsonb)['a':'b']; -select ('[1, "2", null]'::jsonb)[1:2]; -select ('[1, "2", null]'::jsonb)[:2]; -select ('[1, "2", null]'::jsonb)[1:]; -select ('[1, "2", null]'::jsonb)[:]; - -create TEMP TABLE test_jsonb_subscript ( - id int, - test_json jsonb -); - -insert into test_jsonb_subscript values -(1, '{}'), -- empty jsonb -(2, '{"key": "value"}'); -- jsonb with data - --- update empty jsonb -update test_jsonb_subscript set test_json['a'] = '1' where id = 1; -select * from test_jsonb_subscript; - --- update jsonb with some data -update test_jsonb_subscript set test_json['a'] = '1' where id = 2; -select * from test_jsonb_subscript; - --- replace jsonb -update test_jsonb_subscript set test_json['a'] = '"test"'; -select * from test_jsonb_subscript; - --- replace by object -update test_jsonb_subscript set test_json['a'] = '{"b": 1}'::jsonb; -select * from test_jsonb_subscript; - --- replace by array -update test_jsonb_subscript set test_json['a'] = '[1, 2, 3]'::jsonb; -select * from test_jsonb_subscript; - --- use jsonb subscription in where clause -select * from test_jsonb_subscript where test_json['key'] = '"value"'; -select * from test_jsonb_subscript where test_json['key_doesnt_exists'] = '"value"'; -select * from test_jsonb_subscript where test_json['key'] = '"wrong_value"'; - --- NULL -update test_jsonb_subscript set test_json[NULL] = '1'; -update test_jsonb_subscript set test_json['another_key'] = NULL; -select * from test_jsonb_subscript; - --- NULL as jsonb source -insert into test_jsonb_subscript values (3, NULL); -update test_jsonb_subscript set test_json['a'] = '1' where id = 3; -select * from test_jsonb_subscript; - -update test_jsonb_subscript set test_json = NULL where id = 3; -update test_jsonb_subscript set test_json[0] = '1'; -select * from test_jsonb_subscript; - --- Fill the gaps logic -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '[0]'); - -update test_jsonb_subscript set test_json[5] = '1'; -select * from test_jsonb_subscript; - -update test_jsonb_subscript set test_json[-4] = '1'; -select * from test_jsonb_subscript; - -update test_jsonb_subscript set test_json[-8] = '1'; -select * from test_jsonb_subscript; - --- keep consistent values position -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '[]'); - -update test_jsonb_subscript set test_json[5] = '1'; -select * from test_jsonb_subscript; - --- create the whole path -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{}'); -update test_jsonb_subscript set test_json['a'][0]['b'][0]['c'] = '1'; -select * from test_jsonb_subscript; - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{}'); -update test_jsonb_subscript set test_json['a'][2]['b'][2]['c'][2] = '1'; -select * from test_jsonb_subscript; - --- create the whole path with already existing keys -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{"b": 1}'); -update test_jsonb_subscript set test_json['a'][0] = '2'; -select * from test_jsonb_subscript; - --- the start jsonb is an object, first subscript is treated as a key -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{}'); -update test_jsonb_subscript set test_json[0]['a'] = '1'; -select * from test_jsonb_subscript; - --- the start jsonb is an array -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '[]'); -update test_jsonb_subscript set test_json[0]['a'] = '1'; -update test_jsonb_subscript set test_json[2]['b'] = '2'; -select * from test_jsonb_subscript; - --- overwriting an existing path -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{}'); -update test_jsonb_subscript set test_json['a']['b'][1] = '1'; -update test_jsonb_subscript set test_json['a']['b'][10] = '1'; -select * from test_jsonb_subscript; - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '[]'); -update test_jsonb_subscript set test_json[0][0][0] = '1'; -update test_jsonb_subscript set test_json[0][0][1] = '1'; -select * from test_jsonb_subscript; - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{}'); -update test_jsonb_subscript set test_json['a']['b'][10] = '1'; -update test_jsonb_subscript set test_json['a'][10][10] = '1'; -select * from test_jsonb_subscript; - --- an empty sub element - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{"a": {}}'); -update test_jsonb_subscript set test_json['a']['b']['c'][2] = '1'; -select * from test_jsonb_subscript; - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{"a": []}'); -update test_jsonb_subscript set test_json['a'][1]['c'][2] = '1'; -select * from test_jsonb_subscript; - --- trying replace assuming a composite object, but it's an element or a value - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, '{"a": 1}'); -update test_jsonb_subscript set test_json['a']['b'] = '1'; -update test_jsonb_subscript set test_json['a']['b']['c'] = '1'; -update test_jsonb_subscript set test_json['a'][0] = '1'; -update test_jsonb_subscript set test_json['a'][0]['c'] = '1'; -update test_jsonb_subscript set test_json['a'][0][0] = '1'; - --- trying replace assuming a composite object, but it's a raw scalar - -delete from test_jsonb_subscript; -insert into test_jsonb_subscript values (1, 'null'); -update test_jsonb_subscript set test_json[0] = '1'; -update test_jsonb_subscript set test_json[0][0] = '1'; - --- jsonb to tsvector -select to_tsvector('{"a": "aaa bbb ddd ccc", "b": ["eee fff ggg"], "c": {"d": "hhh iii"}}'::jsonb); - --- jsonb to tsvector with config -select to_tsvector('simple', '{"a": "aaa bbb ddd ccc", "b": ["eee fff ggg"], "c": {"d": "hhh iii"}}'::jsonb); - --- jsonb to tsvector with stop words -select to_tsvector('english', '{"a": "aaa in bbb ddd ccc", "b": ["the eee fff ggg"], "c": {"d": "hhh. iii"}}'::jsonb); - --- jsonb to tsvector with numeric values -select to_tsvector('english', '{"a": "aaa in bbb ddd ccc", "b": 123, "c": 456}'::jsonb); - --- jsonb_to_tsvector -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"all"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"key"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"string"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"numeric"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"boolean"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '["string", "numeric"]'); - -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"all"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"key"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"string"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"numeric"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"boolean"'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '["string", "numeric"]'); - --- to_tsvector corner cases -select to_tsvector('""'::jsonb); -select to_tsvector('{}'::jsonb); -select to_tsvector('[]'::jsonb); -select to_tsvector('null'::jsonb); - --- jsonb_to_tsvector corner cases -select jsonb_to_tsvector('""'::jsonb, '"all"'); -select jsonb_to_tsvector('{}'::jsonb, '"all"'); -select jsonb_to_tsvector('[]'::jsonb, '"all"'); -select jsonb_to_tsvector('null'::jsonb, '"all"'); - -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '""'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '{}'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '[]'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, 'null'); -select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '["all", null]'); - --- ts_headline for jsonb -select ts_headline('{"a": "aaa bbb", "b": {"c": "ccc ddd fff", "c1": "ccc1 ddd1"}, "d": ["ggg hhh", "iii jjj"]}'::jsonb, tsquery('bbb & ddd & hhh')); -select ts_headline('english', '{"a": "aaa bbb", "b": {"c": "ccc ddd fff"}, "d": ["ggg hhh", "iii jjj"]}'::jsonb, tsquery('bbb & ddd & hhh')); -select ts_headline('{"a": "aaa bbb", "b": {"c": "ccc ddd fff", "c1": "ccc1 ddd1"}, "d": ["ggg hhh", "iii jjj"]}'::jsonb, tsquery('bbb & ddd & hhh'), 'StartSel = <, StopSel = >'); -select ts_headline('english', '{"a": "aaa bbb", "b": {"c": "ccc ddd fff", "c1": "ccc1 ddd1"}, "d": ["ggg hhh", "iii jjj"]}'::jsonb, tsquery('bbb & ddd & hhh'), 'StartSel = <, StopSel = >'); - --- corner cases for ts_headline with jsonb -select ts_headline('null'::jsonb, tsquery('aaa & bbb')); -select ts_headline('{}'::jsonb, tsquery('aaa & bbb')); -select ts_headline('[]'::jsonb, tsquery('aaa & bbb')); - --- casts -select 'true'::jsonb::bool; -select '[]'::jsonb::bool; -select '1.0'::jsonb::float; -select '[1.0]'::jsonb::float; -select '12345'::jsonb::int4; -select '"hello"'::jsonb::int4; -select '12345'::jsonb::numeric; -select '{}'::jsonb::numeric; -select '12345.05'::jsonb::numeric; -select '12345.05'::jsonb::float4; -select '12345.05'::jsonb::float8; -select '12345.05'::jsonb::int2; -select '12345.05'::jsonb::int4; -select '12345.05'::jsonb::int8; -select '12345.0000000000000000000000000000000000000000000005'::jsonb::numeric; -select '12345.0000000000000000000000000000000000000000000005'::jsonb::float4; -select '12345.0000000000000000000000000000000000000000000005'::jsonb::float8; -select '12345.0000000000000000000000000000000000000000000005'::jsonb::int2; -select '12345.0000000000000000000000000000000000000000000005'::jsonb::int4; -select '12345.0000000000000000000000000000000000000000000005'::jsonb::int8; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjsonb_jsonpath.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjsonb_jsonpath.sql deleted file mode 100644 index 60f73cb059..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fjsonb_jsonpath.sql +++ /dev/null @@ -1,587 +0,0 @@ -select jsonb '{"a": 12}' @? '$'; -select jsonb '{"a": 12}' @? '1'; -select jsonb '{"a": 12}' @? '$.a.b'; -select jsonb '{"a": 12}' @? '$.b'; -select jsonb '{"a": 12}' @? '$.a + 2'; -select jsonb '{"a": 12}' @? '$.b + 2'; -select jsonb '{"a": {"a": 12}}' @? '$.a.a'; -select jsonb '{"a": {"a": 12}}' @? '$.*.a'; -select jsonb '{"b": {"a": 12}}' @? '$.*.a'; -select jsonb '{"b": {"a": 12}}' @? '$.*.b'; -select jsonb '{"b": {"a": 12}}' @? 'strict $.*.b'; -select jsonb '{}' @? '$.*'; -select jsonb '{"a": 1}' @? '$.*'; -select jsonb '{"a": {"b": 1}}' @? 'lax $.**{1}'; -select jsonb '{"a": {"b": 1}}' @? 'lax $.**{2}'; -select jsonb '{"a": {"b": 1}}' @? 'lax $.**{3}'; -select jsonb '[]' @? '$[*]'; -select jsonb '[1]' @? '$[*]'; -select jsonb '[1]' @? '$[1]'; -select jsonb '[1]' @? 'strict $[1]'; -select jsonb_path_query('[1]', 'strict $[1]'); -select jsonb_path_query('[1]', 'strict $[1]', silent => true); -select jsonb '[1]' @? 'lax $[10000000000000000]'; -select jsonb '[1]' @? 'strict $[10000000000000000]'; -select jsonb_path_query('[1]', 'lax $[10000000000000000]'); -select jsonb_path_query('[1]', 'strict $[10000000000000000]'); -select jsonb '[1]' @? '$[0]'; -select jsonb '[1]' @? '$[0.3]'; -select jsonb '[1]' @? '$[0.5]'; -select jsonb '[1]' @? '$[0.9]'; -select jsonb '[1]' @? '$[1.2]'; -select jsonb '[1]' @? 'strict $[1.2]'; -select jsonb '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] > @.b[*])'; -select jsonb '{"a": [1,2,3], "b": [3,4,5]}' @? '$ ? (@.a[*] >= @.b[*])'; -select jsonb '{"a": [1,2,3], "b": [3,4,"5"]}' @? '$ ? (@.a[*] >= @.b[*])'; -select jsonb '{"a": [1,2,3], "b": [3,4,"5"]}' @? 'strict $ ? (@.a[*] >= @.b[*])'; -select jsonb '{"a": [1,2,3], "b": [3,4,null]}' @? '$ ? (@.a[*] >= @.b[*])'; -select jsonb '1' @? '$ ? ((@ == "1") is unknown)'; -select jsonb '1' @? '$ ? ((@ == 1) is unknown)'; -select jsonb '[{"a": 1}, {"a": 2}]' @? '$[0 to 1] ? (@.a > 1)'; - -select jsonb_path_exists('[{"a": 1}, {"a": 2}, 3]', 'lax $[*].a', silent => false); -select jsonb_path_exists('[{"a": 1}, {"a": 2}, 3]', 'lax $[*].a', silent => true); -select jsonb_path_exists('[{"a": 1}, {"a": 2}, 3]', 'strict $[*].a', silent => false); -select jsonb_path_exists('[{"a": 1}, {"a": 2}, 3]', 'strict $[*].a', silent => true); - -select jsonb_path_query('1', 'lax $.a'); -select jsonb_path_query('1', 'strict $.a'); -select jsonb_path_query('1', 'strict $.*'); -select jsonb_path_query('1', 'strict $.a', silent => true); -select jsonb_path_query('1', 'strict $.*', silent => true); -select jsonb_path_query('[]', 'lax $.a'); -select jsonb_path_query('[]', 'strict $.a'); -select jsonb_path_query('[]', 'strict $.a', silent => true); -select jsonb_path_query('{}', 'lax $.a'); -select jsonb_path_query('{}', 'strict $.a'); -select jsonb_path_query('{}', 'strict $.a', silent => true); - -select jsonb_path_query('1', 'strict $[1]'); -select jsonb_path_query('1', 'strict $[*]'); -select jsonb_path_query('[]', 'strict $[1]'); -select jsonb_path_query('[]', 'strict $["a"]'); -select jsonb_path_query('1', 'strict $[1]', silent => true); -select jsonb_path_query('1', 'strict $[*]', silent => true); -select jsonb_path_query('[]', 'strict $[1]', silent => true); -select jsonb_path_query('[]', 'strict $["a"]', silent => true); - -select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.a'); -select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.b'); -select jsonb_path_query('{"a": 12, "b": {"a": 13}}', '$.*'); -select jsonb_path_query('{"a": 12, "b": {"a": 13}}', 'lax $.*.a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[*].*'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[1].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[2].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0,1].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}]', 'lax $[0 to 10 / 0].a'); -select jsonb_path_query('[12, {"a": 13}, {"b": 14}, "ccc", true]', '$[2.5 - 1 to $.size() - 2]'); -select jsonb_path_query('1', 'lax $[0]'); -select jsonb_path_query('1', 'lax $[*]'); -select jsonb_path_query('[1]', 'lax $[0]'); -select jsonb_path_query('[1]', 'lax $[*]'); -select jsonb_path_query('[1,2,3]', 'lax $[*]'); -select jsonb_path_query('[1,2,3]', 'strict $[*].a'); -select jsonb_path_query('[1,2,3]', 'strict $[*].a', silent => true); -select jsonb_path_query('[]', '$[last]'); -select jsonb_path_query('[]', '$[last ? (exists(last))]'); -select jsonb_path_query('[]', 'strict $[last]'); -select jsonb_path_query('[]', 'strict $[last]', silent => true); -select jsonb_path_query('[1]', '$[last]'); -select jsonb_path_query('[1,2,3]', '$[last]'); -select jsonb_path_query('[1,2,3]', '$[last - 1]'); -select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "number")]'); -select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]'); -select jsonb_path_query('[1,2,3]', '$[last ? (@.type() == "string")]', silent => true); - -select * from jsonb_path_query('{"a": 10}', '$'); -select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)'); -select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '1'); -select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '[{"value" : 13}]'); -select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 13}'); -select * from jsonb_path_query('{"a": 10}', '$ ? (@.a < $value)', '{"value" : 8}'); -select * from jsonb_path_query('{"a": 10}', '$.a ? (@ < $value)', '{"value" : 13}'); -select * from jsonb_path_query('[10,11,12,13,14,15]', '$[*] ? (@ < $value)', '{"value" : 13}'); -select * from jsonb_path_query('[10,11,12,13,14,15]', '$[0,1] ? (@ < $x.value)', '{"x": {"value" : 13}}'); -select * from jsonb_path_query('[10,11,12,13,14,15]', '$[0 to 2] ? (@ < $value)', '{"value" : 15}'); -select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == "1")'); -select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : "1"}'); -select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : null}'); -select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ != null)'); -select * from jsonb_path_query('[1, "2", null]', '$[*] ? (@ == null)'); -select * from jsonb_path_query('{}', '$ ? (@ == @)'); -select * from jsonb_path_query('[]', 'strict $ ? (@ == @)'); - -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{2}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{2 to last}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{3 to last}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{last}'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{0 to last}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to 2}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{0 to last}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to last}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{1 to 2}.b ? (@ > 0)'); -select jsonb_path_query('{"a": {"c": {"b": 1}}}', 'lax $.**{2 to 3}.b ? (@ > 0)'); - -select jsonb '{"a": {"b": 1}}' @? '$.**.b ? ( @ > 0)'; -select jsonb '{"a": {"b": 1}}' @? '$.**{0}.b ? ( @ > 0)'; -select jsonb '{"a": {"b": 1}}' @? '$.**{1}.b ? ( @ > 0)'; -select jsonb '{"a": {"b": 1}}' @? '$.**{0 to last}.b ? ( @ > 0)'; -select jsonb '{"a": {"b": 1}}' @? '$.**{1 to last}.b ? ( @ > 0)'; -select jsonb '{"a": {"b": 1}}' @? '$.**{1 to 2}.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{0}.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1}.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{0 to last}.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1 to last}.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{1 to 2}.b ? ( @ > 0)'; -select jsonb '{"a": {"c": {"b": 1}}}' @? '$.**{2 to 3}.b ? ( @ > 0)'; - -select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x))'); -select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.y))'); -select jsonb_path_query('{"g": {"x": 2}}', '$.g ? (exists (@.x ? (@ >= 2) ))'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x + "3"))'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? ((exists (@.x + "3")) is unknown)'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? (exists (@.x))'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g[*] ? ((exists (@.x)) is unknown)'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? (exists (@[*].x))'); -select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'strict $.g ? ((exists (@[*].x)) is unknown)'); - ---test ternary logic -select - x, y, - jsonb_path_query( - '[true, false, null]', - '$[*] ? (@ == true && ($x == true && $y == true) || - @ == false && !($x == true && $y == true) || - @ == null && ($x == true && $y == true) is unknown)', - jsonb_build_object('x', x, 'y', y) - ) as "x && y" -from - (values (jsonb 'true'), ('false'), ('"null"')) x(x), - (values (jsonb 'true'), ('false'), ('"null"')) y(y); - -select - x, y, - jsonb_path_query( - '[true, false, null]', - '$[*] ? (@ == true && ($x == true || $y == true) || - @ == false && !($x == true || $y == true) || - @ == null && ($x == true || $y == true) is unknown)', - jsonb_build_object('x', x, 'y', y) - ) as "x || y" -from - (values (jsonb 'true'), ('false'), ('"null"')) x(x), - (values (jsonb 'true'), ('false'), ('"null"')) y(y); - -select jsonb '{"a": 1, "b":1}' @? '$ ? (@.a == @.b)'; -select jsonb '{"c": {"a": 1, "b":1}}' @? '$ ? (@.a == @.b)'; -select jsonb '{"c": {"a": 1, "b":1}}' @? '$.c ? (@.a == @.b)'; -select jsonb '{"c": {"a": 1, "b":1}}' @? '$.c ? ($.c.a == @.b)'; -select jsonb '{"c": {"a": 1, "b":1}}' @? '$.* ? (@.a == @.b)'; -select jsonb '{"a": 1, "b":1}' @? '$.** ? (@.a == @.b)'; -select jsonb '{"c": {"a": 1, "b":1}}' @? '$.** ? (@.a == @.b)'; - -select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == 1 + 1)'); -select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (1 + 1))'); -select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == @.b + 1)'); -select jsonb_path_query('{"c": {"a": 2, "b":1}}', '$.** ? (@.a == (@.b + 1))'); -select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - 1)'; -select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -1)'; -select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == -@.b)'; -select jsonb '{"c": {"a": -1, "b":1}}' @? '$.** ? (@.a == - @.b)'; -select jsonb '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - @.b)'; -select jsonb '{"c": {"a": 2, "b":1}}' @? '$.** ? (@.a == 1 - - @.b)'; -select jsonb '{"c": {"a": 0, "b":1}}' @? '$.** ? (@.a == 1 - +@.b)'; -select jsonb '[1,2,3]' @? '$ ? (+@[*] > +2)'; -select jsonb '[1,2,3]' @? '$ ? (+@[*] > +3)'; -select jsonb '[1,2,3]' @? '$ ? (-@[*] < -2)'; -select jsonb '[1,2,3]' @? '$ ? (-@[*] < -3)'; -select jsonb '1' @? '$ ? ($ > 0)'; - --- arithmetic errors -select jsonb_path_query('[1,2,0,3]', '$[*] ? (2 / @ > 0)'); -select jsonb_path_query('[1,2,0,3]', '$[*] ? ((2 / @ > 0) is unknown)'); -select jsonb_path_query('0', '1 / $'); -select jsonb_path_query('0', '1 / $ + 2'); -select jsonb_path_query('0', '-(3 + 1 % $)'); -select jsonb_path_query('1', '$ + "2"'); -select jsonb_path_query('[1, 2]', '3 * $'); -select jsonb_path_query('"a"', '-$'); -select jsonb_path_query('[1,"2",3]', '+$'); -select jsonb_path_query('1', '$ + "2"', silent => true); -select jsonb_path_query('[1, 2]', '3 * $', silent => true); -select jsonb_path_query('"a"', '-$', silent => true); -select jsonb_path_query('[1,"2",3]', '+$', silent => true); -select jsonb '["1",2,0,3]' @? '-$[*]'; -select jsonb '[1,"2",0,3]' @? '-$[*]'; -select jsonb '["1",2,0,3]' @? 'strict -$[*]'; -select jsonb '[1,"2",0,3]' @? 'strict -$[*]'; - --- unwrapping of operator arguments in lax mode -select jsonb_path_query('{"a": [2]}', 'lax $.a * 3'); -select jsonb_path_query('{"a": [2]}', 'lax $.a + 3'); -select jsonb_path_query('{"a": [2, 3, 4]}', 'lax -$.a'); --- should fail -select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3'); -select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3', silent => true); - --- extension: boolean expressions -select jsonb_path_query('2', '$ > 1'); -select jsonb_path_query('2', '$ <= 1'); -select jsonb_path_query('2', '$ == "2"'); -select jsonb '2' @? '$ == "2"'; - -select jsonb '2' @@ '$ > 1'; -select jsonb '2' @@ '$ <= 1'; -select jsonb '2' @@ '$ == "2"'; -select jsonb '2' @@ '1'; -select jsonb '{}' @@ '$'; -select jsonb '[]' @@ '$'; -select jsonb '[1,2,3]' @@ '$[*]'; -select jsonb '[]' @@ '$[*]'; -select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] > $x) [1]', '{"x": 1}'); -select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}'); - -select jsonb_path_match('[{"a": 1}, {"a": 2}, 3]', 'lax exists($[*].a)', silent => false); -select jsonb_path_match('[{"a": 1}, {"a": 2}, 3]', 'lax exists($[*].a)', silent => true); -select jsonb_path_match('[{"a": 1}, {"a": 2}, 3]', 'strict exists($[*].a)', silent => false); -select jsonb_path_match('[{"a": 1}, {"a": 2}, 3]', 'strict exists($[*].a)', silent => true); - - -select jsonb_path_query('[null,1,true,"a",[],{}]', '$.type()'); -select jsonb_path_query('[null,1,true,"a",[],{}]', 'lax $.type()'); -select jsonb_path_query('[null,1,true,"a",[],{}]', '$[*].type()'); -select jsonb_path_query('null', 'null.type()'); -select jsonb_path_query('null', 'true.type()'); -select jsonb_path_query('null', '(123).type()'); -select jsonb_path_query('null', '"123".type()'); - -select jsonb_path_query('{"a": 2}', '($.a - 5).abs() + 10'); -select jsonb_path_query('{"a": 2.5}', '-($.a * $.a).floor() % 4.3'); -select jsonb_path_query('[1, 2, 3]', '($[*] > 2) ? (@ == true)'); -select jsonb_path_query('[1, 2, 3]', '($[*] > 3).type()'); -select jsonb_path_query('[1, 2, 3]', '($[*].a > 3).type()'); -select jsonb_path_query('[1, 2, 3]', 'strict ($[*].a > 3).type()'); - -select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'strict $[*].size()'); -select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'strict $[*].size()', silent => true); -select jsonb_path_query('[1,null,true,"11",[],[1],[1,2,3],{},{"a":1,"b":2}]', 'lax $[*].size()'); - -select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].abs()'); -select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].floor()'); -select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling()'); -select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs()'); -select jsonb_path_query('[0, 1, -2, -3.4, 5.6]', '$[*].ceiling().abs().type()'); - -select jsonb_path_query('[{},1]', '$[*].keyvalue()'); -select jsonb_path_query('[{},1]', '$[*].keyvalue()', silent => true); -select jsonb_path_query('{}', '$.keyvalue()'); -select jsonb_path_query('{"a": 1, "b": [1, 2], "c": {"a": "bbb"}}', '$.keyvalue()'); -select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', '$[*].keyvalue()'); -select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue()'); -select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'lax $.keyvalue()'); -select jsonb_path_query('[{"a": 1, "b": [1, 2]}, {"c": {"a": "bbb"}}]', 'strict $.keyvalue().a'); -select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue()'; -select jsonb '{"a": 1, "b": [1, 2]}' @? 'lax $.keyvalue().key'; - -select jsonb_path_query('null', '$.double()'); -select jsonb_path_query('true', '$.double()'); -select jsonb_path_query('null', '$.double()', silent => true); -select jsonb_path_query('true', '$.double()', silent => true); -select jsonb_path_query('[]', '$.double()'); -select jsonb_path_query('[]', 'strict $.double()'); -select jsonb_path_query('{}', '$.double()'); -select jsonb_path_query('[]', 'strict $.double()', silent => true); -select jsonb_path_query('{}', '$.double()', silent => true); -select jsonb_path_query('1.23', '$.double()'); -select jsonb_path_query('"1.23"', '$.double()'); -select jsonb_path_query('"1.23aaa"', '$.double()'); -select jsonb_path_query('1e1000', '$.double()'); -select jsonb_path_query('"nan"', '$.double()'); -select jsonb_path_query('"NaN"', '$.double()'); -select jsonb_path_query('"inf"', '$.double()'); -select jsonb_path_query('"-inf"', '$.double()'); -select jsonb_path_query('"inf"', '$.double()', silent => true); -select jsonb_path_query('"-inf"', '$.double()', silent => true); - -select jsonb_path_query('{}', '$.abs()'); -select jsonb_path_query('true', '$.floor()'); -select jsonb_path_query('"1.2"', '$.ceiling()'); -select jsonb_path_query('{}', '$.abs()', silent => true); -select jsonb_path_query('true', '$.floor()', silent => true); -select jsonb_path_query('"1.2"', '$.ceiling()', silent => true); - -select jsonb_path_query('["", "a", "abc", "abcabc"]', '$[*] ? (@ starts with "abc")'); -select jsonb_path_query('["", "a", "abc", "abcabc"]', 'strict $ ? (@[*] starts with "abc")'); -select jsonb_path_query('["", "a", "abd", "abdabc"]', 'strict $ ? (@[*] starts with "abc")'); -select jsonb_path_query('["abc", "abcabc", null, 1]', 'strict $ ? (@[*] starts with "abc")'); -select jsonb_path_query('["abc", "abcabc", null, 1]', 'strict $ ? ((@[*] starts with "abc") is unknown)'); -select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")'); -select jsonb_path_query('[[null, 1, "abd", "abdabc"]]', 'lax $ ? ((@[*] starts with "abc") is unknown)'); -select jsonb_path_query('[null, 1, "abd", "abdabc"]', 'lax $[*] ? ((@ starts with "abc") is unknown)'); - -select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "babc", "adc\nabc", "ab\nadc"]', 'lax $[*] ? (@ like_regex "^ab.*c")'); -select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "babc", "adc\nabc", "ab\nadc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "i")'); -select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "babc", "adc\nabc", "ab\nadc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "m")'); -select jsonb_path_query('[null, 1, "abc", "abd", "aBdC", "abdacb", "babc", "adc\nabc", "ab\nadc"]', 'lax $[*] ? (@ like_regex "^ab.*c" flag "s")'); -select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "a\\b" flag "q")'); -select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "a\\b" flag "")'); -select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "^a\\b$" flag "q")'); -select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "^a\\B$" flag "q")'); -select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "^a\\B$" flag "iq")'); -select jsonb_path_query('[null, 1, "a\b", "a\\b", "^a\\b$"]', 'lax $[*] ? (@ like_regex "^a\\b$" flag "")'); - -select jsonb_path_query('null', '$.datetime()'); -select jsonb_path_query('true', '$.datetime()'); -select jsonb_path_query('1', '$.datetime()'); -select jsonb_path_query('[]', '$.datetime()'); -select jsonb_path_query('[]', 'strict $.datetime()'); -select jsonb_path_query('{}', '$.datetime()'); -select jsonb_path_query('"bogus"', '$.datetime()'); -select jsonb_path_query('"12:34"', '$.datetime("aaa")'); -select jsonb_path_query('"aaaa"', '$.datetime("HH24")'); - -select jsonb '"10-03-2017"' @? '$.datetime("dd-mm-yyyy")'; -select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy")'); -select jsonb_path_query('"10-03-2017"', '$.datetime("dd-mm-yyyy").type()'); -select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy")'); -select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy").type()'); - -select jsonb_path_query('"10-03-2017 12:34"', ' $.datetime("dd-mm-yyyy HH24:MI").type()'); -select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM").type()'); -select jsonb_path_query('"12:34:56"', '$.datetime("HH24:MI:SS").type()'); -select jsonb_path_query('"12:34:56 +05:20"', '$.datetime("HH24:MI:SS TZH:TZM").type()'); - -select jsonb_path_query('"10-03-2017T12:34:56"', '$.datetime("dd-mm-yyyy\"T\"HH24:MI:SS")'); -select jsonb_path_query('"10-03-2017t12:34:56"', '$.datetime("dd-mm-yyyy\"T\"HH24:MI:SS")'); -select jsonb_path_query('"10-03-2017 12:34:56"', '$.datetime("dd-mm-yyyy\"T\"HH24:MI:SS")'); - -set time zone '+00'; - -select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")'); -select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")'); -select jsonb_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")'); -select jsonb_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")'); -select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")'); -select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")'); -select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")'); -select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH")'); -select jsonb_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")'); -select jsonb_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")'); -select jsonb_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")'); -select jsonb_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")'); - -set time zone '+10'; - -select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI")'); -select jsonb_path_query('"10-03-2017 12:34"', '$.datetime("dd-mm-yyyy HH24:MI TZH")'); -select jsonb_path_query('"10-03-2017 12:34 +05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")'); -select jsonb_path_query('"10-03-2017 12:34 -05"', '$.datetime("dd-mm-yyyy HH24:MI TZH")'); -select jsonb_path_query('"10-03-2017 12:34 +05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")'); -select jsonb_path_query('"10-03-2017 12:34 -05:20"', '$.datetime("dd-mm-yyyy HH24:MI TZH:TZM")'); -select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")'); -select jsonb_path_query('"12:34"', '$.datetime("HH24:MI TZH")'); -select jsonb_path_query('"12:34 +05"', '$.datetime("HH24:MI TZH")'); -select jsonb_path_query('"12:34 -05"', '$.datetime("HH24:MI TZH")'); -select jsonb_path_query('"12:34 +05:20"', '$.datetime("HH24:MI TZH:TZM")'); -select jsonb_path_query('"12:34 -05:20"', '$.datetime("HH24:MI TZH:TZM")'); - -set time zone default; - -select jsonb_path_query('"2017-03-10"', '$.datetime().type()'); -select jsonb_path_query('"2017-03-10"', '$.datetime()'); -select jsonb_path_query('"2017-03-10 12:34:56"', '$.datetime().type()'); -select jsonb_path_query('"2017-03-10 12:34:56"', '$.datetime()'); -select jsonb_path_query('"2017-03-10 12:34:56+3"', '$.datetime().type()'); -select jsonb_path_query('"2017-03-10 12:34:56+3"', '$.datetime()'); -select jsonb_path_query('"2017-03-10 12:34:56+3:10"', '$.datetime().type()'); -select jsonb_path_query('"2017-03-10 12:34:56+3:10"', '$.datetime()'); -select jsonb_path_query('"2017-03-10T12:34:56+3:10"', '$.datetime()'); -select jsonb_path_query('"2017-03-10t12:34:56+3:10"', '$.datetime()'); -select jsonb_path_query('"12:34:56"', '$.datetime().type()'); -select jsonb_path_query('"12:34:56"', '$.datetime()'); -select jsonb_path_query('"12:34:56+3"', '$.datetime().type()'); -select jsonb_path_query('"12:34:56+3"', '$.datetime()'); -select jsonb_path_query('"12:34:56+3:10"', '$.datetime().type()'); -select jsonb_path_query('"12:34:56+3:10"', '$.datetime()'); - -set time zone '+00'; - --- date comparison -select jsonb_path_query( - '["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03+04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03+04", "2017-03-10 03:00:00+03"]', - '$[*].datetime() ? (@ == "10.03.2017".datetime("dd.mm.yyyy"))'); -select jsonb_path_query( - '["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03+04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03+04", "2017-03-10 03:00:00+03"]', - '$[*].datetime() ? (@ >= "10.03.2017".datetime("dd.mm.yyyy"))'); -select jsonb_path_query( - '["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03+04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03+04", "2017-03-10 03:00:00+03"]', - '$[*].datetime() ? (@ < "10.03.2017".datetime("dd.mm.yyyy"))'); -select jsonb_path_query_tz( - '["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03+04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03+04", "2017-03-10 03:00:00+03"]', - '$[*].datetime() ? (@ == "10.03.2017".datetime("dd.mm.yyyy"))'); -select jsonb_path_query_tz( - '["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03+04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03+04", "2017-03-10 03:00:00+03"]', - '$[*].datetime() ? (@ >= "10.03.2017".datetime("dd.mm.yyyy"))'); -select jsonb_path_query_tz( - '["2017-03-10", "2017-03-11", "2017-03-09", "12:34:56", "01:02:03+04", "2017-03-10 00:00:00", "2017-03-10 12:34:56", "2017-03-10 01:02:03+04", "2017-03-10 03:00:00+03"]', - '$[*].datetime() ? (@ < "10.03.2017".datetime("dd.mm.yyyy"))'); - --- time comparison -select jsonb_path_query( - '["12:34:00", "12:35:00", "12:36:00", "12:35:00+00", "12:35:00+01", "13:35:00+01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00+01"]', - '$[*].datetime() ? (@ == "12:35".datetime("HH24:MI"))'); -select jsonb_path_query( - '["12:34:00", "12:35:00", "12:36:00", "12:35:00+00", "12:35:00+01", "13:35:00+01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00+01"]', - '$[*].datetime() ? (@ >= "12:35".datetime("HH24:MI"))'); -select jsonb_path_query( - '["12:34:00", "12:35:00", "12:36:00", "12:35:00+00", "12:35:00+01", "13:35:00+01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00+01"]', - '$[*].datetime() ? (@ < "12:35".datetime("HH24:MI"))'); -select jsonb_path_query_tz( - '["12:34:00", "12:35:00", "12:36:00", "12:35:00+00", "12:35:00+01", "13:35:00+01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00+01"]', - '$[*].datetime() ? (@ == "12:35".datetime("HH24:MI"))'); -select jsonb_path_query_tz( - '["12:34:00", "12:35:00", "12:36:00", "12:35:00+00", "12:35:00+01", "13:35:00+01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00+01"]', - '$[*].datetime() ? (@ >= "12:35".datetime("HH24:MI"))'); -select jsonb_path_query_tz( - '["12:34:00", "12:35:00", "12:36:00", "12:35:00+00", "12:35:00+01", "13:35:00+01", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00+01"]', - '$[*].datetime() ? (@ < "12:35".datetime("HH24:MI"))'); - --- timetz comparison -select jsonb_path_query( - '["12:34:00+01", "12:35:00+01", "12:36:00+01", "12:35:00+02", "12:35:00-02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]', - '$[*].datetime() ? (@ == "12:35 +1".datetime("HH24:MI TZH"))'); -select jsonb_path_query( - '["12:34:00+01", "12:35:00+01", "12:36:00+01", "12:35:00+02", "12:35:00-02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]', - '$[*].datetime() ? (@ >= "12:35 +1".datetime("HH24:MI TZH"))'); -select jsonb_path_query( - '["12:34:00+01", "12:35:00+01", "12:36:00+01", "12:35:00+02", "12:35:00-02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]', - '$[*].datetime() ? (@ < "12:35 +1".datetime("HH24:MI TZH"))'); -select jsonb_path_query_tz( - '["12:34:00+01", "12:35:00+01", "12:36:00+01", "12:35:00+02", "12:35:00-02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]', - '$[*].datetime() ? (@ == "12:35 +1".datetime("HH24:MI TZH"))'); -select jsonb_path_query_tz( - '["12:34:00+01", "12:35:00+01", "12:36:00+01", "12:35:00+02", "12:35:00-02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]', - '$[*].datetime() ? (@ >= "12:35 +1".datetime("HH24:MI TZH"))'); -select jsonb_path_query_tz( - '["12:34:00+01", "12:35:00+01", "12:36:00+01", "12:35:00+02", "12:35:00-02", "10:35:00", "11:35:00", "12:35:00", "2017-03-10", "2017-03-10 12:35:00", "2017-03-10 12:35:00 +1"]', - '$[*].datetime() ? (@ < "12:35 +1".datetime("HH24:MI TZH"))'); - --- timestamp comparison -select jsonb_path_query( - '["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00+01", "2017-03-10 13:35:00+01", "2017-03-10 12:35:00-01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ == "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))'); -select jsonb_path_query( - '["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00+01", "2017-03-10 13:35:00+01", "2017-03-10 12:35:00-01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ >= "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))'); -select jsonb_path_query( - '["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00+01", "2017-03-10 13:35:00+01", "2017-03-10 12:35:00-01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ < "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))'); -select jsonb_path_query_tz( - '["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00+01", "2017-03-10 13:35:00+01", "2017-03-10 12:35:00-01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ == "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))'); -select jsonb_path_query_tz( - '["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00+01", "2017-03-10 13:35:00+01", "2017-03-10 12:35:00-01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ >= "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))'); -select jsonb_path_query_tz( - '["2017-03-10 12:34:00", "2017-03-10 12:35:00", "2017-03-10 12:36:00", "2017-03-10 12:35:00+01", "2017-03-10 13:35:00+01", "2017-03-10 12:35:00-01", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ < "10.03.2017 12:35".datetime("dd.mm.yyyy HH24:MI"))'); - --- timestamptz comparison -select jsonb_path_query( - '["2017-03-10 12:34:00+01", "2017-03-10 12:35:00+01", "2017-03-10 12:36:00+01", "2017-03-10 12:35:00+02", "2017-03-10 12:35:00-02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ == "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))'); -select jsonb_path_query( - '["2017-03-10 12:34:00+01", "2017-03-10 12:35:00+01", "2017-03-10 12:36:00+01", "2017-03-10 12:35:00+02", "2017-03-10 12:35:00-02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ >= "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))'); -select jsonb_path_query( - '["2017-03-10 12:34:00+01", "2017-03-10 12:35:00+01", "2017-03-10 12:36:00+01", "2017-03-10 12:35:00+02", "2017-03-10 12:35:00-02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ < "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))'); -select jsonb_path_query_tz( - '["2017-03-10 12:34:00+01", "2017-03-10 12:35:00+01", "2017-03-10 12:36:00+01", "2017-03-10 12:35:00+02", "2017-03-10 12:35:00-02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ == "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))'); -select jsonb_path_query_tz( - '["2017-03-10 12:34:00+01", "2017-03-10 12:35:00+01", "2017-03-10 12:36:00+01", "2017-03-10 12:35:00+02", "2017-03-10 12:35:00-02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ >= "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))'); -select jsonb_path_query_tz( - '["2017-03-10 12:34:00+01", "2017-03-10 12:35:00+01", "2017-03-10 12:36:00+01", "2017-03-10 12:35:00+02", "2017-03-10 12:35:00-02", "2017-03-10 10:35:00", "2017-03-10 11:35:00", "2017-03-10 12:35:00", "2017-03-10", "2017-03-11", "12:34:56", "12:34:56+01"]', - '$[*].datetime() ? (@ < "10.03.2017 12:35 +1".datetime("dd.mm.yyyy HH24:MI TZH"))'); - --- overflow during comparison -select jsonb_path_query('"1000000-01-01"', '$.datetime() > "2020-01-01 12:00:00".datetime()'::jsonpath); - -set time zone default; - --- jsonpath operators - -SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*]'); -SELECT jsonb_path_query('[{"a": 1}, {"a": 2}]', '$[*] ? (@.a > 10)'); - -SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a'); -SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a'); -SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)'); -SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)'); -SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', vars => '{"min": 1, "max": 4}'); -SELECT jsonb_path_query_array('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', vars => '{"min": 3, "max": 4}'); - -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a'); -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {}]', 'strict $[*].a', silent => true); -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a'); -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ == 1)'); -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 10)'); -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', vars => '{"min": 1, "max": 4}'); -SELECT jsonb_path_query_first('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*].a ? (@ > $min && @ < $max)', vars => '{"min": 3, "max": 4}'); - -SELECT jsonb '[{"a": 1}, {"a": 2}]' @? '$[*].a ? (@ > 1)'; -SELECT jsonb '[{"a": 1}, {"a": 2}]' @? '$[*] ? (@.a > 2)'; -SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}]', '$[*].a ? (@ > 1)'); -SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', vars => '{"min": 1, "max": 4}'); -SELECT jsonb_path_exists('[{"a": 1}, {"a": 2}, {"a": 3}, {"a": 5}]', '$[*] ? (@.a > $min && @.a < $max)', vars => '{"min": 3, "max": 4}'); - -SELECT jsonb_path_match('true', '$', silent => false); -SELECT jsonb_path_match('false', '$', silent => false); -SELECT jsonb_path_match('null', '$', silent => false); -SELECT jsonb_path_match('1', '$', silent => true); -SELECT jsonb_path_match('1', '$', silent => false); -SELECT jsonb_path_match('"a"', '$', silent => false); -SELECT jsonb_path_match('{}', '$', silent => false); -SELECT jsonb_path_match('[true]', '$', silent => false); -SELECT jsonb_path_match('{}', 'lax $.a', silent => false); -SELECT jsonb_path_match('{}', 'strict $.a', silent => false); -SELECT jsonb_path_match('{}', 'strict $.a', silent => true); -SELECT jsonb_path_match('[true, true]', '$[*]', silent => false); -SELECT jsonb '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 1'; -SELECT jsonb '[{"a": 1}, {"a": 2}]' @@ '$[*].a > 2'; -SELECT jsonb_path_match('[{"a": 1}, {"a": 2}]', '$[*].a > 1'); - --- test string comparison (Unicode codepoint collation) -WITH str(j, num) AS -( - SELECT jsonb_build_object('s', s), num - FROM unnest('{"", "a", "ab", "abc", "abcd", "b", "A", "AB", "ABC", "ABc", "ABcD", "B"}'::text[]) WITH ORDINALITY AS a(s, num) -) -SELECT - s1.j, s2.j, - jsonb_path_query_first(s1.j, '$.s < $s', vars => s2.j) lt, - jsonb_path_query_first(s1.j, '$.s <= $s', vars => s2.j) le, - jsonb_path_query_first(s1.j, '$.s == $s', vars => s2.j) eq, - jsonb_path_query_first(s1.j, '$.s >= $s', vars => s2.j) ge, - jsonb_path_query_first(s1.j, '$.s > $s', vars => s2.j) gt -FROM str s1, str s2 -ORDER BY s1.num, s2.num; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flargeobject.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flargeobject.sql deleted file mode 100644 index fd3518889e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flargeobject.sql +++ /dev/null @@ -1,277 +0,0 @@ --- --- Test large object support --- - --- directory paths are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR -\getenv abs_builddir PG_ABS_BUILDDIR - --- ensure consistent test output regardless of the default bytea format -SET bytea_output TO escape; - --- Test ALTER LARGE OBJECT OWNER, GRANT, COMMENT -CREATE ROLE regress_lo_user; -SELECT lo_create(42); -ALTER LARGE OBJECT 42 OWNER TO regress_lo_user; -GRANT SELECT ON LARGE OBJECT 42 TO public; -COMMENT ON LARGE OBJECT 42 IS 'the ultimate answer'; - --- Test psql's \lo_list et al (we assume no other LOs exist yet) -\lo_list -\lo_list+ -\lo_unlink 42 -\dl - --- Load a file -CREATE TABLE lotest_stash_values (loid oid, fd integer); --- lo_creat(mode integer) returns oid --- The mode arg to lo_creat is unused, some vestigal holdover from ancient times --- returns the large object id -INSERT INTO lotest_stash_values (loid) SELECT lo_creat(42); - --- NOTE: large objects require transactions -BEGIN; - --- lo_open(lobjId oid, mode integer) returns integer --- The mode parameter to lo_open uses two constants: --- INV_READ = 0x20000 --- INV_WRITE = 0x40000 --- The return value is a file descriptor-like value which remains valid for the --- transaction. -UPDATE lotest_stash_values SET fd = lo_open(loid, CAST(x'20000' | x'40000' AS integer)); - --- loread/lowrite names are wonky, different from other functions which are lo_* --- lowrite(fd integer, data bytea) returns integer --- the integer is the number of bytes written -SELECT lowrite(fd, ' -I wandered lonely as a cloud -That floats on high o''er vales and hills, -When all at once I saw a crowd, -A host, of golden daffodils; -Beside the lake, beneath the trees, -Fluttering and dancing in the breeze. - -Continuous as the stars that shine -And twinkle on the milky way, -They stretched in never-ending line -Along the margin of a bay: -Ten thousand saw I at a glance, -Tossing their heads in sprightly dance. - -The waves beside them danced; but they -Out-did the sparkling waves in glee: -A poet could not but be gay, -In such a jocund company: -I gazed--and gazed--but little thought -What wealth the show to me had brought: - -For oft, when on my couch I lie -In vacant or in pensive mood, -They flash upon that inward eye -Which is the bliss of solitude; -And then my heart with pleasure fills, -And dances with the daffodils. - - -- William Wordsworth -') FROM lotest_stash_values; - --- lo_close(fd integer) returns integer --- return value is 0 for success, or <0 for error (actually only -1, but...) -SELECT lo_close(fd) FROM lotest_stash_values; - -END; - --- Copy to another large object. --- Note: we intentionally don't remove the object created here; --- it's left behind to help test pg_dump. - -SELECT lo_from_bytea(0, lo_get(loid)) AS newloid FROM lotest_stash_values -\gset - --- Add a comment to it, as well, for pg_dump/pg_upgrade testing. -COMMENT ON LARGE OBJECT :newloid IS 'I Wandered Lonely as a Cloud'; - --- Read out a portion -BEGIN; -UPDATE lotest_stash_values SET fd=lo_open(loid, CAST(x'20000' | x'40000' AS integer)); - --- lo_lseek(fd integer, offset integer, whence integer) returns integer --- offset is in bytes, whence is one of three values: --- SEEK_SET (= 0) meaning relative to beginning --- SEEK_CUR (= 1) meaning relative to current position --- SEEK_END (= 2) meaning relative to end (offset better be negative) --- returns current position in file -SELECT lo_lseek(fd, 104, 0) FROM lotest_stash_values; - --- loread/lowrite names are wonky, different from other functions which are lo_* --- loread(fd integer, len integer) returns bytea -SELECT loread(fd, 28) FROM lotest_stash_values; - -SELECT lo_lseek(fd, -19, 1) FROM lotest_stash_values; - -SELECT lowrite(fd, 'n') FROM lotest_stash_values; - -SELECT lo_tell(fd) FROM lotest_stash_values; - -SELECT lo_lseek(fd, -744, 2) FROM lotest_stash_values; - -SELECT loread(fd, 28) FROM lotest_stash_values; - -SELECT lo_close(fd) FROM lotest_stash_values; - -END; - --- Test resource management -BEGIN; -SELECT lo_open(loid, x'40000'::int) from lotest_stash_values; -ABORT; - -\set filename :abs_builddir '/results/invalid/path' -\set dobody 'DECLARE loid oid; BEGIN ' -\set dobody :dobody 'SELECT tbl.loid INTO loid FROM lotest_stash_values tbl; ' -\set dobody :dobody 'PERFORM lo_export(loid, ' :'filename' '); ' -\set dobody :dobody 'EXCEPTION WHEN UNDEFINED_FILE THEN ' -\set dobody :dobody 'RAISE NOTICE ''could not open file, as expected''; END' -DO :'dobody'; - --- Test truncation. -BEGIN; -UPDATE lotest_stash_values SET fd=lo_open(loid, CAST(x'20000' | x'40000' AS integer)); - -SELECT lo_truncate(fd, 11) FROM lotest_stash_values; -SELECT loread(fd, 15) FROM lotest_stash_values; - -SELECT lo_truncate(fd, 10000) FROM lotest_stash_values; -SELECT loread(fd, 10) FROM lotest_stash_values; -SELECT lo_lseek(fd, 0, 2) FROM lotest_stash_values; -SELECT lo_tell(fd) FROM lotest_stash_values; - -SELECT lo_truncate(fd, 5000) FROM lotest_stash_values; -SELECT lo_lseek(fd, 0, 2) FROM lotest_stash_values; -SELECT lo_tell(fd) FROM lotest_stash_values; - -SELECT lo_close(fd) FROM lotest_stash_values; -END; - --- Test 64-bit large object functions. -BEGIN; -UPDATE lotest_stash_values SET fd = lo_open(loid, CAST(x'20000' | x'40000' AS integer)); - -SELECT lo_lseek64(fd, 4294967296, 0) FROM lotest_stash_values; -SELECT lowrite(fd, 'offset:4GB') FROM lotest_stash_values; -SELECT lo_tell64(fd) FROM lotest_stash_values; - -SELECT lo_lseek64(fd, -10, 1) FROM lotest_stash_values; -SELECT lo_tell64(fd) FROM lotest_stash_values; -SELECT loread(fd, 10) FROM lotest_stash_values; - -SELECT lo_truncate64(fd, 5000000000) FROM lotest_stash_values; -SELECT lo_lseek64(fd, 0, 2) FROM lotest_stash_values; -SELECT lo_tell64(fd) FROM lotest_stash_values; - -SELECT lo_truncate64(fd, 3000000000) FROM lotest_stash_values; -SELECT lo_lseek64(fd, 0, 2) FROM lotest_stash_values; -SELECT lo_tell64(fd) FROM lotest_stash_values; - -SELECT lo_close(fd) FROM lotest_stash_values; -END; - --- lo_unlink(lobjId oid) returns integer --- return value appears to always be 1 -SELECT lo_unlink(loid) from lotest_stash_values; - -TRUNCATE lotest_stash_values; - -\set filename :abs_srcdir '/data/tenk.data' -INSERT INTO lotest_stash_values (loid) SELECT lo_import(:'filename'); - -BEGIN; -UPDATE lotest_stash_values SET fd=lo_open(loid, CAST(x'20000' | x'40000' AS integer)); - --- verify length of large object -SELECT lo_lseek(fd, 0, 2) FROM lotest_stash_values; - --- with the default BLCKSZ, LOBLKSIZE = 2048, so this positions us for a block --- edge case -SELECT lo_lseek(fd, 2030, 0) FROM lotest_stash_values; - --- this should get half of the value from page 0 and half from page 1 of the --- large object -SELECT loread(fd, 36) FROM lotest_stash_values; - -SELECT lo_tell(fd) FROM lotest_stash_values; - -SELECT lo_lseek(fd, -26, 1) FROM lotest_stash_values; - -SELECT lowrite(fd, 'abcdefghijklmnop') FROM lotest_stash_values; - -SELECT lo_lseek(fd, 2030, 0) FROM lotest_stash_values; - -SELECT loread(fd, 36) FROM lotest_stash_values; - -SELECT lo_close(fd) FROM lotest_stash_values; -END; - -\set filename :abs_builddir '/results/lotest.txt' -SELECT lo_export(loid, :'filename') FROM lotest_stash_values; - -\lo_import :filename - -\set newloid :LASTOID - --- just make sure \lo_export does not barf -\set filename :abs_builddir '/results/lotest2.txt' -\lo_export :newloid :filename - --- This is a hack to test that export/import are reversible --- This uses knowledge about the inner workings of large object mechanism --- which should not be used outside it. This makes it a HACK -SELECT pageno, data FROM pg_largeobject WHERE loid = (SELECT loid from lotest_stash_values) -EXCEPT -SELECT pageno, data FROM pg_largeobject WHERE loid = :newloid; - -SELECT lo_unlink(loid) FROM lotest_stash_values; - -TRUNCATE lotest_stash_values; - -\lo_unlink :newloid - -\set filename :abs_builddir '/results/lotest.txt' -\lo_import :filename - -\set newloid_1 :LASTOID - -SELECT lo_from_bytea(0, lo_get(:newloid_1)) AS newloid_2 -\gset - -SELECT md5(lo_get(:newloid_1)) = md5(lo_get(:newloid_2)); - -SELECT lo_get(:newloid_1, 0, 20); -SELECT lo_get(:newloid_1, 10, 20); -SELECT lo_put(:newloid_1, 5, decode('afafafaf', 'hex')); -SELECT lo_get(:newloid_1, 0, 20); - -SELECT lo_put(:newloid_1, 4294967310, 'foo'); -SELECT lo_get(:newloid_1); -SELECT lo_get(:newloid_1, 4294967294, 100); - -\lo_unlink :newloid_1 -\lo_unlink :newloid_2 - --- This object is left in the database for pg_dump test purposes -SELECT lo_from_bytea(0, E'\\xdeadbeef') AS newloid -\gset - -SET bytea_output TO hex; -SELECT lo_get(:newloid); - --- Create one more object that we leave behind for testing pg_dump/pg_upgrade; --- this one intentionally has an OID in the system range -SELECT lo_create(2121); - -COMMENT ON LARGE OBJECT 2121 IS 'testing comments'; - --- Clean up -DROP TABLE lotest_stash_values; - -DROP ROLE regress_lo_user; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flimit.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flimit.sql deleted file mode 100644 index 6f0cda9870..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flimit.sql +++ /dev/null @@ -1,201 +0,0 @@ --- --- LIMIT --- Check the LIMIT/OFFSET feature of SELECT --- - -SELECT ''::text AS two, unique1, unique2, stringu1 - FROM onek WHERE unique1 > 50 - ORDER BY unique1 LIMIT 2; -SELECT ''::text AS five, unique1, unique2, stringu1 - FROM onek WHERE unique1 > 60 - ORDER BY unique1 LIMIT 5; -SELECT ''::text AS two, unique1, unique2, stringu1 - FROM onek WHERE unique1 > 60 AND unique1 < 63 - ORDER BY unique1 LIMIT 5; -SELECT ''::text AS three, unique1, unique2, stringu1 - FROM onek WHERE unique1 > 100 - ORDER BY unique1 LIMIT 3 OFFSET 20; -SELECT ''::text AS zero, unique1, unique2, stringu1 - FROM onek WHERE unique1 < 50 - ORDER BY unique1 DESC LIMIT 8 OFFSET 99; -SELECT ''::text AS eleven, unique1, unique2, stringu1 - FROM onek WHERE unique1 < 50 - ORDER BY unique1 DESC LIMIT 20 OFFSET 39; -SELECT ''::text AS ten, unique1, unique2, stringu1 - FROM onek - ORDER BY unique1 OFFSET 990; -SELECT ''::text AS five, unique1, unique2, stringu1 - FROM onek - ORDER BY unique1 OFFSET 990 LIMIT 5; -SELECT ''::text AS five, unique1, unique2, stringu1 - FROM onek - ORDER BY unique1 LIMIT 5 OFFSET 900; - --- Test null limit and offset. The planner would discard a simple null --- constant, so to ensure executor is exercised, do this: -select * from int8_tbl limit (case when random() < 0.5 then null::bigint end); -select * from int8_tbl offset (case when random() < 0.5 then null::bigint end); - --- Test assorted cases involving backwards fetch from a LIMIT plan node -begin; - -declare c1 cursor for select * from int8_tbl limit 10; -fetch all in c1; -fetch 1 in c1; -fetch backward 1 in c1; -fetch backward all in c1; -fetch backward 1 in c1; -fetch all in c1; - -declare c2 cursor for select * from int8_tbl limit 3; -fetch all in c2; -fetch 1 in c2; -fetch backward 1 in c2; -fetch backward all in c2; -fetch backward 1 in c2; -fetch all in c2; - -declare c3 cursor for select * from int8_tbl offset 3; -fetch all in c3; -fetch 1 in c3; -fetch backward 1 in c3; -fetch backward all in c3; -fetch backward 1 in c3; -fetch all in c3; - -declare c4 cursor for select * from int8_tbl offset 10; -fetch all in c4; -fetch 1 in c4; -fetch backward 1 in c4; -fetch backward all in c4; -fetch backward 1 in c4; -fetch all in c4; - -declare c5 cursor for select * from int8_tbl order by q1 fetch first 2 rows with ties; -fetch all in c5; -fetch 1 in c5; -fetch backward 1 in c5; -fetch backward 1 in c5; -fetch all in c5; -fetch backward all in c5; -fetch all in c5; -fetch backward all in c5; - -rollback; - --- Stress test for variable LIMIT in conjunction with bounded-heap sorting - -SELECT - (SELECT n - FROM (VALUES (1)) AS x, - (SELECT n FROM generate_series(1,10) AS n - ORDER BY n LIMIT 1 OFFSET s-1) AS y) AS z - FROM generate_series(1,10) AS s; - --- --- Test behavior of volatile and set-returning functions in conjunction --- with ORDER BY and LIMIT. --- - -create temp sequence testseq; - -explain (verbose, costs off) -select unique1, unique2, nextval('testseq') - from tenk1 order by unique2 limit 10; - -select unique1, unique2, nextval('testseq') - from tenk1 order by unique2 limit 10; - -select currval('testseq'); - -explain (verbose, costs off) -select unique1, unique2, nextval('testseq') - from tenk1 order by tenthous limit 10; - -select unique1, unique2, nextval('testseq') - from tenk1 order by tenthous limit 10; - -select currval('testseq'); - -explain (verbose, costs off) -select unique1, unique2, generate_series(1,10) - from tenk1 order by unique2 limit 7; - -select unique1, unique2, generate_series(1,10) - from tenk1 order by unique2 limit 7; - -explain (verbose, costs off) -select unique1, unique2, generate_series(1,10) - from tenk1 order by tenthous limit 7; - -select unique1, unique2, generate_series(1,10) - from tenk1 order by tenthous limit 7; - --- use of random() is to keep planner from folding the expressions together -explain (verbose, costs off) -select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; - -select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2; - -explain (verbose, costs off) -select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2 -order by s2 desc; - -select generate_series(0,2) as s1, generate_series((random()*.1)::int,2) as s2 -order by s2 desc; - --- test for failure to set all aggregates' aggtranstype -explain (verbose, costs off) -select sum(tenthous) as s1, sum(tenthous) + random()*0 as s2 - from tenk1 group by thousand order by thousand limit 3; - -select sum(tenthous) as s1, sum(tenthous) + random()*0 as s2 - from tenk1 group by thousand order by thousand limit 3; - --- --- FETCH FIRST --- Check the WITH TIES clause --- - -SELECT thousand - FROM onek WHERE thousand < 5 - ORDER BY thousand FETCH FIRST 2 ROW WITH TIES; - -SELECT thousand - FROM onek WHERE thousand < 5 - ORDER BY thousand FETCH FIRST ROWS WITH TIES; - -SELECT thousand - FROM onek WHERE thousand < 5 - ORDER BY thousand FETCH FIRST 1 ROW WITH TIES; - -SELECT thousand - FROM onek WHERE thousand < 5 - ORDER BY thousand FETCH FIRST 2 ROW ONLY; - --- SKIP LOCKED and WITH TIES are incompatible -SELECT thousand - FROM onek WHERE thousand < 5 - ORDER BY thousand FETCH FIRST 1 ROW WITH TIES FOR UPDATE SKIP LOCKED; - --- should fail -SELECT ''::text AS two, unique1, unique2, stringu1 - FROM onek WHERE unique1 > 50 - FETCH FIRST 2 ROW WITH TIES; - --- test ruleutils -CREATE VIEW limit_thousand_v_1 AS SELECT thousand FROM onek WHERE thousand < 995 - ORDER BY thousand FETCH FIRST 5 ROWS WITH TIES OFFSET 10; -\d+ limit_thousand_v_1 -CREATE VIEW limit_thousand_v_2 AS SELECT thousand FROM onek WHERE thousand < 995 - ORDER BY thousand OFFSET 10 FETCH FIRST 5 ROWS ONLY; -\d+ limit_thousand_v_2 -CREATE VIEW limit_thousand_v_3 AS SELECT thousand FROM onek WHERE thousand < 995 - ORDER BY thousand FETCH FIRST NULL ROWS WITH TIES; -- fails -CREATE VIEW limit_thousand_v_3 AS SELECT thousand FROM onek WHERE thousand < 995 - ORDER BY thousand FETCH FIRST (NULL+1) ROWS WITH TIES; -\d+ limit_thousand_v_3 -CREATE VIEW limit_thousand_v_4 AS SELECT thousand FROM onek WHERE thousand < 995 - ORDER BY thousand FETCH FIRST NULL ROWS ONLY; -\d+ limit_thousand_v_4 --- leave these views diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flock.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flock.sql deleted file mode 100644 index b88488c6d0..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Flock.sql +++ /dev/null @@ -1,200 +0,0 @@ --- --- Test the LOCK statement --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - --- Setup -CREATE SCHEMA lock_schema1; -SET search_path = lock_schema1; -CREATE TABLE lock_tbl1 (a BIGINT); -CREATE TABLE lock_tbl1a (a BIGINT); -CREATE VIEW lock_view1 AS SELECT * FROM lock_tbl1; -CREATE VIEW lock_view2(a,b) AS SELECT * FROM lock_tbl1, lock_tbl1a; -CREATE VIEW lock_view3 AS SELECT * from lock_view2; -CREATE VIEW lock_view4 AS SELECT (select a from lock_tbl1a limit 1) from lock_tbl1; -CREATE VIEW lock_view5 AS SELECT * from lock_tbl1 where a in (select * from lock_tbl1a); -CREATE VIEW lock_view6 AS SELECT * from (select * from lock_tbl1) sub; -CREATE ROLE regress_rol_lock1; -ALTER ROLE regress_rol_lock1 SET search_path = lock_schema1; -GRANT USAGE ON SCHEMA lock_schema1 TO regress_rol_lock1; - --- Try all valid lock options; also try omitting the optional TABLE keyword. -BEGIN TRANSACTION; -LOCK TABLE lock_tbl1 IN ACCESS SHARE MODE; -LOCK lock_tbl1 IN ROW SHARE MODE; -LOCK TABLE lock_tbl1 IN ROW EXCLUSIVE MODE; -LOCK TABLE lock_tbl1 IN SHARE UPDATE EXCLUSIVE MODE; -LOCK TABLE lock_tbl1 IN SHARE MODE; -LOCK lock_tbl1 IN SHARE ROW EXCLUSIVE MODE; -LOCK TABLE lock_tbl1 IN EXCLUSIVE MODE; -LOCK TABLE lock_tbl1 IN ACCESS EXCLUSIVE MODE; -ROLLBACK; - --- Try using NOWAIT along with valid options. -BEGIN TRANSACTION; -LOCK TABLE lock_tbl1 IN ACCESS SHARE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN ROW SHARE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN ROW EXCLUSIVE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN SHARE UPDATE EXCLUSIVE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN SHARE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN SHARE ROW EXCLUSIVE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN EXCLUSIVE MODE NOWAIT; -LOCK TABLE lock_tbl1 IN ACCESS EXCLUSIVE MODE NOWAIT; -ROLLBACK; - --- Verify that we can lock views. -BEGIN TRANSACTION; -LOCK TABLE lock_view1 IN EXCLUSIVE MODE; --- lock_view1 and lock_tbl1 are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'ExclusiveLock' - order by relname; -ROLLBACK; -BEGIN TRANSACTION; -LOCK TABLE lock_view2 IN EXCLUSIVE MODE; --- lock_view1, lock_tbl1, and lock_tbl1a are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'ExclusiveLock' - order by relname; -ROLLBACK; -BEGIN TRANSACTION; -LOCK TABLE lock_view3 IN EXCLUSIVE MODE; --- lock_view3, lock_view2, lock_tbl1, and lock_tbl1a are locked recursively. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'ExclusiveLock' - order by relname; -ROLLBACK; -BEGIN TRANSACTION; -LOCK TABLE lock_view4 IN EXCLUSIVE MODE; --- lock_view4, lock_tbl1, and lock_tbl1a are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'ExclusiveLock' - order by relname; -ROLLBACK; -BEGIN TRANSACTION; -LOCK TABLE lock_view5 IN EXCLUSIVE MODE; --- lock_view5, lock_tbl1, and lock_tbl1a are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'ExclusiveLock' - order by relname; -ROLLBACK; -BEGIN TRANSACTION; -LOCK TABLE lock_view6 IN EXCLUSIVE MODE; --- lock_view6 an lock_tbl1 are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'ExclusiveLock' - order by relname; -ROLLBACK; --- Verify that we cope with infinite recursion in view definitions. -CREATE OR REPLACE VIEW lock_view2 AS SELECT * from lock_view3; -BEGIN TRANSACTION; -LOCK TABLE lock_view2 IN EXCLUSIVE MODE; -ROLLBACK; -CREATE VIEW lock_view7 AS SELECT * from lock_view2; -BEGIN TRANSACTION; -LOCK TABLE lock_view7 IN EXCLUSIVE MODE; -ROLLBACK; - --- Verify that we can lock a table with inheritance children. -CREATE TABLE lock_tbl2 (b BIGINT) INHERITS (lock_tbl1); -CREATE TABLE lock_tbl3 () INHERITS (lock_tbl2); -BEGIN TRANSACTION; -LOCK TABLE lock_tbl1 * IN ACCESS EXCLUSIVE MODE; -ROLLBACK; - --- Child tables are locked without granting explicit permission to do so as --- long as we have permission to lock the parent. -GRANT UPDATE ON TABLE lock_tbl1 TO regress_rol_lock1; -SET ROLE regress_rol_lock1; --- fail when child locked directly -BEGIN; -LOCK TABLE lock_tbl2; -ROLLBACK; -BEGIN; -LOCK TABLE lock_tbl1 * IN ACCESS EXCLUSIVE MODE; -ROLLBACK; -BEGIN; -LOCK TABLE ONLY lock_tbl1; -ROLLBACK; -RESET ROLE; -REVOKE UPDATE ON TABLE lock_tbl1 FROM regress_rol_lock1; - --- Tables referred to by views are locked without explicit permission to do so --- as long as we have permission to lock the view itself. -SET ROLE regress_rol_lock1; --- fail without permissions on the view -BEGIN; -LOCK TABLE lock_view1; -ROLLBACK; -RESET ROLE; -GRANT UPDATE ON TABLE lock_view1 TO regress_rol_lock1; -SET ROLE regress_rol_lock1; -BEGIN; -LOCK TABLE lock_view1 IN ACCESS EXCLUSIVE MODE; --- lock_view1 and lock_tbl1 (plus children lock_tbl2 and lock_tbl3) are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'AccessExclusiveLock' - order by relname; -ROLLBACK; -RESET ROLE; -REVOKE UPDATE ON TABLE lock_view1 FROM regress_rol_lock1; - --- Tables referred to by security invoker views require explicit permission to --- be locked. -CREATE VIEW lock_view8 WITH (security_invoker) AS SELECT * FROM lock_tbl1; -SET ROLE regress_rol_lock1; --- fail without permissions on the view -BEGIN; -LOCK TABLE lock_view8; -ROLLBACK; -RESET ROLE; -GRANT UPDATE ON TABLE lock_view8 TO regress_rol_lock1; -SET ROLE regress_rol_lock1; --- fail without permissions on the table referenced by the view -BEGIN; -LOCK TABLE lock_view8; -ROLLBACK; -RESET ROLE; -GRANT UPDATE ON TABLE lock_tbl1 TO regress_rol_lock1; -BEGIN; -LOCK TABLE lock_view8 IN ACCESS EXCLUSIVE MODE; --- lock_view8 and lock_tbl1 (plus children lock_tbl2 and lock_tbl3) are locked. -select relname from pg_locks l, pg_class c - where l.relation = c.oid and relname like '%lock_%' and mode = 'AccessExclusiveLock' - order by relname; -ROLLBACK; -RESET ROLE; -REVOKE UPDATE ON TABLE lock_view8 FROM regress_rol_lock1; - --- --- Clean up --- -DROP VIEW lock_view8; -DROP VIEW lock_view7; -DROP VIEW lock_view6; -DROP VIEW lock_view5; -DROP VIEW lock_view4; -DROP VIEW lock_view3 CASCADE; -DROP VIEW lock_view1; -DROP TABLE lock_tbl3; -DROP TABLE lock_tbl2; -DROP TABLE lock_tbl1; -DROP TABLE lock_tbl1a; -DROP SCHEMA lock_schema1 CASCADE; -DROP ROLE regress_rol_lock1; - - --- atomic ops tests -RESET search_path; - -CREATE FUNCTION test_atomic_ops() - RETURNS bool - AS :'regresslib' - LANGUAGE C; - -SELECT test_atomic_ops(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmatview.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmatview.sql deleted file mode 100644 index 68b9ccfd45..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmatview.sql +++ /dev/null @@ -1,297 +0,0 @@ --- create a table to use as a basis for views and materialized views in various combinations -CREATE TABLE mvtest_t (id int NOT NULL PRIMARY KEY, type text NOT NULL, amt numeric NOT NULL); -INSERT INTO mvtest_t VALUES - (1, 'x', 2), - (2, 'x', 3), - (3, 'y', 5), - (4, 'y', 7), - (5, 'z', 11); - --- we want a view based on the table, too, since views present additional challenges -CREATE VIEW mvtest_tv AS SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type; -SELECT * FROM mvtest_tv ORDER BY type; - --- create a materialized view with no data, and confirm correct behavior -EXPLAIN (costs off) - CREATE MATERIALIZED VIEW mvtest_tm AS SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type WITH NO DATA; -CREATE MATERIALIZED VIEW mvtest_tm AS SELECT type, sum(amt) AS totamt FROM mvtest_t GROUP BY type WITH NO DATA; -SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass; -SELECT * FROM mvtest_tm ORDER BY type; -REFRESH MATERIALIZED VIEW mvtest_tm; -SELECT relispopulated FROM pg_class WHERE oid = 'mvtest_tm'::regclass; -CREATE UNIQUE INDEX mvtest_tm_type ON mvtest_tm (type); -SELECT * FROM mvtest_tm ORDER BY type; - --- create various views -EXPLAIN (costs off) - CREATE MATERIALIZED VIEW mvtest_tvm AS SELECT * FROM mvtest_tv ORDER BY type; -CREATE MATERIALIZED VIEW mvtest_tvm AS SELECT * FROM mvtest_tv ORDER BY type; -SELECT * FROM mvtest_tvm; -CREATE MATERIALIZED VIEW mvtest_tmm AS SELECT sum(totamt) AS grandtot FROM mvtest_tm; -CREATE MATERIALIZED VIEW mvtest_tvmm AS SELECT sum(totamt) AS grandtot FROM mvtest_tvm; -CREATE UNIQUE INDEX mvtest_tvmm_expr ON mvtest_tvmm ((grandtot > 0)); -CREATE UNIQUE INDEX mvtest_tvmm_pred ON mvtest_tvmm (grandtot) WHERE grandtot < 0; -CREATE VIEW mvtest_tvv AS SELECT sum(totamt) AS grandtot FROM mvtest_tv; -EXPLAIN (costs off) - CREATE MATERIALIZED VIEW mvtest_tvvm AS SELECT * FROM mvtest_tvv; -CREATE MATERIALIZED VIEW mvtest_tvvm AS SELECT * FROM mvtest_tvv; -CREATE VIEW mvtest_tvvmv AS SELECT * FROM mvtest_tvvm; -CREATE MATERIALIZED VIEW mvtest_bb AS SELECT * FROM mvtest_tvvmv; -CREATE INDEX mvtest_aa ON mvtest_bb (grandtot); - --- check that plans seem reasonable -\d+ mvtest_tvm -\d+ mvtest_tvm -\d+ mvtest_tvvm -\d+ mvtest_bb - --- test schema behavior -CREATE SCHEMA mvtest_mvschema; -ALTER MATERIALIZED VIEW mvtest_tvm SET SCHEMA mvtest_mvschema; -\d+ mvtest_tvm -\d+ mvtest_tvmm -SET search_path = mvtest_mvschema, public; -\d+ mvtest_tvm - --- modify the underlying table data -INSERT INTO mvtest_t VALUES (6, 'z', 13); - --- confirm pre- and post-refresh contents of fairly simple materialized views -SELECT * FROM mvtest_tm ORDER BY type; -SELECT * FROM mvtest_tvm ORDER BY type; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_tm; -REFRESH MATERIALIZED VIEW mvtest_tvm; -SELECT * FROM mvtest_tm ORDER BY type; -SELECT * FROM mvtest_tvm ORDER BY type; -RESET search_path; - --- confirm pre- and post-refresh contents of nested materialized views -EXPLAIN (costs off) - SELECT * FROM mvtest_tmm; -EXPLAIN (costs off) - SELECT * FROM mvtest_tvmm; -EXPLAIN (costs off) - SELECT * FROM mvtest_tvvm; -SELECT * FROM mvtest_tmm; -SELECT * FROM mvtest_tvmm; -SELECT * FROM mvtest_tvvm; -REFRESH MATERIALIZED VIEW mvtest_tmm; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_tvmm; -REFRESH MATERIALIZED VIEW mvtest_tvmm; -REFRESH MATERIALIZED VIEW mvtest_tvvm; -EXPLAIN (costs off) - SELECT * FROM mvtest_tmm; -EXPLAIN (costs off) - SELECT * FROM mvtest_tvmm; -EXPLAIN (costs off) - SELECT * FROM mvtest_tvvm; -SELECT * FROM mvtest_tmm; -SELECT * FROM mvtest_tvmm; -SELECT * FROM mvtest_tvvm; - --- test diemv when the mv does not exist -DROP MATERIALIZED VIEW IF EXISTS no_such_mv; - --- make sure invalid combination of options is prohibited -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_tvmm WITH NO DATA; - --- no tuple locks on materialized views -SELECT * FROM mvtest_tvvm FOR SHARE; - --- test join of mv and view -SELECT type, m.totamt AS mtot, v.totamt AS vtot FROM mvtest_tm m LEFT JOIN mvtest_tv v USING (type) ORDER BY type; - --- make sure that dependencies are reported properly when they block the drop -DROP TABLE mvtest_t; - --- make sure dependencies are dropped and reported --- and make sure that transactional behavior is correct on rollback --- incidentally leaving some interesting materialized views for pg_dump testing -BEGIN; -DROP TABLE mvtest_t CASCADE; -ROLLBACK; - --- some additional tests not using base tables -CREATE VIEW mvtest_vt1 AS SELECT 1 moo; -CREATE VIEW mvtest_vt2 AS SELECT moo, 2*moo FROM mvtest_vt1 UNION ALL SELECT moo, 3*moo FROM mvtest_vt1; -\d+ mvtest_vt2 -CREATE MATERIALIZED VIEW mv_test2 AS SELECT moo, 2*moo FROM mvtest_vt2 UNION ALL SELECT moo, 3*moo FROM mvtest_vt2; -\d+ mv_test2 -CREATE MATERIALIZED VIEW mv_test3 AS SELECT * FROM mv_test2 WHERE moo = 12345; -SELECT relispopulated FROM pg_class WHERE oid = 'mv_test3'::regclass; - -DROP VIEW mvtest_vt1 CASCADE; - --- test that duplicate values on unique index prevent refresh -CREATE TABLE mvtest_foo(a, b) AS VALUES(1, 10); -CREATE MATERIALIZED VIEW mvtest_mv AS SELECT * FROM mvtest_foo; -CREATE UNIQUE INDEX ON mvtest_mv(a); -INSERT INTO mvtest_foo SELECT * FROM mvtest_foo; -REFRESH MATERIALIZED VIEW mvtest_mv; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_mv; -DROP TABLE mvtest_foo CASCADE; - --- make sure that all columns covered by unique indexes works -CREATE TABLE mvtest_foo(a, b, c) AS VALUES(1, 2, 3); -CREATE MATERIALIZED VIEW mvtest_mv AS SELECT * FROM mvtest_foo; -CREATE UNIQUE INDEX ON mvtest_mv (a); -CREATE UNIQUE INDEX ON mvtest_mv (b); -CREATE UNIQUE INDEX on mvtest_mv (c); -INSERT INTO mvtest_foo VALUES(2, 3, 4); -INSERT INTO mvtest_foo VALUES(3, 4, 5); -REFRESH MATERIALIZED VIEW mvtest_mv; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_mv; -DROP TABLE mvtest_foo CASCADE; - --- allow subquery to reference unpopulated matview if WITH NO DATA is specified -CREATE MATERIALIZED VIEW mvtest_mv1 AS SELECT 1 AS col1 WITH NO DATA; -CREATE MATERIALIZED VIEW mvtest_mv2 AS SELECT * FROM mvtest_mv1 - WHERE col1 = (SELECT LEAST(col1) FROM mvtest_mv1) WITH NO DATA; -DROP MATERIALIZED VIEW mvtest_mv1 CASCADE; - --- make sure that types with unusual equality tests work -CREATE TABLE mvtest_boxes (id serial primary key, b box); -INSERT INTO mvtest_boxes (b) VALUES - ('(32,32),(31,31)'), - ('(2.0000004,2.0000004),(1,1)'), - ('(1.9999996,1.9999996),(1,1)'); -CREATE MATERIALIZED VIEW mvtest_boxmv AS SELECT * FROM mvtest_boxes; -CREATE UNIQUE INDEX mvtest_boxmv_id ON mvtest_boxmv (id); -UPDATE mvtest_boxes SET b = '(2,2),(1,1)' WHERE id = 2; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_boxmv; -SELECT * FROM mvtest_boxmv ORDER BY id; -DROP TABLE mvtest_boxes CASCADE; - --- make sure that column names are handled correctly -CREATE TABLE mvtest_v (i int, j int); -CREATE MATERIALIZED VIEW mvtest_mv_v (ii, jj, kk) AS SELECT i, j FROM mvtest_v; -- error -CREATE MATERIALIZED VIEW mvtest_mv_v (ii, jj) AS SELECT i, j FROM mvtest_v; -- ok -CREATE MATERIALIZED VIEW mvtest_mv_v_2 (ii) AS SELECT i, j FROM mvtest_v; -- ok -CREATE MATERIALIZED VIEW mvtest_mv_v_3 (ii, jj, kk) AS SELECT i, j FROM mvtest_v WITH NO DATA; -- error -CREATE MATERIALIZED VIEW mvtest_mv_v_3 (ii, jj) AS SELECT i, j FROM mvtest_v WITH NO DATA; -- ok -CREATE MATERIALIZED VIEW mvtest_mv_v_4 (ii) AS SELECT i, j FROM mvtest_v WITH NO DATA; -- ok -ALTER TABLE mvtest_v RENAME COLUMN i TO x; -INSERT INTO mvtest_v values (1, 2); -CREATE UNIQUE INDEX mvtest_mv_v_ii ON mvtest_mv_v (ii); -REFRESH MATERIALIZED VIEW mvtest_mv_v; -UPDATE mvtest_v SET j = 3 WHERE x = 1; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_mv_v; -REFRESH MATERIALIZED VIEW mvtest_mv_v_2; -REFRESH MATERIALIZED VIEW mvtest_mv_v_3; -REFRESH MATERIALIZED VIEW mvtest_mv_v_4; -SELECT * FROM mvtest_v; -SELECT * FROM mvtest_mv_v; -SELECT * FROM mvtest_mv_v_2; -SELECT * FROM mvtest_mv_v_3; -SELECT * FROM mvtest_mv_v_4; -DROP TABLE mvtest_v CASCADE; - --- Check that unknown literals are converted to "text" in CREATE MATVIEW, --- so that we don't end up with unknown-type columns. -CREATE MATERIALIZED VIEW mv_unspecified_types AS - SELECT 42 as i, 42.5 as num, 'foo' as u, 'foo'::unknown as u2, null as n; -\d+ mv_unspecified_types -SELECT * FROM mv_unspecified_types; -DROP MATERIALIZED VIEW mv_unspecified_types; - --- make sure that create WITH NO DATA does not plan the query (bug #13907) -create materialized view mvtest_error as select 1/0 as x; -- fail -create materialized view mvtest_error as select 1/0 as x with no data; -refresh materialized view mvtest_error; -- fail here -drop materialized view mvtest_error; - --- make sure that matview rows can be referenced as source rows (bug #9398) -CREATE TABLE mvtest_v AS SELECT generate_series(1,10) AS a; -CREATE MATERIALIZED VIEW mvtest_mv_v AS SELECT a FROM mvtest_v WHERE a <= 5; -DELETE FROM mvtest_v WHERE EXISTS ( SELECT * FROM mvtest_mv_v WHERE mvtest_mv_v.a = mvtest_v.a ); -SELECT * FROM mvtest_v; -SELECT * FROM mvtest_mv_v; -DROP TABLE mvtest_v CASCADE; - --- make sure running as superuser works when MV owned by another role (bug #11208) -CREATE ROLE regress_user_mvtest; -SET ROLE regress_user_mvtest; --- this test case also checks for ambiguity in the queries issued by --- refresh_by_match_merge(), by choosing column names that intentionally --- duplicate all the aliases used in those queries -CREATE TABLE mvtest_foo_data AS SELECT i, - i+1 AS tid, - md5(random()::text) AS mv, - md5(random()::text) AS newdata, - md5(random()::text) AS newdata2, - md5(random()::text) AS diff - FROM generate_series(1, 10) i; -CREATE MATERIALIZED VIEW mvtest_mv_foo AS SELECT * FROM mvtest_foo_data; -CREATE MATERIALIZED VIEW mvtest_mv_foo AS SELECT * FROM mvtest_foo_data; -CREATE MATERIALIZED VIEW IF NOT EXISTS mvtest_mv_foo AS SELECT * FROM mvtest_foo_data; -CREATE UNIQUE INDEX ON mvtest_mv_foo (i); -RESET ROLE; -REFRESH MATERIALIZED VIEW mvtest_mv_foo; -REFRESH MATERIALIZED VIEW CONCURRENTLY mvtest_mv_foo; -DROP OWNED BY regress_user_mvtest CASCADE; -DROP ROLE regress_user_mvtest; - --- make sure that create WITH NO DATA works via SPI -BEGIN; -CREATE FUNCTION mvtest_func() - RETURNS void AS $$ -BEGIN - CREATE MATERIALIZED VIEW mvtest1 AS SELECT 1 AS x; - CREATE MATERIALIZED VIEW mvtest2 AS SELECT 1 AS x WITH NO DATA; -END; -$$ LANGUAGE plpgsql; -SELECT mvtest_func(); -SELECT * FROM mvtest1; -SELECT * FROM mvtest2; -ROLLBACK; - --- INSERT privileges if relation owner is not allowed to insert. -CREATE SCHEMA matview_schema; -CREATE USER regress_matview_user; -ALTER DEFAULT PRIVILEGES FOR ROLE regress_matview_user - REVOKE INSERT ON TABLES FROM regress_matview_user; -GRANT ALL ON SCHEMA matview_schema TO public; - -SET SESSION AUTHORIZATION regress_matview_user; -CREATE MATERIALIZED VIEW matview_schema.mv_withdata1 (a) AS - SELECT generate_series(1, 10) WITH DATA; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE MATERIALIZED VIEW matview_schema.mv_withdata2 (a) AS - SELECT generate_series(1, 10) WITH DATA; -REFRESH MATERIALIZED VIEW matview_schema.mv_withdata2; -CREATE MATERIALIZED VIEW matview_schema.mv_nodata1 (a) AS - SELECT generate_series(1, 10) WITH NO DATA; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE MATERIALIZED VIEW matview_schema.mv_nodata2 (a) AS - SELECT generate_series(1, 10) WITH NO DATA; -REFRESH MATERIALIZED VIEW matview_schema.mv_nodata2; -RESET SESSION AUTHORIZATION; - -ALTER DEFAULT PRIVILEGES FOR ROLE regress_matview_user - GRANT INSERT ON TABLES TO regress_matview_user; - -DROP SCHEMA matview_schema CASCADE; -DROP USER regress_matview_user; - --- CREATE MATERIALIZED VIEW ... IF NOT EXISTS -CREATE MATERIALIZED VIEW matview_ine_tab AS SELECT 1; -CREATE MATERIALIZED VIEW matview_ine_tab AS SELECT 1 / 0; -- error -CREATE MATERIALIZED VIEW IF NOT EXISTS matview_ine_tab AS - SELECT 1 / 0; -- ok -CREATE MATERIALIZED VIEW matview_ine_tab AS - SELECT 1 / 0 WITH NO DATA; -- error -CREATE MATERIALIZED VIEW IF NOT EXISTS matview_ine_tab AS - SELECT 1 / 0 WITH NO DATA; -- ok -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE MATERIALIZED VIEW matview_ine_tab AS - SELECT 1 / 0; -- error -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE MATERIALIZED VIEW IF NOT EXISTS matview_ine_tab AS - SELECT 1 / 0; -- ok -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE MATERIALIZED VIEW matview_ine_tab AS - SELECT 1 / 0 WITH NO DATA; -- error -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE MATERIALIZED VIEW IF NOT EXISTS matview_ine_tab AS - SELECT 1 / 0 WITH NO DATA; -- ok -DROP MATERIALIZED VIEW matview_ine_tab; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmemoize.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmemoize.sql deleted file mode 100644 index 0979bcdf76..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmemoize.sql +++ /dev/null @@ -1,154 +0,0 @@ --- Perform tests on the Memoize node. - --- The cache hits/misses/evictions from the Memoize node can vary between --- machines. Let's just replace the number with an 'N'. In order to allow us --- to perform validation when the measure was zero, we replace a zero value --- with "Zero". All other numbers are replaced with 'N'. -create function explain_memoize(query text, hide_hitmiss bool) returns setof text -language plpgsql as -$$ -declare - ln text; -begin - for ln in - execute format('explain (analyze, costs off, summary off, timing off) %s', - query) - loop - if hide_hitmiss = true then - ln := regexp_replace(ln, 'Hits: 0', 'Hits: Zero'); - ln := regexp_replace(ln, 'Hits: \d+', 'Hits: N'); - ln := regexp_replace(ln, 'Misses: 0', 'Misses: Zero'); - ln := regexp_replace(ln, 'Misses: \d+', 'Misses: N'); - end if; - ln := regexp_replace(ln, 'Evictions: 0', 'Evictions: Zero'); - ln := regexp_replace(ln, 'Evictions: \d+', 'Evictions: N'); - ln := regexp_replace(ln, 'Memory Usage: \d+', 'Memory Usage: N'); - ln := regexp_replace(ln, 'Heap Fetches: \d+', 'Heap Fetches: N'); - ln := regexp_replace(ln, 'loops=\d+', 'loops=N'); - return next ln; - end loop; -end; -$$; - --- Ensure we get a memoize node on the inner side of the nested loop -SET enable_hashjoin TO off; -SET enable_bitmapscan TO off; - -SELECT explain_memoize(' -SELECT COUNT(*),AVG(t1.unique1) FROM tenk1 t1 -INNER JOIN tenk1 t2 ON t1.unique1 = t2.twenty -WHERE t2.unique1 < 1000;', false); - --- And check we get the expected results. -SELECT COUNT(*),AVG(t1.unique1) FROM tenk1 t1 -INNER JOIN tenk1 t2 ON t1.unique1 = t2.twenty -WHERE t2.unique1 < 1000; - --- Try with LATERAL joins -SELECT explain_memoize(' -SELECT COUNT(*),AVG(t2.unique1) FROM tenk1 t1, -LATERAL (SELECT t2.unique1 FROM tenk1 t2 WHERE t1.twenty = t2.unique1) t2 -WHERE t1.unique1 < 1000;', false); - --- And check we get the expected results. -SELECT COUNT(*),AVG(t2.unique1) FROM tenk1 t1, -LATERAL (SELECT t2.unique1 FROM tenk1 t2 WHERE t1.twenty = t2.unique1) t2 -WHERE t1.unique1 < 1000; - --- Reduce work_mem and hash_mem_multiplier so that we see some cache evictions -SET work_mem TO '64kB'; -SET hash_mem_multiplier TO 1.0; -SET enable_mergejoin TO off; --- Ensure we get some evictions. We're unable to validate the hits and misses --- here as the number of entries that fit in the cache at once will vary --- between different machines. -SELECT explain_memoize(' -SELECT COUNT(*),AVG(t1.unique1) FROM tenk1 t1 -INNER JOIN tenk1 t2 ON t1.unique1 = t2.thousand -WHERE t2.unique1 < 1200;', true); - -CREATE TABLE flt (f float); -CREATE INDEX flt_f_idx ON flt (f); -INSERT INTO flt VALUES('-0.0'::float),('+0.0'::float); -ANALYZE flt; - -SET enable_seqscan TO off; - --- Ensure memoize operates in logical mode -SELECT explain_memoize(' -SELECT * FROM flt f1 INNER JOIN flt f2 ON f1.f = f2.f;', false); - --- Ensure memoize operates in binary mode -SELECT explain_memoize(' -SELECT * FROM flt f1 INNER JOIN flt f2 ON f1.f >= f2.f;', false); - -DROP TABLE flt; - --- Exercise Memoize in binary mode with a large fixed width type and a --- varlena type. -CREATE TABLE strtest (n name, t text); -CREATE INDEX strtest_n_idx ON strtest (n); -CREATE INDEX strtest_t_idx ON strtest (t); -INSERT INTO strtest VALUES('one','one'),('two','two'),('three',repeat(md5('three'),100)); --- duplicate rows so we get some cache hits -INSERT INTO strtest SELECT * FROM strtest; -ANALYZE strtest; - --- Ensure we get 3 hits and 3 misses -SELECT explain_memoize(' -SELECT * FROM strtest s1 INNER JOIN strtest s2 ON s1.n >= s2.n;', false); - --- Ensure we get 3 hits and 3 misses -SELECT explain_memoize(' -SELECT * FROM strtest s1 INNER JOIN strtest s2 ON s1.t >= s2.t;', false); - -DROP TABLE strtest; - --- Exercise Memoize code that flushes the cache when a parameter changes which --- is not part of the cache key. - --- Ensure we get a Memoize plan -EXPLAIN (COSTS OFF) -SELECT unique1 FROM tenk1 t0 -WHERE unique1 < 3 - AND EXISTS ( - SELECT 1 FROM tenk1 t1 - INNER JOIN tenk1 t2 ON t1.unique1 = t2.hundred - WHERE t0.ten = t1.twenty AND t0.two <> t2.four OFFSET 0); - --- Ensure the above query returns the correct result -SELECT unique1 FROM tenk1 t0 -WHERE unique1 < 3 - AND EXISTS ( - SELECT 1 FROM tenk1 t1 - INNER JOIN tenk1 t2 ON t1.unique1 = t2.hundred - WHERE t0.ten = t1.twenty AND t0.two <> t2.four OFFSET 0); - -RESET enable_seqscan; -RESET enable_mergejoin; -RESET work_mem; -RESET hash_mem_multiplier; -RESET enable_bitmapscan; -RESET enable_hashjoin; - --- Test parallel plans with Memoize -SET min_parallel_table_scan_size TO 0; -SET parallel_setup_cost TO 0; -SET parallel_tuple_cost TO 0; -SET max_parallel_workers_per_gather TO 2; - --- Ensure we get a parallel plan. -EXPLAIN (COSTS OFF) -SELECT COUNT(*),AVG(t2.unique1) FROM tenk1 t1, -LATERAL (SELECT t2.unique1 FROM tenk1 t2 WHERE t1.twenty = t2.unique1) t2 -WHERE t1.unique1 < 1000; - --- And ensure the parallel plan gives us the correct results. -SELECT COUNT(*),AVG(t2.unique1) FROM tenk1 t1, -LATERAL (SELECT t2.unique1 FROM tenk1 t2 WHERE t1.twenty = t2.unique1) t2 -WHERE t1.unique1 < 1000; - -RESET max_parallel_workers_per_gather; -RESET parallel_tuple_cost; -RESET parallel_setup_cost; -RESET min_parallel_table_scan_size; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmerge.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmerge.sql deleted file mode 100644 index afeb212f3c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmerge.sql +++ /dev/null @@ -1,1288 +0,0 @@ --- --- MERGE --- ---\set VERBOSITY verbose - ---set debug_print_rewritten = true; ---set debug_print_parse = true; ---set debug_print_pretty = true; - - -CREATE USER regress_merge_privs; -CREATE USER regress_merge_no_privs; -DROP TABLE IF EXISTS target; -DROP TABLE IF EXISTS source; -CREATE TABLE target (tid integer, balance integer); -CREATE TABLE source (sid integer, delta integer); --no index -INSERT INTO target VALUES (1, 10); -INSERT INTO target VALUES (2, 20); -INSERT INTO target VALUES (3, 30); -SELECT t.ctid is not null as matched, t.*, s.* FROM source s FULL OUTER JOIN target t ON s.sid = t.tid ORDER BY t.tid, s.sid; - -ALTER TABLE target OWNER TO regress_merge_privs; -ALTER TABLE source OWNER TO regress_merge_privs; - -CREATE TABLE target2 (tid integer, balance integer); -CREATE TABLE source2 (sid integer, delta integer); - -ALTER TABLE target2 OWNER TO regress_merge_no_privs; -ALTER TABLE source2 OWNER TO regress_merge_no_privs; - -GRANT INSERT ON target TO regress_merge_no_privs; - -SET SESSION AUTHORIZATION regress_merge_privs; - -EXPLAIN (COSTS OFF) -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DELETE; - --- --- Errors --- -MERGE INTO target t RANDOMWORD -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; --- MATCHED/INSERT error -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - INSERT DEFAULT VALUES; --- incorrectly specifying INTO target -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT INTO target DEFAULT VALUES; --- Multiple VALUES clause -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (1,1), (2,2); --- SELECT query for INSERT -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT SELECT (1, 1); --- NOT MATCHED/UPDATE -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - UPDATE SET balance = 0; --- UPDATE tablename -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE target SET balance = 0; --- source and target names the same -MERGE INTO target -USING target -ON tid = tid -WHEN MATCHED THEN DO NOTHING; - --- unsupported relation types --- view -CREATE VIEW tv AS SELECT * FROM target; -MERGE INTO tv t -USING source s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT DEFAULT VALUES; -DROP VIEW tv; - --- materialized view -CREATE MATERIALIZED VIEW mv AS SELECT * FROM target; -MERGE INTO mv t -USING source s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT DEFAULT VALUES; -DROP MATERIALIZED VIEW mv; - --- permissions - -MERGE INTO target -USING source2 -ON target.tid = source2.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; - -GRANT INSERT ON target TO regress_merge_no_privs; -SET SESSION AUTHORIZATION regress_merge_no_privs; - -MERGE INTO target -USING source2 -ON target.tid = source2.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; - -GRANT UPDATE ON target2 TO regress_merge_privs; -SET SESSION AUTHORIZATION regress_merge_privs; - -MERGE INTO target2 -USING source -ON target2.tid = source.sid -WHEN MATCHED THEN - DELETE; - -MERGE INTO target2 -USING source -ON target2.tid = source.sid -WHEN NOT MATCHED THEN - INSERT DEFAULT VALUES; - --- check if the target can be accessed from source relation subquery; we should --- not be able to do so -MERGE INTO target t -USING (SELECT * FROM source WHERE t.tid > sid) s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT DEFAULT VALUES; - --- --- initial tests --- --- zero rows in source has no effect -MERGE INTO target -USING source -ON target.tid = source.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; - -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DELETE; -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT DEFAULT VALUES; -ROLLBACK; - --- insert some non-matching source rows to work from -INSERT INTO source VALUES (4, 40); -SELECT * FROM source ORDER BY sid; -SELECT * FROM target ORDER BY tid; - -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - DO NOTHING; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DELETE; -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT DEFAULT VALUES; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- index plans -INSERT INTO target SELECT generate_series(1000,2500), 0; -ALTER TABLE target ADD PRIMARY KEY (tid); -ANALYZE target; - -EXPLAIN (COSTS OFF) -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; -EXPLAIN (COSTS OFF) -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DELETE; -EXPLAIN (COSTS OFF) -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (4, NULL); -DELETE FROM target WHERE tid > 100; -ANALYZE target; - --- insert some matching source rows to work from -INSERT INTO source VALUES (2, 5); -INSERT INTO source VALUES (3, 20); -SELECT * FROM source ORDER BY sid; -SELECT * FROM target ORDER BY tid; - --- equivalent of an UPDATE join -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- equivalent of a DELETE join -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DELETE; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DO NOTHING; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (4, NULL); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- duplicate source row causes multiple target row update ERROR -INSERT INTO source VALUES (2, 5); -SELECT * FROM source ORDER BY sid; -SELECT * FROM target ORDER BY tid; -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0; -ROLLBACK; - -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - DELETE; -ROLLBACK; - --- remove duplicate MATCHED data from source data -DELETE FROM source WHERE sid = 2; -INSERT INTO source VALUES (2, 5); -SELECT * FROM source ORDER BY sid; -SELECT * FROM target ORDER BY tid; - --- duplicate source row on INSERT should fail because of target_pkey -INSERT INTO source VALUES (4, 40); -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (4, NULL); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- remove duplicate NOT MATCHED data from source data -DELETE FROM source WHERE sid = 4; -INSERT INTO source VALUES (4, 40); -SELECT * FROM source ORDER BY sid; -SELECT * FROM target ORDER BY tid; - --- remove constraints -alter table target drop CONSTRAINT target_pkey; -alter table target alter column tid drop not null; - --- multiple actions -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (4, 4) -WHEN MATCHED THEN - UPDATE SET balance = 0; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- should be equivalent -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = 0 -WHEN NOT MATCHED THEN - INSERT VALUES (4, 4); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- column references --- do a simple equivalent of an UPDATE join -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = t.balance + s.delta; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- do a simple equivalent of an INSERT SELECT -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- and again with duplicate source rows -INSERT INTO source VALUES (5, 50); -INSERT INTO source VALUES (5, 50); - --- do a simple equivalent of an INSERT SELECT -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- removing duplicate source rows -DELETE FROM source WHERE sid = 5; - --- and again with explicitly identified column list -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- and again with a subtle error: referring to non-existent target row for NOT MATCHED -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (t.tid, s.delta); - --- and again with a constant ON clause -BEGIN; -MERGE INTO target t -USING source AS s -ON (SELECT true) -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (t.tid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- now the classic UPSERT -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = t.balance + s.delta -WHEN NOT MATCHED THEN - INSERT VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- unreachable WHEN clause should ERROR -BEGIN; -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED THEN /* Terminal WHEN clause for MATCHED */ - DELETE -WHEN MATCHED AND s.delta > 0 THEN - UPDATE SET balance = t.balance - s.delta; -ROLLBACK; - --- conditional WHEN clause -CREATE TABLE wq_target (tid integer not null, balance integer DEFAULT -1); -CREATE TABLE wq_source (balance integer, sid integer); - -INSERT INTO wq_source (sid, balance) VALUES (1, 100); - -BEGIN; --- try a simple INSERT with default values first -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid) VALUES (s.sid); -SELECT * FROM wq_target; -ROLLBACK; - --- this time with a FALSE condition -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN NOT MATCHED AND FALSE THEN - INSERT (tid) VALUES (s.sid); -SELECT * FROM wq_target; - --- this time with an actual condition which returns false -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN NOT MATCHED AND s.balance <> 100 THEN - INSERT (tid) VALUES (s.sid); -SELECT * FROM wq_target; - -BEGIN; --- and now with a condition which returns true -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN NOT MATCHED AND s.balance = 100 THEN - INSERT (tid) VALUES (s.sid); -SELECT * FROM wq_target; -ROLLBACK; - --- conditions in the NOT MATCHED clause can only refer to source columns -BEGIN; -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN NOT MATCHED AND t.balance = 100 THEN - INSERT (tid) VALUES (s.sid); -SELECT * FROM wq_target; -ROLLBACK; - -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN NOT MATCHED AND s.balance = 100 THEN - INSERT (tid) VALUES (s.sid); -SELECT * FROM wq_target; - --- conditions in MATCHED clause can refer to both source and target -SELECT * FROM wq_source; -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND s.balance = 100 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.balance = 100 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - --- check if AND works -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.balance = 99 AND s.balance > 100 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.balance = 99 AND s.balance = 100 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - --- check if OR works -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.balance = 99 OR s.balance > 100 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.balance = 199 OR s.balance > 100 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - --- check source-side whole-row references -BEGIN; -MERGE INTO wq_target t -USING wq_source s ON (t.tid = s.sid) -WHEN matched and t = s or t.tid = s.sid THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; -ROLLBACK; - --- check if subqueries work in the conditions? -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.balance > (SELECT max(balance) FROM target) THEN - UPDATE SET balance = t.balance + s.balance; - --- check if we can access system columns in the conditions -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.xmin = t.xmax THEN - UPDATE SET balance = t.balance + s.balance; - -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND t.tableoid >= 0 THEN - UPDATE SET balance = t.balance + s.balance; -SELECT * FROM wq_target; - --- test preventing WHEN conditions from writing to the database -create or replace function merge_when_and_write() returns boolean -language plpgsql as -$$ -BEGIN - INSERT INTO target VALUES (100, 100); - RETURN TRUE; -END; -$$; - -BEGIN; -MERGE INTO wq_target t -USING wq_source s ON t.tid = s.sid -WHEN MATCHED AND (merge_when_and_write()) THEN - UPDATE SET balance = t.balance + s.balance; -ROLLBACK; -drop function merge_when_and_write(); - -DROP TABLE wq_target, wq_source; - --- test triggers -create or replace function merge_trigfunc () returns trigger -language plpgsql as -$$ -DECLARE - line text; -BEGIN - SELECT INTO line format('%s %s %s trigger%s', - TG_WHEN, TG_OP, TG_LEVEL, CASE - WHEN TG_OP = 'INSERT' AND TG_LEVEL = 'ROW' - THEN format(' row: %s', NEW) - WHEN TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW' - THEN format(' row: %s -> %s', OLD, NEW) - WHEN TG_OP = 'DELETE' AND TG_LEVEL = 'ROW' - THEN format(' row: %s', OLD) - END); - - RAISE NOTICE '%', line; - IF (TG_WHEN = 'BEFORE' AND TG_LEVEL = 'ROW') THEN - IF (TG_OP = 'DELETE') THEN - RETURN OLD; - ELSE - RETURN NEW; - END IF; - ELSE - RETURN NULL; - END IF; -END; -$$; -CREATE TRIGGER merge_bsi BEFORE INSERT ON target FOR EACH STATEMENT EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_bsu BEFORE UPDATE ON target FOR EACH STATEMENT EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_bsd BEFORE DELETE ON target FOR EACH STATEMENT EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_asi AFTER INSERT ON target FOR EACH STATEMENT EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_asu AFTER UPDATE ON target FOR EACH STATEMENT EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_asd AFTER DELETE ON target FOR EACH STATEMENT EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_bri BEFORE INSERT ON target FOR EACH ROW EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_bru BEFORE UPDATE ON target FOR EACH ROW EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_brd BEFORE DELETE ON target FOR EACH ROW EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_ari AFTER INSERT ON target FOR EACH ROW EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_aru AFTER UPDATE ON target FOR EACH ROW EXECUTE PROCEDURE merge_trigfunc (); -CREATE TRIGGER merge_ard AFTER DELETE ON target FOR EACH ROW EXECUTE PROCEDURE merge_trigfunc (); - --- now the classic UPSERT, with a DELETE -BEGIN; -UPDATE target SET balance = 0 WHERE tid = 3; ---EXPLAIN (ANALYZE ON, COSTS OFF, SUMMARY OFF, TIMING OFF) -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED AND t.balance > s.delta THEN - UPDATE SET balance = t.balance - s.delta -WHEN MATCHED THEN - DELETE -WHEN NOT MATCHED THEN - INSERT VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- Test behavior of triggers that turn UPDATE/DELETE into no-ops -create or replace function skip_merge_op() returns trigger -language plpgsql as -$$ -BEGIN - RETURN NULL; -END; -$$; - -SELECT * FROM target full outer join source on (sid = tid); -create trigger merge_skip BEFORE INSERT OR UPDATE or DELETE - ON target FOR EACH ROW EXECUTE FUNCTION skip_merge_op(); -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED AND s.sid = 3 THEN UPDATE SET balance = t.balance + s.delta -WHEN MATCHED THEN DELETE -WHEN NOT MATCHED THEN INSERT VALUES (sid, delta); -SELECT * FROM target FULL OUTER JOIN source ON (sid = tid); -DROP TRIGGER merge_skip ON target; -DROP FUNCTION skip_merge_op(); - --- test from PL/pgSQL --- make sure MERGE INTO isn't interpreted to mean returning variables like SELECT INTO -BEGIN; -DO LANGUAGE plpgsql $$ -BEGIN -MERGE INTO target t -USING source AS s -ON t.tid = s.sid -WHEN MATCHED AND t.balance > s.delta THEN - UPDATE SET balance = t.balance - s.delta; -END; -$$; -ROLLBACK; - ---source constants -BEGIN; -MERGE INTO target t -USING (SELECT 9 AS sid, 57 AS delta) AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - ---source query -BEGIN; -MERGE INTO target t -USING (SELECT sid, delta FROM source WHERE delta > 0) AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - -BEGIN; -MERGE INTO target t -USING (SELECT sid, delta as newname FROM source WHERE delta > 0) AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (s.sid, s.newname); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - ---self-merge -BEGIN; -MERGE INTO target t1 -USING target t2 -ON t1.tid = t2.tid -WHEN MATCHED THEN - UPDATE SET balance = t1.balance + t2.balance -WHEN NOT MATCHED THEN - INSERT VALUES (t2.tid, t2.balance); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - -BEGIN; -MERGE INTO target t -USING (SELECT tid as sid, balance as delta FROM target WHERE balance > 0) AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - -BEGIN; -MERGE INTO target t -USING -(SELECT sid, max(delta) AS delta - FROM source - GROUP BY sid - HAVING count(*) = 1 - ORDER BY sid ASC) AS s -ON t.tid = s.sid -WHEN NOT MATCHED THEN - INSERT (tid, balance) VALUES (s.sid, s.delta); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- plpgsql parameters and results -BEGIN; -CREATE FUNCTION merge_func (p_id integer, p_bal integer) -RETURNS INTEGER -LANGUAGE plpgsql -AS $$ -DECLARE - result integer; -BEGIN -MERGE INTO target t -USING (SELECT p_id AS sid) AS s -ON t.tid = s.sid -WHEN MATCHED THEN - UPDATE SET balance = t.balance - p_bal; -IF FOUND THEN - GET DIAGNOSTICS result := ROW_COUNT; -END IF; -RETURN result; -END; -$$; -SELECT merge_func(3, 4); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- PREPARE -BEGIN; -prepare foom as merge into target t using (select 1 as sid) s on (t.tid = s.sid) when matched then update set balance = 1; -execute foom; -SELECT * FROM target ORDER BY tid; -ROLLBACK; - -BEGIN; -PREPARE foom2 (integer, integer) AS -MERGE INTO target t -USING (SELECT 1) s -ON t.tid = $1 -WHEN MATCHED THEN -UPDATE SET balance = $2; ---EXPLAIN (ANALYZE ON, COSTS OFF, SUMMARY OFF, TIMING OFF) -execute foom2 (1, 1); -SELECT * FROM target ORDER BY tid; -ROLLBACK; - --- subqueries in source relation - -CREATE TABLE sq_target (tid integer NOT NULL, balance integer); -CREATE TABLE sq_source (delta integer, sid integer, balance integer DEFAULT 0); - -INSERT INTO sq_target(tid, balance) VALUES (1,100), (2,200), (3,300); -INSERT INTO sq_source(sid, delta) VALUES (1,10), (2,20), (4,40); - -BEGIN; -MERGE INTO sq_target t -USING (SELECT * FROM sq_source) s -ON tid = sid -WHEN MATCHED AND t.balance > delta THEN - UPDATE SET balance = t.balance + delta; -SELECT * FROM sq_target; -ROLLBACK; - --- try a view -CREATE VIEW v AS SELECT * FROM sq_source WHERE sid < 2; - -BEGIN; -MERGE INTO sq_target -USING v -ON tid = sid -WHEN MATCHED THEN - UPDATE SET balance = v.balance + delta; -SELECT * FROM sq_target; -ROLLBACK; - --- ambiguous reference to a column -BEGIN; -MERGE INTO sq_target -USING v -ON tid = sid -WHEN MATCHED AND tid > 2 THEN - UPDATE SET balance = balance + delta -WHEN NOT MATCHED THEN - INSERT (balance, tid) VALUES (balance + delta, sid) -WHEN MATCHED AND tid < 2 THEN - DELETE; -ROLLBACK; - -BEGIN; -INSERT INTO sq_source (sid, balance, delta) VALUES (-1, -1, -10); -MERGE INTO sq_target t -USING v -ON tid = sid -WHEN MATCHED AND tid > 2 THEN - UPDATE SET balance = t.balance + delta -WHEN NOT MATCHED THEN - INSERT (balance, tid) VALUES (balance + delta, sid) -WHEN MATCHED AND tid < 2 THEN - DELETE; -SELECT * FROM sq_target; -ROLLBACK; - --- CTEs -BEGIN; -INSERT INTO sq_source (sid, balance, delta) VALUES (-1, -1, -10); -WITH targq AS ( - SELECT * FROM v -) -MERGE INTO sq_target t -USING v -ON tid = sid -WHEN MATCHED AND tid > 2 THEN - UPDATE SET balance = t.balance + delta -WHEN NOT MATCHED THEN - INSERT (balance, tid) VALUES (balance + delta, sid) -WHEN MATCHED AND tid < 2 THEN - DELETE; -ROLLBACK; - --- RETURNING -BEGIN; -INSERT INTO sq_source (sid, balance, delta) VALUES (-1, -1, -10); -MERGE INTO sq_target t -USING v -ON tid = sid -WHEN MATCHED AND tid > 2 THEN - UPDATE SET balance = t.balance + delta -WHEN NOT MATCHED THEN - INSERT (balance, tid) VALUES (balance + delta, sid) -WHEN MATCHED AND tid < 2 THEN - DELETE -RETURNING *; -ROLLBACK; - --- EXPLAIN -CREATE TABLE ex_mtarget (a int, b int); -CREATE TABLE ex_msource (a int, b int); -INSERT INTO ex_mtarget SELECT i, i*10 FROM generate_series(1,100,2) i; -INSERT INTO ex_msource SELECT i, i*10 FROM generate_series(1,100,1) i; - -CREATE FUNCTION explain_merge(query text) RETURNS SETOF text -LANGUAGE plpgsql AS -$$ -DECLARE ln text; -BEGIN - FOR ln IN - EXECUTE 'explain (analyze, timing off, summary off, costs off) ' || - query - LOOP - ln := regexp_replace(ln, '(Memory( Usage)?|Buckets|Batches): \S*', '\1: xxx', 'g'); - RETURN NEXT ln; - END LOOP; -END; -$$; - --- only updates -SELECT explain_merge(' -MERGE INTO ex_mtarget t USING ex_msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = t.b + 1'); - --- only updates to selected tuples -SELECT explain_merge(' -MERGE INTO ex_mtarget t USING ex_msource s ON t.a = s.a -WHEN MATCHED AND t.a < 10 THEN - UPDATE SET b = t.b + 1'); - --- updates + deletes -SELECT explain_merge(' -MERGE INTO ex_mtarget t USING ex_msource s ON t.a = s.a -WHEN MATCHED AND t.a < 10 THEN - UPDATE SET b = t.b + 1 -WHEN MATCHED AND t.a >= 10 AND t.a <= 20 THEN - DELETE'); - --- only inserts -SELECT explain_merge(' -MERGE INTO ex_mtarget t USING ex_msource s ON t.a = s.a -WHEN NOT MATCHED AND s.a < 10 THEN - INSERT VALUES (a, b)'); - --- all three -SELECT explain_merge(' -MERGE INTO ex_mtarget t USING ex_msource s ON t.a = s.a -WHEN MATCHED AND t.a < 10 THEN - UPDATE SET b = t.b + 1 -WHEN MATCHED AND t.a >= 30 AND t.a <= 40 THEN - DELETE -WHEN NOT MATCHED AND s.a < 20 THEN - INSERT VALUES (a, b)'); - --- nothing -SELECT explain_merge(' -MERGE INTO ex_mtarget t USING ex_msource s ON t.a = s.a AND t.a < -1000 -WHEN MATCHED AND t.a < 10 THEN - DO NOTHING'); - -DROP TABLE ex_msource, ex_mtarget; -DROP FUNCTION explain_merge(text); - --- Subqueries -BEGIN; -MERGE INTO sq_target t -USING v -ON tid = sid -WHEN MATCHED THEN - UPDATE SET balance = (SELECT count(*) FROM sq_target); -SELECT * FROM sq_target WHERE tid = 1; -ROLLBACK; - -BEGIN; -MERGE INTO sq_target t -USING v -ON tid = sid -WHEN MATCHED AND (SELECT count(*) > 0 FROM sq_target) THEN - UPDATE SET balance = 42; -SELECT * FROM sq_target WHERE tid = 1; -ROLLBACK; - -BEGIN; -MERGE INTO sq_target t -USING v -ON tid = sid AND (SELECT count(*) > 0 FROM sq_target) -WHEN MATCHED THEN - UPDATE SET balance = 42; -SELECT * FROM sq_target WHERE tid = 1; -ROLLBACK; - -DROP TABLE sq_target, sq_source CASCADE; - -CREATE TABLE pa_target (tid integer, balance float, val text) - PARTITION BY LIST (tid); - -CREATE TABLE part1 PARTITION OF pa_target FOR VALUES IN (1,4); -CREATE TABLE part2 PARTITION OF pa_target FOR VALUES IN (2,5,6); -CREATE TABLE part3 PARTITION OF pa_target FOR VALUES IN (3,8,9); -CREATE TABLE part4 PARTITION OF pa_target DEFAULT; - -CREATE TABLE pa_source (sid integer, delta float); --- insert many rows to the source table -INSERT INTO pa_source SELECT id, id * 10 FROM generate_series(1,14) AS id; --- insert a few rows in the target table (odd numbered tid) -INSERT INTO pa_target SELECT id, id * 100, 'initial' FROM generate_series(1,14,2) AS id; - --- try simple MERGE -BEGIN; -MERGE INTO pa_target t - USING pa_source s - ON t.tid = s.sid - WHEN MATCHED THEN - UPDATE SET balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - --- same with a constant qual -BEGIN; -MERGE INTO pa_target t - USING pa_source s - ON t.tid = s.sid AND tid = 1 - WHEN MATCHED THEN - UPDATE SET balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - --- try updating the partition key column -BEGIN; -MERGE INTO pa_target t - USING pa_source s - ON t.tid = s.sid - WHEN MATCHED THEN - UPDATE SET tid = tid + 1, balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - -DROP TABLE pa_target CASCADE; - --- The target table is partitioned in the same way, but this time by attaching --- partitions which have columns in different order, dropped columns etc. -CREATE TABLE pa_target (tid integer, balance float, val text) - PARTITION BY LIST (tid); - -CREATE TABLE part1 (tid integer, balance float, val text); -CREATE TABLE part2 (balance float, tid integer, val text); -CREATE TABLE part3 (tid integer, balance float, val text); -CREATE TABLE part4 (extraid text, tid integer, balance float, val text); -ALTER TABLE part4 DROP COLUMN extraid; - -ALTER TABLE pa_target ATTACH PARTITION part1 FOR VALUES IN (1,4); -ALTER TABLE pa_target ATTACH PARTITION part2 FOR VALUES IN (2,5,6); -ALTER TABLE pa_target ATTACH PARTITION part3 FOR VALUES IN (3,8,9); -ALTER TABLE pa_target ATTACH PARTITION part4 DEFAULT; - --- insert a few rows in the target table (odd numbered tid) -INSERT INTO pa_target SELECT id, id * 100, 'initial' FROM generate_series(1,14,2) AS id; - --- try simple MERGE -BEGIN; -MERGE INTO pa_target t - USING pa_source s - ON t.tid = s.sid - WHEN MATCHED THEN - UPDATE SET balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - --- same with a constant qual -BEGIN; -MERGE INTO pa_target t - USING pa_source s - ON t.tid = s.sid AND tid IN (1, 5) - WHEN MATCHED AND tid % 5 = 0 THEN DELETE - WHEN MATCHED THEN - UPDATE SET balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - --- try updating the partition key column -BEGIN; -MERGE INTO pa_target t - USING pa_source s - ON t.tid = s.sid - WHEN MATCHED THEN - UPDATE SET tid = tid + 1, balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - -DROP TABLE pa_source; -DROP TABLE pa_target CASCADE; - --- Sub-partitioning -CREATE TABLE pa_target (logts timestamp, tid integer, balance float, val text) - PARTITION BY RANGE (logts); - -CREATE TABLE part_m01 PARTITION OF pa_target - FOR VALUES FROM ('2017-01-01') TO ('2017-02-01') - PARTITION BY LIST (tid); -CREATE TABLE part_m01_odd PARTITION OF part_m01 - FOR VALUES IN (1,3,5,7,9); -CREATE TABLE part_m01_even PARTITION OF part_m01 - FOR VALUES IN (2,4,6,8); -CREATE TABLE part_m02 PARTITION OF pa_target - FOR VALUES FROM ('2017-02-01') TO ('2017-03-01') - PARTITION BY LIST (tid); -CREATE TABLE part_m02_odd PARTITION OF part_m02 - FOR VALUES IN (1,3,5,7,9); -CREATE TABLE part_m02_even PARTITION OF part_m02 - FOR VALUES IN (2,4,6,8); - -CREATE TABLE pa_source (sid integer, delta float); --- insert many rows to the source table -INSERT INTO pa_source SELECT id, id * 10 FROM generate_series(1,14) AS id; --- insert a few rows in the target table (odd numbered tid) -INSERT INTO pa_target SELECT '2017-01-31', id, id * 100, 'initial' FROM generate_series(1,9,3) AS id; -INSERT INTO pa_target SELECT '2017-02-28', id, id * 100, 'initial' FROM generate_series(2,9,3) AS id; - --- try simple MERGE -BEGIN; -MERGE INTO pa_target t - USING (SELECT '2017-01-15' AS slogts, * FROM pa_source WHERE sid < 10) s - ON t.tid = s.sid - WHEN MATCHED THEN - UPDATE SET balance = balance + delta, val = val || ' updated by merge' - WHEN NOT MATCHED THEN - INSERT VALUES (slogts::timestamp, sid, delta, 'inserted by merge'); -SELECT * FROM pa_target ORDER BY tid; -ROLLBACK; - -DROP TABLE pa_source; -DROP TABLE pa_target CASCADE; - --- some complex joins on the source side - -CREATE TABLE cj_target (tid integer, balance float, val text); -CREATE TABLE cj_source1 (sid1 integer, scat integer, delta integer); -CREATE TABLE cj_source2 (sid2 integer, sval text); -INSERT INTO cj_source1 VALUES (1, 10, 100); -INSERT INTO cj_source1 VALUES (1, 20, 200); -INSERT INTO cj_source1 VALUES (2, 20, 300); -INSERT INTO cj_source1 VALUES (3, 10, 400); -INSERT INTO cj_source2 VALUES (1, 'initial source2'); -INSERT INTO cj_source2 VALUES (2, 'initial source2'); -INSERT INTO cj_source2 VALUES (3, 'initial source2'); - --- source relation is an unaliased join -MERGE INTO cj_target t -USING cj_source1 s1 - INNER JOIN cj_source2 s2 ON sid1 = sid2 -ON t.tid = sid1 -WHEN NOT MATCHED THEN - INSERT VALUES (sid1, delta, sval); - --- try accessing columns from either side of the source join -MERGE INTO cj_target t -USING cj_source2 s2 - INNER JOIN cj_source1 s1 ON sid1 = sid2 AND scat = 20 -ON t.tid = sid1 -WHEN NOT MATCHED THEN - INSERT VALUES (sid2, delta, sval) -WHEN MATCHED THEN - DELETE; - --- some simple expressions in INSERT targetlist -MERGE INTO cj_target t -USING cj_source2 s2 - INNER JOIN cj_source1 s1 ON sid1 = sid2 -ON t.tid = sid1 -WHEN NOT MATCHED THEN - INSERT VALUES (sid2, delta + scat, sval) -WHEN MATCHED THEN - UPDATE SET val = val || ' updated by merge'; - -MERGE INTO cj_target t -USING cj_source2 s2 - INNER JOIN cj_source1 s1 ON sid1 = sid2 AND scat = 20 -ON t.tid = sid1 -WHEN MATCHED THEN - UPDATE SET val = val || ' ' || delta::text; - -SELECT * FROM cj_target; - -ALTER TABLE cj_source1 RENAME COLUMN sid1 TO sid; -ALTER TABLE cj_source2 RENAME COLUMN sid2 TO sid; - -TRUNCATE cj_target; - -MERGE INTO cj_target t -USING cj_source1 s1 - INNER JOIN cj_source2 s2 ON s1.sid = s2.sid -ON t.tid = s1.sid -WHEN NOT MATCHED THEN - INSERT VALUES (s2.sid, delta, sval); - -DROP TABLE cj_source2, cj_source1, cj_target; - --- Function scans -CREATE TABLE fs_target (a int, b int, c text); -MERGE INTO fs_target t -USING generate_series(1,100,1) AS id -ON t.a = id -WHEN MATCHED THEN - UPDATE SET b = b + id -WHEN NOT MATCHED THEN - INSERT VALUES (id, -1); - -MERGE INTO fs_target t -USING generate_series(1,100,2) AS id -ON t.a = id -WHEN MATCHED THEN - UPDATE SET b = b + id, c = 'updated '|| id.*::text -WHEN NOT MATCHED THEN - INSERT VALUES (id, -1, 'inserted ' || id.*::text); - -SELECT count(*) FROM fs_target; -DROP TABLE fs_target; - --- SERIALIZABLE test --- handled in isolation tests - --- Inheritance-based partitioning -CREATE TABLE measurement ( - city_id int not null, - logdate date not null, - peaktemp int, - unitsales int -); -CREATE TABLE measurement_y2006m02 ( - CHECK ( logdate >= DATE '2006-02-01' AND logdate < DATE '2006-03-01' ) -) INHERITS (measurement); -CREATE TABLE measurement_y2006m03 ( - CHECK ( logdate >= DATE '2006-03-01' AND logdate < DATE '2006-04-01' ) -) INHERITS (measurement); -CREATE TABLE measurement_y2007m01 ( - filler text, - peaktemp int, - logdate date not null, - city_id int not null, - unitsales int - CHECK ( logdate >= DATE '2007-01-01' AND logdate < DATE '2007-02-01') -); -ALTER TABLE measurement_y2007m01 DROP COLUMN filler; -ALTER TABLE measurement_y2007m01 INHERIT measurement; - -CREATE OR REPLACE FUNCTION measurement_insert_trigger() -RETURNS TRIGGER AS $$ -BEGIN - IF ( NEW.logdate >= DATE '2006-02-01' AND - NEW.logdate < DATE '2006-03-01' ) THEN - INSERT INTO measurement_y2006m02 VALUES (NEW.*); - ELSIF ( NEW.logdate >= DATE '2006-03-01' AND - NEW.logdate < DATE '2006-04-01' ) THEN - INSERT INTO measurement_y2006m03 VALUES (NEW.*); - ELSIF ( NEW.logdate >= DATE '2007-01-01' AND - NEW.logdate < DATE '2007-02-01' ) THEN - INSERT INTO measurement_y2007m01 (city_id, logdate, peaktemp, unitsales) - VALUES (NEW.*); - ELSE - RAISE EXCEPTION 'Date out of range. Fix the measurement_insert_trigger() function!'; - END IF; - RETURN NULL; -END; -$$ LANGUAGE plpgsql ; -CREATE TRIGGER insert_measurement_trigger - BEFORE INSERT ON measurement - FOR EACH ROW EXECUTE PROCEDURE measurement_insert_trigger(); -INSERT INTO measurement VALUES (1, '2006-02-10', 35, 10); -INSERT INTO measurement VALUES (1, '2006-02-16', 45, 20); -INSERT INTO measurement VALUES (1, '2006-03-17', 25, 10); -INSERT INTO measurement VALUES (1, '2006-03-27', 15, 40); -INSERT INTO measurement VALUES (1, '2007-01-15', 10, 10); -INSERT INTO measurement VALUES (1, '2007-01-17', 10, 10); - -SELECT tableoid::regclass, * FROM measurement ORDER BY city_id, logdate; - -CREATE TABLE new_measurement (LIKE measurement); -INSERT INTO new_measurement VALUES (1, '2006-03-01', 20, 10); -INSERT INTO new_measurement VALUES (1, '2006-02-16', 50, 10); -INSERT INTO new_measurement VALUES (2, '2006-02-10', 20, 20); -INSERT INTO new_measurement VALUES (1, '2006-03-27', NULL, NULL); -INSERT INTO new_measurement VALUES (1, '2007-01-17', NULL, NULL); -INSERT INTO new_measurement VALUES (1, '2007-01-15', 5, NULL); -INSERT INTO new_measurement VALUES (1, '2007-01-16', 10, 10); - -MERGE into measurement m - USING new_measurement nm ON - (m.city_id = nm.city_id and m.logdate=nm.logdate) -WHEN MATCHED AND nm.peaktemp IS NULL THEN DELETE -WHEN MATCHED THEN UPDATE - SET peaktemp = greatest(m.peaktemp, nm.peaktemp), - unitsales = m.unitsales + coalesce(nm.unitsales, 0) -WHEN NOT MATCHED THEN INSERT - (city_id, logdate, peaktemp, unitsales) - VALUES (city_id, logdate, peaktemp, unitsales); - -SELECT tableoid::regclass, * FROM measurement ORDER BY city_id, logdate; -DROP TABLE measurement, new_measurement CASCADE; -DROP FUNCTION measurement_insert_trigger(); - --- prepare - -RESET SESSION AUTHORIZATION; -DROP TABLE target, target2; -DROP TABLE source, source2; -DROP FUNCTION merge_trigfunc(); -DROP USER regress_merge_privs; -DROP USER regress_merge_no_privs; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmisc_functions.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmisc_functions.sql deleted file mode 100644 index 072fc36a1f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmisc_functions.sql +++ /dev/null @@ -1,199 +0,0 @@ --- directory paths and dlsuffix are passed to us in environment variables -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - --- --- num_nulls() --- - -SELECT num_nonnulls(NULL); -SELECT num_nonnulls('1'); -SELECT num_nonnulls(NULL::text); -SELECT num_nonnulls(NULL::text, NULL::int); -SELECT num_nonnulls(1, 2, NULL::text, NULL::point, '', int8 '9', 1.0 / NULL); -SELECT num_nonnulls(VARIADIC '{1,2,NULL,3}'::int[]); -SELECT num_nonnulls(VARIADIC '{"1","2","3","4"}'::text[]); -SELECT num_nonnulls(VARIADIC ARRAY(SELECT CASE WHEN i <> 40 THEN i END FROM generate_series(1, 100) i)); - -SELECT num_nulls(NULL); -SELECT num_nulls('1'); -SELECT num_nulls(NULL::text); -SELECT num_nulls(NULL::text, NULL::int); -SELECT num_nulls(1, 2, NULL::text, NULL::point, '', int8 '9', 1.0 / NULL); -SELECT num_nulls(VARIADIC '{1,2,NULL,3}'::int[]); -SELECT num_nulls(VARIADIC '{"1","2","3","4"}'::text[]); -SELECT num_nulls(VARIADIC ARRAY(SELECT CASE WHEN i <> 40 THEN i END FROM generate_series(1, 100) i)); - --- special cases -SELECT num_nonnulls(VARIADIC NULL::text[]); -SELECT num_nonnulls(VARIADIC '{}'::int[]); -SELECT num_nulls(VARIADIC NULL::text[]); -SELECT num_nulls(VARIADIC '{}'::int[]); - --- should fail, one or more arguments is required -SELECT num_nonnulls(); -SELECT num_nulls(); - --- --- canonicalize_path() --- - -CREATE FUNCTION test_canonicalize_path(text) - RETURNS text - AS :'regresslib' - LANGUAGE C STRICT IMMUTABLE; - -SELECT test_canonicalize_path('/'); -SELECT test_canonicalize_path('/./abc/def/'); -SELECT test_canonicalize_path('/./../abc/def'); -SELECT test_canonicalize_path('/./../../abc/def/'); -SELECT test_canonicalize_path('/abc/.././def/ghi'); -SELECT test_canonicalize_path('/abc/./../def/ghi//'); -SELECT test_canonicalize_path('/abc/def/../..'); -SELECT test_canonicalize_path('/abc/def/../../..'); -SELECT test_canonicalize_path('/abc/def/../../../../ghi/jkl'); -SELECT test_canonicalize_path('.'); -SELECT test_canonicalize_path('./'); -SELECT test_canonicalize_path('./abc/..'); -SELECT test_canonicalize_path('abc/../'); -SELECT test_canonicalize_path('abc/../def'); -SELECT test_canonicalize_path('..'); -SELECT test_canonicalize_path('../abc/def'); -SELECT test_canonicalize_path('../abc/..'); -SELECT test_canonicalize_path('../abc/../def'); -SELECT test_canonicalize_path('../abc/../../def/ghi'); -SELECT test_canonicalize_path('./abc/./def/.'); -SELECT test_canonicalize_path('./abc/././def/.'); -SELECT test_canonicalize_path('./abc/./def/.././ghi/../../../jkl/mno'); - --- --- pg_log_backend_memory_contexts() --- --- Memory contexts are logged and they are not returned to the function. --- Furthermore, their contents can vary depending on the timing. However, --- we can at least verify that the code doesn't fail, and that the --- permissions are set properly. --- - -SELECT pg_log_backend_memory_contexts(pg_backend_pid()); - -SELECT pg_log_backend_memory_contexts(pid) FROM pg_stat_activity - WHERE backend_type = 'checkpointer'; - -CREATE ROLE regress_log_memory; - -SELECT has_function_privilege('regress_log_memory', - 'pg_log_backend_memory_contexts(integer)', 'EXECUTE'); -- no - -GRANT EXECUTE ON FUNCTION pg_log_backend_memory_contexts(integer) - TO regress_log_memory; - -SELECT has_function_privilege('regress_log_memory', - 'pg_log_backend_memory_contexts(integer)', 'EXECUTE'); -- yes - -SET ROLE regress_log_memory; -SELECT pg_log_backend_memory_contexts(pg_backend_pid()); -RESET ROLE; - -REVOKE EXECUTE ON FUNCTION pg_log_backend_memory_contexts(integer) - FROM regress_log_memory; - -DROP ROLE regress_log_memory; - --- --- Test some built-in SRFs --- --- The outputs of these are variable, so we can't just print their results --- directly, but we can at least verify that the code doesn't fail. --- -select setting as segsize -from pg_settings where name = 'wal_segment_size' -\gset - -select count(*) > 0 as ok from pg_ls_waldir(); --- Test ProjectSet as well as FunctionScan -select count(*) > 0 as ok from (select pg_ls_waldir()) ss; --- Test not-run-to-completion cases. -select * from pg_ls_waldir() limit 0; -select count(*) > 0 as ok from (select * from pg_ls_waldir() limit 1) ss; -select (w).size = :segsize as ok -from (select pg_ls_waldir() w) ss where length((w).name) = 24 limit 1; - -select count(*) >= 0 as ok from pg_ls_archive_statusdir(); - -select * from (select pg_ls_dir('.') a) a where a = 'base' limit 1; --- Test missing_ok (second argument) -select pg_ls_dir('does not exist', false, false); -- error -select pg_ls_dir('does not exist', true, false); -- ok --- Test include_dot_dirs (third argument) -select count(*) = 1 as dot_found - from pg_ls_dir('.', false, true) as ls where ls = '.'; -select count(*) = 1 as dot_found - from pg_ls_dir('.', false, false) as ls where ls = '.'; - -select * from (select (pg_timezone_names()).name) ptn where name='UTC' limit 1; - -select count(*) > 0 from - (select pg_tablespace_databases(oid) as pts from pg_tablespace - where spcname = 'pg_default') pts - join pg_database db on pts.pts = db.oid; - --- --- Test replication slot directory functions --- -CREATE ROLE regress_slot_dir_funcs; --- Not available by default. -SELECT has_function_privilege('regress_slot_dir_funcs', - 'pg_ls_logicalsnapdir()', 'EXECUTE'); -SELECT has_function_privilege('regress_slot_dir_funcs', - 'pg_ls_logicalmapdir()', 'EXECUTE'); -SELECT has_function_privilege('regress_slot_dir_funcs', - 'pg_ls_replslotdir(text)', 'EXECUTE'); -GRANT pg_monitor TO regress_slot_dir_funcs; --- Role is now part of pg_monitor, so these are available. -SELECT has_function_privilege('regress_slot_dir_funcs', - 'pg_ls_logicalsnapdir()', 'EXECUTE'); -SELECT has_function_privilege('regress_slot_dir_funcs', - 'pg_ls_logicalmapdir()', 'EXECUTE'); -SELECT has_function_privilege('regress_slot_dir_funcs', - 'pg_ls_replslotdir(text)', 'EXECUTE'); -DROP ROLE regress_slot_dir_funcs; - --- --- Test adding a support function to a subject function --- - -CREATE FUNCTION my_int_eq(int, int) RETURNS bool - LANGUAGE internal STRICT IMMUTABLE PARALLEL SAFE - AS $$int4eq$$; - --- By default, planner does not think that's selective -EXPLAIN (COSTS OFF) -SELECT * FROM tenk1 a JOIN tenk1 b ON a.unique1 = b.unique1 -WHERE my_int_eq(a.unique2, 42); - --- With support function that knows it's int4eq, we get a different plan -CREATE FUNCTION test_support_func(internal) - RETURNS internal - AS :'regresslib', 'test_support_func' - LANGUAGE C STRICT; - -ALTER FUNCTION my_int_eq(int, int) SUPPORT test_support_func; - -EXPLAIN (COSTS OFF) -SELECT * FROM tenk1 a JOIN tenk1 b ON a.unique1 = b.unique1 -WHERE my_int_eq(a.unique2, 42); - --- Also test non-default rowcount estimate -CREATE FUNCTION my_gen_series(int, int) RETURNS SETOF integer - LANGUAGE internal STRICT IMMUTABLE PARALLEL SAFE - AS $$generate_series_int4$$ - SUPPORT test_support_func; - -EXPLAIN (COSTS OFF) -SELECT * FROM tenk1 a JOIN my_gen_series(1,1000) g ON a.unique1 = g; - -EXPLAIN (COSTS OFF) -SELECT * FROM tenk1 a JOIN my_gen_series(1,10) g ON a.unique1 = g; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmultirangetypes.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmultirangetypes.sql deleted file mode 100644 index 1abcaeddb5..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmultirangetypes.sql +++ /dev/null @@ -1,856 +0,0 @@ --- Tests for multirange data types. - --- --- test input parser --- - --- negative tests; should fail -select ''::textmultirange; -select '{,}'::textmultirange; -select '{(,)}.'::textmultirange; -select '{[a,c),}'::textmultirange; -select '{,[a,c)}'::textmultirange; -select '{-[a,z)}'::textmultirange; -select '{[a,z) - }'::textmultirange; -select '{(",a)}'::textmultirange; -select '{(,,a)}'::textmultirange; -select '{(),a)}'::textmultirange; -select '{(a,))}'::textmultirange; -select '{(],a)}'::textmultirange; -select '{(a,])}'::textmultirange; -select '{[z,a]}'::textmultirange; - --- should succeed -select '{}'::textmultirange; -select ' {} '::textmultirange; -select ' { empty, empty } '::textmultirange; -select ' {( " a " " a ", " z " " z " ) }'::textmultirange; -select textrange('\\\\', repeat('a', 200))::textmultirange; -select '{(,z)}'::textmultirange; -select '{(a,)}'::textmultirange; -select '{[,z]}'::textmultirange; -select '{[a,]}'::textmultirange; -select '{(,)}'::textmultirange; -select '{[ , ]}'::textmultirange; -select '{["",""]}'::textmultirange; -select '{[",",","]}'::textmultirange; -select '{["\\","\\"]}'::textmultirange; -select '{["""","\""]}'::textmultirange; -select '{(\\,a)}'::textmultirange; -select '{((,z)}'::textmultirange; -select '{([,z)}'::textmultirange; -select '{(!,()}'::textmultirange; -select '{(!,[)}'::textmultirange; -select '{[a,a]}'::textmultirange; -select '{[a,a],[a,b]}'::textmultirange; -select '{[a,b), [b,e]}'::textmultirange; -select '{[a,d), [b,f]}'::textmultirange; -select '{[a,a],[b,b]}'::textmultirange; --- without canonicalization, we can't join these: -select '{[a,a], [b,b]}'::textmultirange; --- with canonicalization, we can join these: -select '{[1,2], [3,4]}'::int4multirange; -select '{[a,a], [b,b], [c,c]}'::textmultirange; -select '{[a,d], [b,e]}'::textmultirange; -select '{[a,d), [d,e)}'::textmultirange; --- these are allowed but normalize to empty: -select '{[a,a)}'::textmultirange; -select '{(a,a]}'::textmultirange; -select '{(a,a)}'::textmultirange; - --- --- test the constructor ---- -select textmultirange(); -select textmultirange(textrange('a', 'c')); -select textmultirange(textrange('a', 'c'), textrange('f', 'g')); -select textmultirange(textrange('\\\\', repeat('a', 200)), textrange('c', 'd')); - --- --- test casts, both a built-in range type and a user-defined one: --- -select 'empty'::int4range::int4multirange; -select int4range(1, 3)::int4multirange; -select int4range(1, null)::int4multirange; -select int4range(null, null)::int4multirange; -select 'empty'::textrange::textmultirange; -select textrange('a', 'c')::textmultirange; -select textrange('a', null)::textmultirange; -select textrange(null, null)::textmultirange; - --- --- test unnest(multirange) function --- -select unnest(int4multirange(int4range('5', '6'), int4range('1', '2'))); -select unnest(textmultirange(textrange('a', 'b'), textrange('d', 'e'))); -select unnest(textmultirange(textrange('\\\\', repeat('a', 200)), textrange('c', 'd'))); - --- --- create some test data and test the operators --- - -CREATE TABLE nummultirange_test (nmr NUMMULTIRANGE); -CREATE INDEX nummultirange_test_btree ON nummultirange_test(nmr); - -INSERT INTO nummultirange_test VALUES('{}'); -INSERT INTO nummultirange_test VALUES('{[,)}'); -INSERT INTO nummultirange_test VALUES('{[3,]}'); -INSERT INTO nummultirange_test VALUES('{[,), [3,]}'); -INSERT INTO nummultirange_test VALUES('{[, 5)}'); -INSERT INTO nummultirange_test VALUES(nummultirange()); -INSERT INTO nummultirange_test VALUES(nummultirange(variadic '{}'::numrange[])); -INSERT INTO nummultirange_test VALUES(nummultirange(numrange(1.1, 2.2))); -INSERT INTO nummultirange_test VALUES('{empty}'); -INSERT INTO nummultirange_test VALUES(nummultirange(numrange(1.7, 1.7, '[]'), numrange(1.7, 1.9))); -INSERT INTO nummultirange_test VALUES(nummultirange(numrange(1.7, 1.7, '[]'), numrange(1.9, 2.1))); - -SELECT nmr, isempty(nmr), lower(nmr), upper(nmr) FROM nummultirange_test ORDER BY nmr; -SELECT nmr, lower_inc(nmr), lower_inf(nmr), upper_inc(nmr), upper_inf(nmr) FROM nummultirange_test ORDER BY nmr; - -SELECT * FROM nummultirange_test WHERE nmr = '{}'; -SELECT * FROM nummultirange_test WHERE nmr = '{(,5)}'; -SELECT * FROM nummultirange_test WHERE nmr = '{[3,)}'; -SELECT * FROM nummultirange_test WHERE nmr = '{[1.7,1.7]}'; -SELECT * FROM nummultirange_test WHERE nmr = '{[1.7,1.7],[1.9,2.1)}'; -SELECT * FROM nummultirange_test WHERE nmr < '{}'; -SELECT * FROM nummultirange_test WHERE nmr < '{[-1000.0, -1000.0]}'; -SELECT * FROM nummultirange_test WHERE nmr < '{[0.0, 1.0]}'; -SELECT * FROM nummultirange_test WHERE nmr < '{[1000.0, 1001.0]}'; -SELECT * FROM nummultirange_test WHERE nmr <= '{}'; -SELECT * FROM nummultirange_test WHERE nmr <= '{[3,)}'; -SELECT * FROM nummultirange_test WHERE nmr >= '{}'; -SELECT * FROM nummultirange_test WHERE nmr >= '{[3,)}'; -SELECT * FROM nummultirange_test WHERE nmr > '{}'; -SELECT * FROM nummultirange_test WHERE nmr > '{[-1000.0, -1000.0]}'; -SELECT * FROM nummultirange_test WHERE nmr > '{[0.0, 1.0]}'; -SELECT * FROM nummultirange_test WHERE nmr > '{[1000.0, 1001.0]}'; -SELECT * FROM nummultirange_test WHERE nmr <> '{}'; -SELECT * FROM nummultirange_test WHERE nmr <> '{(,5)}'; - -select nummultirange(numrange(2.0, 1.0)); -select nummultirange(numrange(5.0, 6.0), numrange(1.0, 2.0)); - -analyze nummultirange_test; - --- overlaps -SELECT * FROM nummultirange_test WHERE range_overlaps_multirange(numrange(4.0, 4.2), nmr); -SELECT * FROM nummultirange_test WHERE numrange(4.0, 4.2) && nmr; -SELECT * FROM nummultirange_test WHERE multirange_overlaps_range(nmr, numrange(4.0, 4.2)); -SELECT * FROM nummultirange_test WHERE nmr && numrange(4.0, 4.2); -SELECT * FROM nummultirange_test WHERE multirange_overlaps_multirange(nmr, nummultirange(numrange(4.0, 4.2), numrange(6.0, 7.0))); -SELECT * FROM nummultirange_test WHERE nmr && nummultirange(numrange(4.0, 4.2), numrange(6.0, 7.0)); -SELECT * FROM nummultirange_test WHERE nmr && nummultirange(numrange(6.0, 7.0)); -SELECT * FROM nummultirange_test WHERE nmr && nummultirange(numrange(6.0, 7.0), numrange(8.0, 9.0)); - --- mr contains x -SELECT * FROM nummultirange_test WHERE multirange_contains_elem(nmr, 4.0); -SELECT * FROM nummultirange_test WHERE nmr @> 4.0; -SELECT * FROM nummultirange_test WHERE multirange_contains_range(nmr, numrange(4.0, 4.2)); -SELECT * FROM nummultirange_test WHERE nmr @> numrange(4.0, 4.2); -SELECT * FROM nummultirange_test WHERE multirange_contains_multirange(nmr, '{[4.0,4.2), [6.0, 8.0)}'); -SELECT * FROM nummultirange_test WHERE nmr @> '{[4.0,4.2), [6.0, 8.0)}'::nummultirange; - --- x is contained by mr -SELECT * FROM nummultirange_test WHERE elem_contained_by_multirange(4.0, nmr); -SELECT * FROM nummultirange_test WHERE 4.0 <@ nmr; -SELECT * FROM nummultirange_test WHERE range_contained_by_multirange(numrange(4.0, 4.2), nmr); -SELECT * FROM nummultirange_test WHERE numrange(4.0, 4.2) <@ nmr; -SELECT * FROM nummultirange_test WHERE multirange_contained_by_multirange('{[4.0,4.2), [6.0, 8.0)}', nmr); -SELECT * FROM nummultirange_test WHERE '{[4.0,4.2), [6.0, 8.0)}'::nummultirange <@ nmr; - --- overlaps -SELECT 'empty'::numrange && nummultirange(); -SELECT 'empty'::numrange && nummultirange(numrange(1,2)); -SELECT nummultirange() && 'empty'::numrange; -SELECT nummultirange(numrange(1,2)) && 'empty'::numrange; -SELECT nummultirange() && nummultirange(); -SELECT nummultirange() && nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) && nummultirange(); -SELECT nummultirange(numrange(3,4)) && nummultirange(numrange(1,2), numrange(7,8)); -SELECT nummultirange(numrange(1,2), numrange(7,8)) && nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(3,4)) && nummultirange(numrange(1,2), numrange(3.5,8)); -SELECT nummultirange(numrange(1,2), numrange(3.5,8)) && numrange(3,4); -SELECT nummultirange(numrange(1,2), numrange(3.5,8)) && nummultirange(numrange(3,4)); -select '{(10,20),(30,40),(50,60)}'::nummultirange && '(42,92)'::numrange; - --- contains -SELECT nummultirange() @> nummultirange(); -SELECT nummultirange() @> 'empty'::numrange; -SELECT nummultirange(numrange(null,null)) @> numrange(1,2); -SELECT nummultirange(numrange(null,null)) @> numrange(null,2); -SELECT nummultirange(numrange(null,null)) @> numrange(2,null); -SELECT nummultirange(numrange(null,5)) @> numrange(null,3); -SELECT nummultirange(numrange(null,5)) @> numrange(null,8); -SELECT nummultirange(numrange(5,null)) @> numrange(8,null); -SELECT nummultirange(numrange(5,null)) @> numrange(3,null); -SELECT nummultirange(numrange(1,5)) @> numrange(8,9); -SELECT nummultirange(numrange(1,5)) @> numrange(3,9); -SELECT nummultirange(numrange(1,5)) @> numrange(1,4); -SELECT nummultirange(numrange(1,5)) @> numrange(1,5); -SELECT nummultirange(numrange(-4,-2), numrange(1,5)) @> numrange(1,5); -SELECT nummultirange(numrange(1,5), numrange(8,9)) @> numrange(1,5); -SELECT nummultirange(numrange(1,5), numrange(8,9)) @> numrange(6,7); -SELECT nummultirange(numrange(1,5), numrange(6,9)) @> numrange(6,7); -SELECT '{[1,5)}'::nummultirange @> '{[1,5)}'; -SELECT '{[-4,-2), [1,5)}'::nummultirange @> '{[1,5)}'; -SELECT '{[1,5), [8,9)}'::nummultirange @> '{[1,5)}'; -SELECT '{[1,5), [8,9)}'::nummultirange @> '{[6,7)}'; -SELECT '{[1,5), [6,9)}'::nummultirange @> '{[6,7)}'; -select '{(10,20),(30,40),(50,60)}'::nummultirange @> '(52,56)'::numrange; -SELECT numrange(null,null) @> nummultirange(numrange(1,2)); -SELECT numrange(null,null) @> nummultirange(numrange(null,2)); -SELECT numrange(null,null) @> nummultirange(numrange(2,null)); -SELECT numrange(null,5) @> nummultirange(numrange(null,3)); -SELECT numrange(null,5) @> nummultirange(numrange(null,8)); -SELECT numrange(5,null) @> nummultirange(numrange(8,null)); -SELECT numrange(5,null) @> nummultirange(numrange(3,null)); -SELECT numrange(1,5) @> nummultirange(numrange(8,9)); -SELECT numrange(1,5) @> nummultirange(numrange(3,9)); -SELECT numrange(1,5) @> nummultirange(numrange(1,4)); -SELECT numrange(1,5) @> nummultirange(numrange(1,5)); -SELECT numrange(1,9) @> nummultirange(numrange(-4,-2), numrange(1,5)); -SELECT numrange(1,9) @> nummultirange(numrange(1,5), numrange(8,9)); -SELECT numrange(1,9) @> nummultirange(numrange(1,5), numrange(6,9)); -SELECT numrange(1,9) @> nummultirange(numrange(1,5), numrange(6,10)); -SELECT '{[1,9)}' @> '{[1,5)}'::nummultirange; -SELECT '{[1,9)}' @> '{[-4,-2), [1,5)}'::nummultirange; -SELECT '{[1,9)}' @> '{[1,5), [8,9)}'::nummultirange; -SELECT '{[1,9)}' @> '{[1,5), [6,9)}'::nummultirange; -SELECT '{[1,9)}' @> '{[1,5), [6,10)}'::nummultirange; - --- is contained by -SELECT nummultirange() <@ nummultirange(); -SELECT 'empty'::numrange <@ nummultirange(); -SELECT numrange(1,2) <@ nummultirange(numrange(null,null)); -SELECT numrange(null,2) <@ nummultirange(numrange(null,null)); -SELECT numrange(2,null) <@ nummultirange(numrange(null,null)); -SELECT numrange(null,3) <@ nummultirange(numrange(null,5)); -SELECT numrange(null,8) <@ nummultirange(numrange(null,5)); -SELECT numrange(8,null) <@ nummultirange(numrange(5,null)); -SELECT numrange(3,null) <@ nummultirange(numrange(5,null)); -SELECT numrange(8,9) <@ nummultirange(numrange(1,5)); -SELECT numrange(3,9) <@ nummultirange(numrange(1,5)); -SELECT numrange(1,4) <@ nummultirange(numrange(1,5)); -SELECT numrange(1,5) <@ nummultirange(numrange(1,5)); -SELECT numrange(1,5) <@ nummultirange(numrange(-4,-2), numrange(1,5)); -SELECT numrange(1,5) <@ nummultirange(numrange(1,5), numrange(8,9)); -SELECT numrange(6,7) <@ nummultirange(numrange(1,5), numrange(8,9)); -SELECT numrange(6,7) <@ nummultirange(numrange(1,5), numrange(6,9)); -SELECT '{[1,5)}' <@ '{[1,5)}'::nummultirange; -SELECT '{[1,5)}' <@ '{[-4,-2), [1,5)}'::nummultirange; -SELECT '{[1,5)}' <@ '{[1,5), [8,9)}'::nummultirange; -SELECT '{[6,7)}' <@ '{[1,5), [8,9)}'::nummultirange; -SELECT '{[6,7)}' <@ '{[1,5), [6,9)}'::nummultirange; -SELECT nummultirange(numrange(1,2)) <@ numrange(null,null); -SELECT nummultirange(numrange(null,2)) <@ numrange(null,null); -SELECT nummultirange(numrange(2,null)) <@ numrange(null,null); -SELECT nummultirange(numrange(null,3)) <@ numrange(null,5); -SELECT nummultirange(numrange(null,8)) <@ numrange(null,5); -SELECT nummultirange(numrange(8,null)) <@ numrange(5,null); -SELECT nummultirange(numrange(3,null)) <@ numrange(5,null); -SELECT nummultirange(numrange(8,9)) <@ numrange(1,5); -SELECT nummultirange(numrange(3,9)) <@ numrange(1,5); -SELECT nummultirange(numrange(1,4)) <@ numrange(1,5); -SELECT nummultirange(numrange(1,5)) <@ numrange(1,5); -SELECT nummultirange(numrange(-4,-2), numrange(1,5)) <@ numrange(1,9); -SELECT nummultirange(numrange(1,5), numrange(8,9)) <@ numrange(1,9); -SELECT nummultirange(numrange(1,5), numrange(6,9)) <@ numrange(1,9); -SELECT nummultirange(numrange(1,5), numrange(6,10)) <@ numrange(1,9); -SELECT '{[1,5)}'::nummultirange <@ '{[1,9)}'; -SELECT '{[-4,-2), [1,5)}'::nummultirange <@ '{[1,9)}'; -SELECT '{[1,5), [8,9)}'::nummultirange <@ '{[1,9)}'; -SELECT '{[1,5), [6,9)}'::nummultirange <@ '{[1,9)}'; -SELECT '{[1,5), [6,10)}'::nummultirange <@ '{[1,9)}'; - --- overleft -SELECT 'empty'::numrange &< nummultirange(); -SELECT 'empty'::numrange &< nummultirange(numrange(1,2)); -SELECT nummultirange() &< 'empty'::numrange; -SELECT nummultirange(numrange(1,2)) &< 'empty'::numrange; -SELECT nummultirange() &< nummultirange(); -SELECT nummultirange(numrange(1,2)) &< nummultirange(); -SELECT nummultirange() &< nummultirange(numrange(1,2)); -SELECT numrange(6,7) &< nummultirange(numrange(3,4)); -SELECT numrange(1,2) &< nummultirange(numrange(3,4)); -SELECT numrange(1,4) &< nummultirange(numrange(3,4)); -SELECT numrange(1,6) &< nummultirange(numrange(3,4)); -SELECT numrange(3.5,6) &< nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(6,7)) &< numrange(3,4); -SELECT nummultirange(numrange(1,2)) &< numrange(3,4); -SELECT nummultirange(numrange(1,4)) &< numrange(3,4); -SELECT nummultirange(numrange(1,6)) &< numrange(3,4); -SELECT nummultirange(numrange(3.5,6)) &< numrange(3,4); -SELECT nummultirange(numrange(6,7)) &< nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,2)) &< nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,4)) &< nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,6)) &< nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(3.5,6)) &< nummultirange(numrange(3,4)); - --- overright -SELECT nummultirange() &> 'empty'::numrange; -SELECT nummultirange(numrange(1,2)) &> 'empty'::numrange; -SELECT 'empty'::numrange &> nummultirange(); -SELECT 'empty'::numrange &> nummultirange(numrange(1,2)); -SELECT nummultirange() &> nummultirange(); -SELECT nummultirange() &> nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) &> nummultirange(); -SELECT nummultirange(numrange(3,4)) &> numrange(6,7); -SELECT nummultirange(numrange(3,4)) &> numrange(1,2); -SELECT nummultirange(numrange(3,4)) &> numrange(1,4); -SELECT nummultirange(numrange(3,4)) &> numrange(1,6); -SELECT nummultirange(numrange(3,4)) &> numrange(3.5,6); -SELECT numrange(3,4) &> nummultirange(numrange(6,7)); -SELECT numrange(3,4) &> nummultirange(numrange(1,2)); -SELECT numrange(3,4) &> nummultirange(numrange(1,4)); -SELECT numrange(3,4) &> nummultirange(numrange(1,6)); -SELECT numrange(3,4) &> nummultirange(numrange(3.5,6)); -SELECT nummultirange(numrange(3,4)) &> nummultirange(numrange(6,7)); -SELECT nummultirange(numrange(3,4)) &> nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(3,4)) &> nummultirange(numrange(1,4)); -SELECT nummultirange(numrange(3,4)) &> nummultirange(numrange(1,6)); -SELECT nummultirange(numrange(3,4)) &> nummultirange(numrange(3.5,6)); - --- meets -SELECT 'empty'::numrange -|- nummultirange(); -SELECT 'empty'::numrange -|- nummultirange(numrange(1,2)); -SELECT nummultirange() -|- 'empty'::numrange; -SELECT nummultirange(numrange(1,2)) -|- 'empty'::numrange; -SELECT nummultirange() -|- nummultirange(); -SELECT nummultirange(numrange(1,2)) -|- nummultirange(); -SELECT nummultirange() -|- nummultirange(numrange(1,2)); -SELECT numrange(1,2) -|- nummultirange(numrange(2,4)); -SELECT numrange(1,2) -|- nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,2)) -|- numrange(2,4); -SELECT nummultirange(numrange(1,2)) -|- numrange(3,4); -SELECT nummultirange(numrange(1,2)) -|- nummultirange(numrange(2,4)); -SELECT nummultirange(numrange(1,2)) -|- nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,2), numrange(5,6)) -|- nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,2), numrange(5,6)) -|- nummultirange(numrange(6,7)); -SELECT nummultirange(numrange(1,2), numrange(5,6)) -|- nummultirange(numrange(8,9)); -SELECT nummultirange(numrange(1,2)) -|- nummultirange(numrange(2,4), numrange(6,7)); - --- strictly left -select 'empty'::numrange << nummultirange(); -select numrange(1,2) << nummultirange(); -select numrange(1,2) << nummultirange(numrange(3,4)); -select numrange(1,2) << nummultirange(numrange(0,4)); -select numrange(1,2) << nummultirange(numrange(0,4), numrange(7,8)); -select nummultirange() << 'empty'::numrange; -select nummultirange() << numrange(1,2); -select nummultirange(numrange(3,4)) << numrange(3,6); -select nummultirange(numrange(0,2)) << numrange(3,6); -select nummultirange(numrange(0,2), numrange(7,8)) << numrange(3,6); -select nummultirange(numrange(-4,-2), numrange(0,2)) << numrange(3,6); -select nummultirange() << nummultirange(); -select nummultirange() << nummultirange(numrange(1,2)); -select nummultirange(numrange(1,2)) << nummultirange(); -select nummultirange(numrange(1,2)) << nummultirange(numrange(1,2)); -select nummultirange(numrange(1,2)) << nummultirange(numrange(3,4)); -select nummultirange(numrange(1,2)) << nummultirange(numrange(3,4), numrange(7,8)); -select nummultirange(numrange(1,2), numrange(4,5)) << nummultirange(numrange(3,4), numrange(7,8)); - --- strictly right -select nummultirange() >> 'empty'::numrange; -select nummultirange() >> numrange(1,2); -select nummultirange(numrange(3,4)) >> numrange(1,2); -select nummultirange(numrange(0,4)) >> numrange(1,2); -select nummultirange(numrange(0,4), numrange(7,8)) >> numrange(1,2); -select 'empty'::numrange >> nummultirange(); -select numrange(1,2) >> nummultirange(); -select numrange(3,6) >> nummultirange(numrange(3,4)); -select numrange(3,6) >> nummultirange(numrange(0,2)); -select numrange(3,6) >> nummultirange(numrange(0,2), numrange(7,8)); -select numrange(3,6) >> nummultirange(numrange(-4,-2), numrange(0,2)); -select nummultirange() >> nummultirange(); -select nummultirange(numrange(1,2)) >> nummultirange(); -select nummultirange() >> nummultirange(numrange(1,2)); -select nummultirange(numrange(1,2)) >> nummultirange(numrange(1,2)); -select nummultirange(numrange(3,4)) >> nummultirange(numrange(1,2)); -select nummultirange(numrange(3,4), numrange(7,8)) >> nummultirange(numrange(1,2)); -select nummultirange(numrange(3,4), numrange(7,8)) >> nummultirange(numrange(1,2), numrange(4,5)); - --- union -SELECT nummultirange() + nummultirange(); -SELECT nummultirange() + nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) + nummultirange(); -SELECT nummultirange(numrange(1,2)) + nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) + nummultirange(numrange(2,4)); -SELECT nummultirange(numrange(1,2)) + nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) + nummultirange(numrange(2,4)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) + nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) + nummultirange(numrange(0,9)); - --- merge -SELECT range_merge(nummultirange()); -SELECT range_merge(nummultirange(numrange(1,2))); -SELECT range_merge(nummultirange(numrange(1,2), numrange(7,8))); - --- minus -SELECT nummultirange() - nummultirange(); -SELECT nummultirange() - nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) - nummultirange(); -SELECT nummultirange(numrange(1,2), numrange(3,4)) - nummultirange(); -SELECT nummultirange(numrange(1,2)) - nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) - nummultirange(numrange(2,4)); -SELECT nummultirange(numrange(1,2)) - nummultirange(numrange(3,4)); -SELECT nummultirange(numrange(1,4)) - nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,4)) - nummultirange(numrange(2,3)); -SELECT nummultirange(numrange(1,4)) - nummultirange(numrange(0,8)); -SELECT nummultirange(numrange(1,4)) - nummultirange(numrange(0,2)); -SELECT nummultirange(numrange(1,8)) - nummultirange(numrange(0,2), numrange(3,4)); -SELECT nummultirange(numrange(1,8)) - nummultirange(numrange(2,3), numrange(5,null)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) - nummultirange(numrange(-2,0)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) - nummultirange(numrange(2,4)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) - nummultirange(numrange(3,5)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) - nummultirange(numrange(0,9)); -SELECT nummultirange(numrange(1,3), numrange(4,5)) - nummultirange(numrange(2,9)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) - nummultirange(numrange(8,9)); -SELECT nummultirange(numrange(1,2), numrange(4,5)) - nummultirange(numrange(-2,0), numrange(8,9)); - --- intersection -SELECT nummultirange() * nummultirange(); -SELECT nummultirange() * nummultirange(numrange(1,2)); -SELECT nummultirange(numrange(1,2)) * nummultirange(); -SELECT '{[1,3)}'::nummultirange * '{[1,5)}'::nummultirange; -SELECT '{[1,3)}'::nummultirange * '{[0,5)}'::nummultirange; -SELECT '{[1,3)}'::nummultirange * '{[0,2)}'::nummultirange; -SELECT '{[1,3)}'::nummultirange * '{[2,5)}'::nummultirange; -SELECT '{[1,4)}'::nummultirange * '{[2,3)}'::nummultirange; -SELECT '{[1,4)}'::nummultirange * '{[0,2), [3,5)}'::nummultirange; -SELECT '{[1,4), [7,10)}'::nummultirange * '{[0,8), [9,12)}'::nummultirange; -SELECT '{[1,4), [7,10)}'::nummultirange * '{[9,12)}'::nummultirange; -SELECT '{[1,4), [7,10)}'::nummultirange * '{[-5,-4), [5,6), [9,12)}'::nummultirange; -SELECT '{[1,4), [7,10)}'::nummultirange * '{[0,2), [3,8), [9,12)}'::nummultirange; -SELECT '{[1,4), [7,10)}'::nummultirange * '{[0,2), [3,8), [9,12)}'::nummultirange; - --- test GiST index -create table test_multirange_gist(mr int4multirange); -insert into test_multirange_gist select int4multirange(int4range(g, g+10),int4range(g+20, g+30),int4range(g+40, g+50)) from generate_series(1,2000) g; -insert into test_multirange_gist select '{}'::int4multirange from generate_series(1,500) g; -insert into test_multirange_gist select int4multirange(int4range(g, g+10000)) from generate_series(1,1000) g; -insert into test_multirange_gist select int4multirange(int4range(NULL, g*10, '(]'), int4range(g*10, g*20, '(]')) from generate_series(1,100) g; -insert into test_multirange_gist select int4multirange(int4range(g*10, g*20, '(]'), int4range(g*20, NULL, '(]')) from generate_series(1,100) g; -create index test_mulrirange_gist_idx on test_multirange_gist using gist (mr); - --- test statistics and selectivity estimation as well --- --- We don't check the accuracy of selectivity estimation, but at least check --- it doesn't fall. -analyze test_multirange_gist; - --- first, verify non-indexed results -SET enable_seqscan = t; -SET enable_indexscan = f; -SET enable_bitmapscan = f; - -select count(*) from test_multirange_gist where mr = '{}'::int4multirange; -select count(*) from test_multirange_gist where mr @> 'empty'::int4range; -select count(*) from test_multirange_gist where mr && 'empty'::int4range; -select count(*) from test_multirange_gist where mr <@ 'empty'::int4range; -select count(*) from test_multirange_gist where mr << 'empty'::int4range; -select count(*) from test_multirange_gist where mr >> 'empty'::int4range; -select count(*) from test_multirange_gist where mr &< 'empty'::int4range; -select count(*) from test_multirange_gist where mr &> 'empty'::int4range; -select count(*) from test_multirange_gist where mr -|- 'empty'::int4range; -select count(*) from test_multirange_gist where mr @> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr @> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr && '{}'::int4multirange; -select count(*) from test_multirange_gist where mr <@ '{}'::int4multirange; -select count(*) from test_multirange_gist where mr << '{}'::int4multirange; -select count(*) from test_multirange_gist where mr >> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr &< '{}'::int4multirange; -select count(*) from test_multirange_gist where mr &> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr -|- '{}'::int4multirange; - -select count(*) from test_multirange_gist where mr = int4multirange(int4range(10,20), int4range(30,40), int4range(50,60)); -select count(*) from test_multirange_gist where mr @> 10; -select count(*) from test_multirange_gist where mr @> int4range(10,20); -select count(*) from test_multirange_gist where mr && int4range(10,20); -select count(*) from test_multirange_gist where mr <@ int4range(10,50); -select count(*) from test_multirange_gist where mr << int4range(100,500); -select count(*) from test_multirange_gist where mr >> int4range(100,500); -select count(*) from test_multirange_gist where mr &< int4range(100,500); -select count(*) from test_multirange_gist where mr &> int4range(100,500); -select count(*) from test_multirange_gist where mr -|- int4range(100,500); -select count(*) from test_multirange_gist where mr @> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr @> int4multirange(int4range(10,20), int4range(30,40)); -select count(*) from test_multirange_gist where mr && '{(10,20),(30,40),(50,60)}'::int4multirange; -select count(*) from test_multirange_gist where mr <@ '{(10,30),(40,60),(70,90)}'::int4multirange; -select count(*) from test_multirange_gist where mr << int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr >> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr &< int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr &> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr -|- int4multirange(int4range(100,200), int4range(400,500)); - --- now check same queries using index -SET enable_seqscan = f; -SET enable_indexscan = t; -SET enable_bitmapscan = f; - -select count(*) from test_multirange_gist where mr = '{}'::int4multirange; -select count(*) from test_multirange_gist where mr @> 'empty'::int4range; -select count(*) from test_multirange_gist where mr && 'empty'::int4range; -select count(*) from test_multirange_gist where mr <@ 'empty'::int4range; -select count(*) from test_multirange_gist where mr << 'empty'::int4range; -select count(*) from test_multirange_gist where mr >> 'empty'::int4range; -select count(*) from test_multirange_gist where mr &< 'empty'::int4range; -select count(*) from test_multirange_gist where mr &> 'empty'::int4range; -select count(*) from test_multirange_gist where mr -|- 'empty'::int4range; -select count(*) from test_multirange_gist where mr @> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr @> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr && '{}'::int4multirange; -select count(*) from test_multirange_gist where mr <@ '{}'::int4multirange; -select count(*) from test_multirange_gist where mr << '{}'::int4multirange; -select count(*) from test_multirange_gist where mr >> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr &< '{}'::int4multirange; -select count(*) from test_multirange_gist where mr &> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr -|- '{}'::int4multirange; - -select count(*) from test_multirange_gist where mr @> 'empty'::int4range; -select count(*) from test_multirange_gist where mr = int4multirange(int4range(10,20), int4range(30,40), int4range(50,60)); -select count(*) from test_multirange_gist where mr @> 10; -select count(*) from test_multirange_gist where mr @> int4range(10,20); -select count(*) from test_multirange_gist where mr && int4range(10,20); -select count(*) from test_multirange_gist where mr <@ int4range(10,50); -select count(*) from test_multirange_gist where mr << int4range(100,500); -select count(*) from test_multirange_gist where mr >> int4range(100,500); -select count(*) from test_multirange_gist where mr &< int4range(100,500); -select count(*) from test_multirange_gist where mr &> int4range(100,500); -select count(*) from test_multirange_gist where mr -|- int4range(100,500); -select count(*) from test_multirange_gist where mr @> '{}'::int4multirange; -select count(*) from test_multirange_gist where mr @> int4multirange(int4range(10,20), int4range(30,40)); -select count(*) from test_multirange_gist where mr && '{(10,20),(30,40),(50,60)}'::int4multirange; -select count(*) from test_multirange_gist where mr <@ '{(10,30),(40,60),(70,90)}'::int4multirange; -select count(*) from test_multirange_gist where mr << int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr >> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr &< int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr &> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_multirange_gist where mr -|- int4multirange(int4range(100,200), int4range(400,500)); - -drop table test_multirange_gist; - --- --- range_agg function --- -create table reservations ( room_id integer not null, booked_during daterange ); -insert into reservations values --- 1: has a meets and a gap -(1, daterange('2018-07-01', '2018-07-07')), -(1, daterange('2018-07-07', '2018-07-14')), -(1, daterange('2018-07-20', '2018-07-22')), --- 2: just a single row -(2, daterange('2018-07-01', '2018-07-03')), --- 3: one null range -(3, NULL), --- 4: two null ranges -(4, NULL), -(4, NULL), --- 5: a null range and a non-null range -(5, NULL), -(5, daterange('2018-07-01', '2018-07-03')), --- 6: has overlap -(6, daterange('2018-07-01', '2018-07-07')), -(6, daterange('2018-07-05', '2018-07-10')), --- 7: two ranges that meet: no gap or overlap -(7, daterange('2018-07-01', '2018-07-07')), -(7, daterange('2018-07-07', '2018-07-14')), --- 8: an empty range -(8, 'empty'::daterange) -; -SELECT room_id, range_agg(booked_during) -FROM reservations -GROUP BY room_id -ORDER BY room_id; - --- range_agg on a custom range type too -SELECT range_agg(r) -FROM (VALUES - ('[a,c]'::textrange), - ('[b,b]'::textrange), - ('[c,f]'::textrange), - ('[g,h)'::textrange), - ('[h,j)'::textrange) - ) t(r); - --- range_agg with multirange inputs -select range_agg(nmr) from nummultirange_test; -select range_agg(nmr) from nummultirange_test where false; -select range_agg(null::nummultirange) from nummultirange_test; -select range_agg(nmr) from (values ('{}'::nummultirange)) t(nmr); -select range_agg(nmr) from (values ('{}'::nummultirange), ('{}'::nummultirange)) t(nmr); -select range_agg(nmr) from (values ('{[1,2]}'::nummultirange)) t(nmr); -select range_agg(nmr) from (values ('{[1,2], [5,6]}'::nummultirange)) t(nmr); -select range_agg(nmr) from (values ('{[1,2], [2,3]}'::nummultirange)) t(nmr); -select range_agg(nmr) from (values ('{[1,2]}'::nummultirange), ('{[5,6]}'::nummultirange)) t(nmr); -select range_agg(nmr) from (values ('{[1,2]}'::nummultirange), ('{[2,3]}'::nummultirange)) t(nmr); - --- --- range_intersect_agg function --- -select range_intersect_agg(nmr) from nummultirange_test; -select range_intersect_agg(nmr) from nummultirange_test where false; -select range_intersect_agg(null::nummultirange) from nummultirange_test; -select range_intersect_agg(nmr) from (values ('{[1,3]}'::nummultirange), ('{[6,12]}'::nummultirange)) t(nmr); -select range_intersect_agg(nmr) from (values ('{[1,6]}'::nummultirange), ('{[3,12]}'::nummultirange)) t(nmr); -select range_intersect_agg(nmr) from (values ('{[1,6], [10,12]}'::nummultirange), ('{[4,14]}'::nummultirange)) t(nmr); --- test with just one input: -select range_intersect_agg(nmr) from (values ('{}'::nummultirange)) t(nmr); -select range_intersect_agg(nmr) from (values ('{[1,2]}'::nummultirange)) t(nmr); -select range_intersect_agg(nmr) from (values ('{[1,6], [10,12]}'::nummultirange)) t(nmr); -select range_intersect_agg(nmr) from nummultirange_test where nmr @> 4.0; - -create table nummultirange_test2(nmr nummultirange); -create index nummultirange_test2_hash_idx on nummultirange_test2 using hash (nmr); - -INSERT INTO nummultirange_test2 VALUES('{[, 5)}'); -INSERT INTO nummultirange_test2 VALUES(nummultirange(numrange(1.1, 2.2))); -INSERT INTO nummultirange_test2 VALUES(nummultirange(numrange(1.1, 2.2))); -INSERT INTO nummultirange_test2 VALUES(nummultirange(numrange(1.1, 2.2,'()'))); -INSERT INTO nummultirange_test2 VALUES('{}'); - -select * from nummultirange_test2 where nmr = '{}'; -select * from nummultirange_test2 where nmr = nummultirange(numrange(1.1, 2.2)); -select * from nummultirange_test2 where nmr = nummultirange(numrange(1.1, 2.3)); - -set enable_nestloop=t; -set enable_hashjoin=f; -set enable_mergejoin=f; -select * from nummultirange_test natural join nummultirange_test2 order by nmr; -set enable_nestloop=f; -set enable_hashjoin=t; -set enable_mergejoin=f; -select * from nummultirange_test natural join nummultirange_test2 order by nmr; -set enable_nestloop=f; -set enable_hashjoin=f; -set enable_mergejoin=t; -select * from nummultirange_test natural join nummultirange_test2 order by nmr; - -set enable_nestloop to default; -set enable_hashjoin to default; -set enable_mergejoin to default; - -DROP TABLE nummultirange_test2; - --- --- Test user-defined multirange of floats --- - -select '{[123.001, 5.e9)}'::float8multirange @> 888.882::float8; -create table float8multirange_test(f8mr float8multirange, i int); -insert into float8multirange_test values(float8multirange(float8range(-100.00007, '1.111113e9')), 42); -select * from float8multirange_test; -drop table float8multirange_test; - --- --- Test multirange types over domains --- - -create domain mydomain as int4; -create type mydomainrange as range(subtype=mydomain); -select '{[4,50)}'::mydomainmultirange @> 7::mydomain; -drop domain mydomain cascade; - --- --- Test domains over multirange types --- - -create domain restrictedmultirange as int4multirange check (upper(value) < 10); -select '{[4,5)}'::restrictedmultirange @> 7; -select '{[4,50)}'::restrictedmultirange @> 7; -- should fail -drop domain restrictedmultirange; - ---- --- Check automatic naming of multiranges ---- - -create type intr as range(subtype=int); -select intr_multirange(intr(1,10)); -drop type intr; -create type intmultirange as (x int, y int); -create type intrange as range(subtype=int); -- should fail -drop type intmultirange; -create type intr_multirange as (x int, y int); -create type intr as range(subtype=int); -- should fail -drop type intr_multirange; - --- --- Test multiple multirange types over the same subtype and manual naming of --- the multirange type. --- - --- should fail -create type textrange1 as range(subtype=text, multirange_type_name=int, collation="C"); --- should pass -create type textrange1 as range(subtype=text, multirange_type_name=multirange_of_text, collation="C"); --- should pass, because existing _textrange1 is automatically renamed -create type textrange2 as range(subtype=text, multirange_type_name=_textrange1, collation="C"); - -select multirange_of_text(textrange2('a','Z')); -- should fail -select multirange_of_text(textrange1('a','Z')) @> 'b'::text; -select unnest(multirange_of_text(textrange1('a','b'), textrange1('d','e'))); -select _textrange1(textrange2('a','z')) @> 'b'::text; - -drop type textrange1; -drop type textrange2; - --- --- Test polymorphic type system --- - -create function anyarray_anymultirange_func(a anyarray, r anymultirange) - returns anyelement as 'select $1[1] + lower($2);' language sql; - -select anyarray_anymultirange_func(ARRAY[1,2], int4multirange(int4range(10,20))); - --- should fail -select anyarray_anymultirange_func(ARRAY[1,2], nummultirange(numrange(10,20))); - -drop function anyarray_anymultirange_func(anyarray, anymultirange); - --- should fail -create function bogus_func(anyelement) - returns anymultirange as 'select int4multirange(int4range(1,10))' language sql; - --- should fail -create function bogus_func(int) - returns anymultirange as 'select int4multirange(int4range(1,10))' language sql; - -create function range_add_bounds(anymultirange) - returns anyelement as 'select lower($1) + upper($1)' language sql; - -select range_add_bounds(int4multirange(int4range(1, 17))); -select range_add_bounds(nummultirange(numrange(1.0001, 123.123))); - -create function multirangetypes_sql(q anymultirange, b anyarray, out c anyelement) - as $$ select upper($1) + $2[1] $$ - language sql; - -select multirangetypes_sql(int4multirange(int4range(1,10)), ARRAY[2,20]); -select multirangetypes_sql(nummultirange(numrange(1,10)), ARRAY[2,20]); -- match failure - -create function anycompatiblearray_anycompatiblemultirange_func(a anycompatiblearray, mr anycompatiblemultirange) - returns anycompatible as 'select $1[1] + lower($2);' language sql; - -select anycompatiblearray_anycompatiblemultirange_func(ARRAY[1,2], multirange(int4range(10,20))); - -select anycompatiblearray_anycompatiblemultirange_func(ARRAY[1,2], multirange(numrange(10,20))); - --- should fail -select anycompatiblearray_anycompatiblemultirange_func(ARRAY[1.1,2], multirange(int4range(10,20))); - -drop function anycompatiblearray_anycompatiblemultirange_func(anycompatiblearray, anycompatiblemultirange); - -create function anycompatiblerange_anycompatiblemultirange_func(r anycompatiblerange, mr anycompatiblemultirange) - returns anycompatible as 'select lower($1) + lower($2);' language sql; - -select anycompatiblerange_anycompatiblemultirange_func(int4range(1,2), multirange(int4range(10,20))); - --- should fail -select anycompatiblerange_anycompatiblemultirange_func(numrange(1,2), multirange(int4range(10,20))); - -drop function anycompatiblerange_anycompatiblemultirange_func(anycompatiblerange, anycompatiblemultirange); - --- should fail -create function bogus_func(anycompatible) - returns anycompatiblerange as 'select int4range(1,10)' language sql; - --- --- Arrays of multiranges --- - -select ARRAY[nummultirange(numrange(1.1, 1.2)), nummultirange(numrange(12.3, 155.5))]; - -create table i8mr_array (f1 int, f2 int8multirange[]); -insert into i8mr_array values (42, array[int8multirange(int8range(1,10)), int8multirange(int8range(2,20))]); -select * from i8mr_array; -drop table i8mr_array; - --- --- Multiranges of arrays --- - -select arraymultirange(arrayrange(ARRAY[1,2], ARRAY[2,1])); -select arraymultirange(arrayrange(ARRAY[2,1], ARRAY[1,2])); -- fail - -select array[1,1] <@ arraymultirange(arrayrange(array[1,2], array[2,1])); -select array[1,3] <@ arraymultirange(arrayrange(array[1,2], array[2,1])); - --- --- Ranges of composites --- - -create type two_ints as (a int, b int); -create type two_ints_range as range (subtype = two_ints); - --- with force_parallel_mode on, this exercises tqueue.c's range remapping -select *, row_to_json(upper(t)) as u from - (values (two_ints_multirange(two_ints_range(row(1,2), row(3,4)))), - (two_ints_multirange(two_ints_range(row(5,6), row(7,8))))) v(t); - -drop type two_ints cascade; - --- --- Check behavior when subtype lacks a hash function --- - -set enable_sort = off; -- try to make it pick a hash setop implementation - -select '{(2,5)}'::cashmultirange except select '{(5,6)}'::cashmultirange; - -reset enable_sort; - --- --- OUT/INOUT/TABLE functions --- - --- infer anymultirange from anymultirange -create function mr_outparam_succeed(i anymultirange, out r anymultirange, out t text) - as $$ select $1, 'foo'::text $$ language sql; - -select * from mr_outparam_succeed(int4multirange(int4range(1,2))); - --- infer anyarray from anymultirange -create function mr_outparam_succeed2(i anymultirange, out r anyarray, out t text) - as $$ select ARRAY[upper($1)], 'foo'::text $$ language sql; - -select * from mr_outparam_succeed2(int4multirange(int4range(1,2))); - --- infer anyrange from anymultirange -create function mr_outparam_succeed3(i anymultirange, out r anyrange, out t text) - as $$ select range_merge($1), 'foo'::text $$ language sql; -select * from mr_outparam_succeed3(int4multirange(int4range(1,2))); - --- infer anymultirange from anyrange -create function mr_outparam_succeed4(i anyrange, out r anymultirange, out t text) - as $$ select multirange($1), 'foo'::text $$ language sql; - -select * from mr_outparam_succeed4(int4range(1,2)); - --- infer anyelement from anymultirange -create function mr_inoutparam_succeed(out i anyelement, inout r anymultirange) - as $$ select upper($1), $1 $$ language sql; - -select * from mr_inoutparam_succeed(int4multirange(int4range(1,2))); - --- infer anyelement+anymultirange from anyelement+anymultirange -create function mr_table_succeed(i anyelement, r anymultirange) returns table(i anyelement, r anymultirange) - as $$ select $1, $2 $$ language sql; - -select * from mr_table_succeed(123, int4multirange(int4range(1,11))); - --- use anymultirange in plpgsql -create function mr_polymorphic(i anyrange) returns anymultirange - as $$ begin return multirange($1); end; $$ language plpgsql; -select mr_polymorphic(int4range(1, 4)); - --- should fail -create function mr_outparam_fail(i anyelement, out r anymultirange, out t text) - as $$ select '[1,10]', 'foo' $$ language sql; - ---should fail -create function mr_inoutparam_fail(inout i anyelement, out r anymultirange) - as $$ select $1, '[1,10]' $$ language sql; - ---should fail -create function mr_table_fail(i anyelement) returns table(i anyelement, r anymultirange) - as $$ select $1, '[1,10]' $$ language sql; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmvcc.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmvcc.sql deleted file mode 100644 index b22a86dc5e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fmvcc.sql +++ /dev/null @@ -1,44 +0,0 @@ --- --- Verify that index scans encountering dead rows produced by an --- aborted subtransaction of the current transaction can utilize the --- kill_prio_tuple optimization --- --- NB: The table size is currently *not* expected to stay the same, we --- don't have logic to trigger opportunistic pruning in cases like --- this. -BEGIN; - -SET LOCAL enable_seqscan = false; -SET LOCAL enable_indexonlyscan = false; -SET LOCAL enable_bitmapscan = false; - --- Can't easily use a unique index, since dead tuples can be found --- independent of the kill_prior_tuples optimization. -CREATE TABLE clean_aborted_self(key int, data text); -CREATE INDEX clean_aborted_self_key ON clean_aborted_self(key); -INSERT INTO clean_aborted_self (key, data) VALUES (-1, 'just to allocate metapage'); - --- save index size from before the changes, for comparison -SELECT pg_relation_size('clean_aborted_self_key') AS clean_aborted_self_key_before \gset - -DO $$ -BEGIN - -- iterate often enough to see index growth even on larger-than-default page sizes - FOR i IN 1..100 LOOP - BEGIN - -- perform index scan over all the inserted keys to get them to be seen as dead - IF EXISTS(SELECT * FROM clean_aborted_self WHERE key > 0 AND key < 100) THEN - RAISE data_corrupted USING MESSAGE = 'these rows should not exist'; - END IF; - INSERT INTO clean_aborted_self SELECT g.i, 'rolling back in a sec' FROM generate_series(1, 100) g(i); - -- just some error that's not normally thrown - RAISE reading_sql_data_not_permitted USING MESSAGE = 'round and round again'; - EXCEPTION WHEN reading_sql_data_not_permitted THEN END; - END LOOP; -END;$$; - --- show sizes only if they differ -SELECT :clean_aborted_self_key_before AS size_before, pg_relation_size('clean_aborted_self_key') size_after -WHERE :clean_aborted_self_key_before != pg_relation_size('clean_aborted_self_key'); - -ROLLBACK; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fname.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fname.sql deleted file mode 100644 index 29a5d97e5b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fname.sql +++ /dev/null @@ -1,87 +0,0 @@ --- --- NAME --- all inputs are silently truncated at NAMEDATALEN-1 (63) characters --- - --- fixed-length by reference -SELECT name 'name string' = name 'name string' AS "True"; - -SELECT name 'name string' = name 'name string ' AS "False"; - --- --- --- - -CREATE TABLE NAME_TBL(f1 name); - -INSERT INTO NAME_TBL(f1) VALUES ('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'); - -INSERT INTO NAME_TBL(f1) VALUES ('1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqr'); - -INSERT INTO NAME_TBL(f1) VALUES ('asdfghjkl;'); - -INSERT INTO NAME_TBL(f1) VALUES ('343f%2a'); - -INSERT INTO NAME_TBL(f1) VALUES ('d34aaasdf'); - -INSERT INTO NAME_TBL(f1) VALUES (''); - -INSERT INTO NAME_TBL(f1) VALUES ('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'); - - -SELECT * FROM NAME_TBL; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 <> '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 < '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 <= '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 > '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 >= '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGHIJKLMNOPQR'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 ~ '.*'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 !~ '.*'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 ~ '[0-9]'; - -SELECT c.f1 FROM NAME_TBL c WHERE c.f1 ~ '.*asdf.*'; - -DROP TABLE NAME_TBL; - -DO $$ -DECLARE r text[]; -BEGIN - r := parse_ident('Schemax.Tabley'); - RAISE NOTICE '%', format('%I.%I', r[1], r[2]); - r := parse_ident('"SchemaX"."TableY"'); - RAISE NOTICE '%', format('%I.%I', r[1], r[2]); -END; -$$; - -SELECT parse_ident('foo.boo'); -SELECT parse_ident('foo.boo[]'); -- should fail -SELECT parse_ident('foo.boo[]', strict => false); -- ok - --- should fail -SELECT parse_ident(' '); -SELECT parse_ident(' .aaa'); -SELECT parse_ident(' aaa . '); -SELECT parse_ident('aaa.a%b'); -SELECT parse_ident(E'X\rXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); - -SELECT length(a[1]), length(a[2]) from parse_ident('"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy') as a ; - -SELECT parse_ident(' first . " second " ." third ". " ' || repeat('x',66) || '"'); -SELECT parse_ident(' first . " second " ." third ". " ' || repeat('x',66) || '"')::name[]; - -SELECT parse_ident(E'"c".X XXXX\002XXXXXX'); -SELECT parse_ident('1020'); -SELECT parse_ident('10.20'); -SELECT parse_ident('.'); -SELECT parse_ident('.1020'); -SELECT parse_ident('xxx.1020'); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fnumeric.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fnumeric.sql deleted file mode 100644 index eeca63d86e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fnumeric.sql +++ /dev/null @@ -1,1435 +0,0 @@ --- --- NUMERIC --- - -CREATE TABLE num_data (id int4, val numeric(210,10)); -CREATE TABLE num_exp_add (id1 int4, id2 int4, expected numeric(210,10)); -CREATE TABLE num_exp_sub (id1 int4, id2 int4, expected numeric(210,10)); -CREATE TABLE num_exp_div (id1 int4, id2 int4, expected numeric(210,10)); -CREATE TABLE num_exp_mul (id1 int4, id2 int4, expected numeric(210,10)); -CREATE TABLE num_exp_sqrt (id int4, expected numeric(210,10)); -CREATE TABLE num_exp_ln (id int4, expected numeric(210,10)); -CREATE TABLE num_exp_log10 (id int4, expected numeric(210,10)); -CREATE TABLE num_exp_power_10_ln (id int4, expected numeric(210,10)); - -CREATE TABLE num_result (id1 int4, id2 int4, result numeric(210,10)); - - --- ****************************** --- * The following EXPECTED results are computed by bc(1) --- * with a scale of 200 --- ****************************** - -BEGIN TRANSACTION; -INSERT INTO num_exp_add VALUES (0,0,'0'); -INSERT INTO num_exp_sub VALUES (0,0,'0'); -INSERT INTO num_exp_mul VALUES (0,0,'0'); -INSERT INTO num_exp_div VALUES (0,0,'NaN'); -INSERT INTO num_exp_add VALUES (0,1,'0'); -INSERT INTO num_exp_sub VALUES (0,1,'0'); -INSERT INTO num_exp_mul VALUES (0,1,'0'); -INSERT INTO num_exp_div VALUES (0,1,'NaN'); -INSERT INTO num_exp_add VALUES (0,2,'-34338492.215397047'); -INSERT INTO num_exp_sub VALUES (0,2,'34338492.215397047'); -INSERT INTO num_exp_mul VALUES (0,2,'0'); -INSERT INTO num_exp_div VALUES (0,2,'0'); -INSERT INTO num_exp_add VALUES (0,3,'4.31'); -INSERT INTO num_exp_sub VALUES (0,3,'-4.31'); -INSERT INTO num_exp_mul VALUES (0,3,'0'); -INSERT INTO num_exp_div VALUES (0,3,'0'); -INSERT INTO num_exp_add VALUES (0,4,'7799461.4119'); -INSERT INTO num_exp_sub VALUES (0,4,'-7799461.4119'); -INSERT INTO num_exp_mul VALUES (0,4,'0'); -INSERT INTO num_exp_div VALUES (0,4,'0'); -INSERT INTO num_exp_add VALUES (0,5,'16397.038491'); -INSERT INTO num_exp_sub VALUES (0,5,'-16397.038491'); -INSERT INTO num_exp_mul VALUES (0,5,'0'); -INSERT INTO num_exp_div VALUES (0,5,'0'); -INSERT INTO num_exp_add VALUES (0,6,'93901.57763026'); -INSERT INTO num_exp_sub VALUES (0,6,'-93901.57763026'); -INSERT INTO num_exp_mul VALUES (0,6,'0'); -INSERT INTO num_exp_div VALUES (0,6,'0'); -INSERT INTO num_exp_add VALUES (0,7,'-83028485'); -INSERT INTO num_exp_sub VALUES (0,7,'83028485'); -INSERT INTO num_exp_mul VALUES (0,7,'0'); -INSERT INTO num_exp_div VALUES (0,7,'0'); -INSERT INTO num_exp_add VALUES (0,8,'74881'); -INSERT INTO num_exp_sub VALUES (0,8,'-74881'); -INSERT INTO num_exp_mul VALUES (0,8,'0'); -INSERT INTO num_exp_div VALUES (0,8,'0'); -INSERT INTO num_exp_add VALUES (0,9,'-24926804.045047420'); -INSERT INTO num_exp_sub VALUES (0,9,'24926804.045047420'); -INSERT INTO num_exp_mul VALUES (0,9,'0'); -INSERT INTO num_exp_div VALUES (0,9,'0'); -INSERT INTO num_exp_add VALUES (1,0,'0'); -INSERT INTO num_exp_sub VALUES (1,0,'0'); -INSERT INTO num_exp_mul VALUES (1,0,'0'); -INSERT INTO num_exp_div VALUES (1,0,'NaN'); -INSERT INTO num_exp_add VALUES (1,1,'0'); -INSERT INTO num_exp_sub VALUES (1,1,'0'); -INSERT INTO num_exp_mul VALUES (1,1,'0'); -INSERT INTO num_exp_div VALUES (1,1,'NaN'); -INSERT INTO num_exp_add VALUES (1,2,'-34338492.215397047'); -INSERT INTO num_exp_sub VALUES (1,2,'34338492.215397047'); -INSERT INTO num_exp_mul VALUES (1,2,'0'); -INSERT INTO num_exp_div VALUES (1,2,'0'); -INSERT INTO num_exp_add VALUES (1,3,'4.31'); -INSERT INTO num_exp_sub VALUES (1,3,'-4.31'); -INSERT INTO num_exp_mul VALUES (1,3,'0'); -INSERT INTO num_exp_div VALUES (1,3,'0'); -INSERT INTO num_exp_add VALUES (1,4,'7799461.4119'); -INSERT INTO num_exp_sub VALUES (1,4,'-7799461.4119'); -INSERT INTO num_exp_mul VALUES (1,4,'0'); -INSERT INTO num_exp_div VALUES (1,4,'0'); -INSERT INTO num_exp_add VALUES (1,5,'16397.038491'); -INSERT INTO num_exp_sub VALUES (1,5,'-16397.038491'); -INSERT INTO num_exp_mul VALUES (1,5,'0'); -INSERT INTO num_exp_div VALUES (1,5,'0'); -INSERT INTO num_exp_add VALUES (1,6,'93901.57763026'); -INSERT INTO num_exp_sub VALUES (1,6,'-93901.57763026'); -INSERT INTO num_exp_mul VALUES (1,6,'0'); -INSERT INTO num_exp_div VALUES (1,6,'0'); -INSERT INTO num_exp_add VALUES (1,7,'-83028485'); -INSERT INTO num_exp_sub VALUES (1,7,'83028485'); -INSERT INTO num_exp_mul VALUES (1,7,'0'); -INSERT INTO num_exp_div VALUES (1,7,'0'); -INSERT INTO num_exp_add VALUES (1,8,'74881'); -INSERT INTO num_exp_sub VALUES (1,8,'-74881'); -INSERT INTO num_exp_mul VALUES (1,8,'0'); -INSERT INTO num_exp_div VALUES (1,8,'0'); -INSERT INTO num_exp_add VALUES (1,9,'-24926804.045047420'); -INSERT INTO num_exp_sub VALUES (1,9,'24926804.045047420'); -INSERT INTO num_exp_mul VALUES (1,9,'0'); -INSERT INTO num_exp_div VALUES (1,9,'0'); -INSERT INTO num_exp_add VALUES (2,0,'-34338492.215397047'); -INSERT INTO num_exp_sub VALUES (2,0,'-34338492.215397047'); -INSERT INTO num_exp_mul VALUES (2,0,'0'); -INSERT INTO num_exp_div VALUES (2,0,'NaN'); -INSERT INTO num_exp_add VALUES (2,1,'-34338492.215397047'); -INSERT INTO num_exp_sub VALUES (2,1,'-34338492.215397047'); -INSERT INTO num_exp_mul VALUES (2,1,'0'); -INSERT INTO num_exp_div VALUES (2,1,'NaN'); -INSERT INTO num_exp_add VALUES (2,2,'-68676984.430794094'); -INSERT INTO num_exp_sub VALUES (2,2,'0'); -INSERT INTO num_exp_mul VALUES (2,2,'1179132047626883.596862135856320209'); -INSERT INTO num_exp_div VALUES (2,2,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (2,3,'-34338487.905397047'); -INSERT INTO num_exp_sub VALUES (2,3,'-34338496.525397047'); -INSERT INTO num_exp_mul VALUES (2,3,'-147998901.44836127257'); -INSERT INTO num_exp_div VALUES (2,3,'-7967167.56737750510440835266'); -INSERT INTO num_exp_add VALUES (2,4,'-26539030.803497047'); -INSERT INTO num_exp_sub VALUES (2,4,'-42137953.627297047'); -INSERT INTO num_exp_mul VALUES (2,4,'-267821744976817.8111137106593'); -INSERT INTO num_exp_div VALUES (2,4,'-4.40267480046830116685'); -INSERT INTO num_exp_add VALUES (2,5,'-34322095.176906047'); -INSERT INTO num_exp_sub VALUES (2,5,'-34354889.253888047'); -INSERT INTO num_exp_mul VALUES (2,5,'-563049578578.769242506736077'); -INSERT INTO num_exp_div VALUES (2,5,'-2094.18866914563535496429'); -INSERT INTO num_exp_add VALUES (2,6,'-34244590.637766787'); -INSERT INTO num_exp_sub VALUES (2,6,'-34432393.793027307'); -INSERT INTO num_exp_mul VALUES (2,6,'-3224438592470.18449811926184222'); -INSERT INTO num_exp_div VALUES (2,6,'-365.68599891479766440940'); -INSERT INTO num_exp_add VALUES (2,7,'-117366977.215397047'); -INSERT INTO num_exp_sub VALUES (2,7,'48689992.784602953'); -INSERT INTO num_exp_mul VALUES (2,7,'2851072985828710.485883795'); -INSERT INTO num_exp_div VALUES (2,7,'.41357483778485235518'); -INSERT INTO num_exp_add VALUES (2,8,'-34263611.215397047'); -INSERT INTO num_exp_sub VALUES (2,8,'-34413373.215397047'); -INSERT INTO num_exp_mul VALUES (2,8,'-2571300635581.146276407'); -INSERT INTO num_exp_div VALUES (2,8,'-458.57416721727870888476'); -INSERT INTO num_exp_add VALUES (2,9,'-59265296.260444467'); -INSERT INTO num_exp_sub VALUES (2,9,'-9411688.170349627'); -INSERT INTO num_exp_mul VALUES (2,9,'855948866655588.453741509242968740'); -INSERT INTO num_exp_div VALUES (2,9,'1.37757299946438931811'); -INSERT INTO num_exp_add VALUES (3,0,'4.31'); -INSERT INTO num_exp_sub VALUES (3,0,'4.31'); -INSERT INTO num_exp_mul VALUES (3,0,'0'); -INSERT INTO num_exp_div VALUES (3,0,'NaN'); -INSERT INTO num_exp_add VALUES (3,1,'4.31'); -INSERT INTO num_exp_sub VALUES (3,1,'4.31'); -INSERT INTO num_exp_mul VALUES (3,1,'0'); -INSERT INTO num_exp_div VALUES (3,1,'NaN'); -INSERT INTO num_exp_add VALUES (3,2,'-34338487.905397047'); -INSERT INTO num_exp_sub VALUES (3,2,'34338496.525397047'); -INSERT INTO num_exp_mul VALUES (3,2,'-147998901.44836127257'); -INSERT INTO num_exp_div VALUES (3,2,'-.00000012551512084352'); -INSERT INTO num_exp_add VALUES (3,3,'8.62'); -INSERT INTO num_exp_sub VALUES (3,3,'0'); -INSERT INTO num_exp_mul VALUES (3,3,'18.5761'); -INSERT INTO num_exp_div VALUES (3,3,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (3,4,'7799465.7219'); -INSERT INTO num_exp_sub VALUES (3,4,'-7799457.1019'); -INSERT INTO num_exp_mul VALUES (3,4,'33615678.685289'); -INSERT INTO num_exp_div VALUES (3,4,'.00000055260225961552'); -INSERT INTO num_exp_add VALUES (3,5,'16401.348491'); -INSERT INTO num_exp_sub VALUES (3,5,'-16392.728491'); -INSERT INTO num_exp_mul VALUES (3,5,'70671.23589621'); -INSERT INTO num_exp_div VALUES (3,5,'.00026285234387695504'); -INSERT INTO num_exp_add VALUES (3,6,'93905.88763026'); -INSERT INTO num_exp_sub VALUES (3,6,'-93897.26763026'); -INSERT INTO num_exp_mul VALUES (3,6,'404715.7995864206'); -INSERT INTO num_exp_div VALUES (3,6,'.00004589912234457595'); -INSERT INTO num_exp_add VALUES (3,7,'-83028480.69'); -INSERT INTO num_exp_sub VALUES (3,7,'83028489.31'); -INSERT INTO num_exp_mul VALUES (3,7,'-357852770.35'); -INSERT INTO num_exp_div VALUES (3,7,'-.00000005190989574240'); -INSERT INTO num_exp_add VALUES (3,8,'74885.31'); -INSERT INTO num_exp_sub VALUES (3,8,'-74876.69'); -INSERT INTO num_exp_mul VALUES (3,8,'322737.11'); -INSERT INTO num_exp_div VALUES (3,8,'.00005755799201399553'); -INSERT INTO num_exp_add VALUES (3,9,'-24926799.735047420'); -INSERT INTO num_exp_sub VALUES (3,9,'24926808.355047420'); -INSERT INTO num_exp_mul VALUES (3,9,'-107434525.43415438020'); -INSERT INTO num_exp_div VALUES (3,9,'-.00000017290624149854'); -INSERT INTO num_exp_add VALUES (4,0,'7799461.4119'); -INSERT INTO num_exp_sub VALUES (4,0,'7799461.4119'); -INSERT INTO num_exp_mul VALUES (4,0,'0'); -INSERT INTO num_exp_div VALUES (4,0,'NaN'); -INSERT INTO num_exp_add VALUES (4,1,'7799461.4119'); -INSERT INTO num_exp_sub VALUES (4,1,'7799461.4119'); -INSERT INTO num_exp_mul VALUES (4,1,'0'); -INSERT INTO num_exp_div VALUES (4,1,'NaN'); -INSERT INTO num_exp_add VALUES (4,2,'-26539030.803497047'); -INSERT INTO num_exp_sub VALUES (4,2,'42137953.627297047'); -INSERT INTO num_exp_mul VALUES (4,2,'-267821744976817.8111137106593'); -INSERT INTO num_exp_div VALUES (4,2,'-.22713465002993920385'); -INSERT INTO num_exp_add VALUES (4,3,'7799465.7219'); -INSERT INTO num_exp_sub VALUES (4,3,'7799457.1019'); -INSERT INTO num_exp_mul VALUES (4,3,'33615678.685289'); -INSERT INTO num_exp_div VALUES (4,3,'1809619.81714617169373549883'); -INSERT INTO num_exp_add VALUES (4,4,'15598922.8238'); -INSERT INTO num_exp_sub VALUES (4,4,'0'); -INSERT INTO num_exp_mul VALUES (4,4,'60831598315717.14146161'); -INSERT INTO num_exp_div VALUES (4,4,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (4,5,'7815858.450391'); -INSERT INTO num_exp_sub VALUES (4,5,'7783064.373409'); -INSERT INTO num_exp_mul VALUES (4,5,'127888068979.9935054429'); -INSERT INTO num_exp_div VALUES (4,5,'475.66281046305802686061'); -INSERT INTO num_exp_add VALUES (4,6,'7893362.98953026'); -INSERT INTO num_exp_sub VALUES (4,6,'7705559.83426974'); -INSERT INTO num_exp_mul VALUES (4,6,'732381731243.745115764094'); -INSERT INTO num_exp_div VALUES (4,6,'83.05996138436129499606'); -INSERT INTO num_exp_add VALUES (4,7,'-75229023.5881'); -INSERT INTO num_exp_sub VALUES (4,7,'90827946.4119'); -INSERT INTO num_exp_mul VALUES (4,7,'-647577464846017.9715'); -INSERT INTO num_exp_div VALUES (4,7,'-.09393717604145131637'); -INSERT INTO num_exp_add VALUES (4,8,'7874342.4119'); -INSERT INTO num_exp_sub VALUES (4,8,'7724580.4119'); -INSERT INTO num_exp_mul VALUES (4,8,'584031469984.4839'); -INSERT INTO num_exp_div VALUES (4,8,'104.15808298366741897143'); -INSERT INTO num_exp_add VALUES (4,9,'-17127342.633147420'); -INSERT INTO num_exp_sub VALUES (4,9,'32726265.456947420'); -INSERT INTO num_exp_mul VALUES (4,9,'-194415646271340.1815956522980'); -INSERT INTO num_exp_div VALUES (4,9,'-.31289456112403769409'); -INSERT INTO num_exp_add VALUES (5,0,'16397.038491'); -INSERT INTO num_exp_sub VALUES (5,0,'16397.038491'); -INSERT INTO num_exp_mul VALUES (5,0,'0'); -INSERT INTO num_exp_div VALUES (5,0,'NaN'); -INSERT INTO num_exp_add VALUES (5,1,'16397.038491'); -INSERT INTO num_exp_sub VALUES (5,1,'16397.038491'); -INSERT INTO num_exp_mul VALUES (5,1,'0'); -INSERT INTO num_exp_div VALUES (5,1,'NaN'); -INSERT INTO num_exp_add VALUES (5,2,'-34322095.176906047'); -INSERT INTO num_exp_sub VALUES (5,2,'34354889.253888047'); -INSERT INTO num_exp_mul VALUES (5,2,'-563049578578.769242506736077'); -INSERT INTO num_exp_div VALUES (5,2,'-.00047751189505192446'); -INSERT INTO num_exp_add VALUES (5,3,'16401.348491'); -INSERT INTO num_exp_sub VALUES (5,3,'16392.728491'); -INSERT INTO num_exp_mul VALUES (5,3,'70671.23589621'); -INSERT INTO num_exp_div VALUES (5,3,'3804.41728329466357308584'); -INSERT INTO num_exp_add VALUES (5,4,'7815858.450391'); -INSERT INTO num_exp_sub VALUES (5,4,'-7783064.373409'); -INSERT INTO num_exp_mul VALUES (5,4,'127888068979.9935054429'); -INSERT INTO num_exp_div VALUES (5,4,'.00210232958726897192'); -INSERT INTO num_exp_add VALUES (5,5,'32794.076982'); -INSERT INTO num_exp_sub VALUES (5,5,'0'); -INSERT INTO num_exp_mul VALUES (5,5,'268862871.275335557081'); -INSERT INTO num_exp_div VALUES (5,5,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (5,6,'110298.61612126'); -INSERT INTO num_exp_sub VALUES (5,6,'-77504.53913926'); -INSERT INTO num_exp_mul VALUES (5,6,'1539707782.76899778633766'); -INSERT INTO num_exp_div VALUES (5,6,'.17461941433576102689'); -INSERT INTO num_exp_add VALUES (5,7,'-83012087.961509'); -INSERT INTO num_exp_sub VALUES (5,7,'83044882.038491'); -INSERT INTO num_exp_mul VALUES (5,7,'-1361421264394.416135'); -INSERT INTO num_exp_div VALUES (5,7,'-.00019748690453643710'); -INSERT INTO num_exp_add VALUES (5,8,'91278.038491'); -INSERT INTO num_exp_sub VALUES (5,8,'-58483.961509'); -INSERT INTO num_exp_mul VALUES (5,8,'1227826639.244571'); -INSERT INTO num_exp_div VALUES (5,8,'.21897461960978085228'); -INSERT INTO num_exp_add VALUES (5,9,'-24910407.006556420'); -INSERT INTO num_exp_sub VALUES (5,9,'24943201.083538420'); -INSERT INTO num_exp_mul VALUES (5,9,'-408725765384.257043660243220'); -INSERT INTO num_exp_div VALUES (5,9,'-.00065780749354660427'); -INSERT INTO num_exp_add VALUES (6,0,'93901.57763026'); -INSERT INTO num_exp_sub VALUES (6,0,'93901.57763026'); -INSERT INTO num_exp_mul VALUES (6,0,'0'); -INSERT INTO num_exp_div VALUES (6,0,'NaN'); -INSERT INTO num_exp_add VALUES (6,1,'93901.57763026'); -INSERT INTO num_exp_sub VALUES (6,1,'93901.57763026'); -INSERT INTO num_exp_mul VALUES (6,1,'0'); -INSERT INTO num_exp_div VALUES (6,1,'NaN'); -INSERT INTO num_exp_add VALUES (6,2,'-34244590.637766787'); -INSERT INTO num_exp_sub VALUES (6,2,'34432393.793027307'); -INSERT INTO num_exp_mul VALUES (6,2,'-3224438592470.18449811926184222'); -INSERT INTO num_exp_div VALUES (6,2,'-.00273458651128995823'); -INSERT INTO num_exp_add VALUES (6,3,'93905.88763026'); -INSERT INTO num_exp_sub VALUES (6,3,'93897.26763026'); -INSERT INTO num_exp_mul VALUES (6,3,'404715.7995864206'); -INSERT INTO num_exp_div VALUES (6,3,'21786.90896293735498839907'); -INSERT INTO num_exp_add VALUES (6,4,'7893362.98953026'); -INSERT INTO num_exp_sub VALUES (6,4,'-7705559.83426974'); -INSERT INTO num_exp_mul VALUES (6,4,'732381731243.745115764094'); -INSERT INTO num_exp_div VALUES (6,4,'.01203949512295682469'); -INSERT INTO num_exp_add VALUES (6,5,'110298.61612126'); -INSERT INTO num_exp_sub VALUES (6,5,'77504.53913926'); -INSERT INTO num_exp_mul VALUES (6,5,'1539707782.76899778633766'); -INSERT INTO num_exp_div VALUES (6,5,'5.72674008674192359679'); -INSERT INTO num_exp_add VALUES (6,6,'187803.15526052'); -INSERT INTO num_exp_sub VALUES (6,6,'0'); -INSERT INTO num_exp_mul VALUES (6,6,'8817506281.4517452372676676'); -INSERT INTO num_exp_div VALUES (6,6,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (6,7,'-82934583.42236974'); -INSERT INTO num_exp_sub VALUES (6,7,'83122386.57763026'); -INSERT INTO num_exp_mul VALUES (6,7,'-7796505729750.37795610'); -INSERT INTO num_exp_div VALUES (6,7,'-.00113095617281538980'); -INSERT INTO num_exp_add VALUES (6,8,'168782.57763026'); -INSERT INTO num_exp_sub VALUES (6,8,'19020.57763026'); -INSERT INTO num_exp_mul VALUES (6,8,'7031444034.53149906'); -INSERT INTO num_exp_div VALUES (6,8,'1.25401073209839612184'); -INSERT INTO num_exp_add VALUES (6,9,'-24832902.467417160'); -INSERT INTO num_exp_sub VALUES (6,9,'25020705.622677680'); -INSERT INTO num_exp_mul VALUES (6,9,'-2340666225110.29929521292692920'); -INSERT INTO num_exp_div VALUES (6,9,'-.00376709254265256789'); -INSERT INTO num_exp_add VALUES (7,0,'-83028485'); -INSERT INTO num_exp_sub VALUES (7,0,'-83028485'); -INSERT INTO num_exp_mul VALUES (7,0,'0'); -INSERT INTO num_exp_div VALUES (7,0,'NaN'); -INSERT INTO num_exp_add VALUES (7,1,'-83028485'); -INSERT INTO num_exp_sub VALUES (7,1,'-83028485'); -INSERT INTO num_exp_mul VALUES (7,1,'0'); -INSERT INTO num_exp_div VALUES (7,1,'NaN'); -INSERT INTO num_exp_add VALUES (7,2,'-117366977.215397047'); -INSERT INTO num_exp_sub VALUES (7,2,'-48689992.784602953'); -INSERT INTO num_exp_mul VALUES (7,2,'2851072985828710.485883795'); -INSERT INTO num_exp_div VALUES (7,2,'2.41794207151503385700'); -INSERT INTO num_exp_add VALUES (7,3,'-83028480.69'); -INSERT INTO num_exp_sub VALUES (7,3,'-83028489.31'); -INSERT INTO num_exp_mul VALUES (7,3,'-357852770.35'); -INSERT INTO num_exp_div VALUES (7,3,'-19264149.65197215777262180974'); -INSERT INTO num_exp_add VALUES (7,4,'-75229023.5881'); -INSERT INTO num_exp_sub VALUES (7,4,'-90827946.4119'); -INSERT INTO num_exp_mul VALUES (7,4,'-647577464846017.9715'); -INSERT INTO num_exp_div VALUES (7,4,'-10.64541262725136247686'); -INSERT INTO num_exp_add VALUES (7,5,'-83012087.961509'); -INSERT INTO num_exp_sub VALUES (7,5,'-83044882.038491'); -INSERT INTO num_exp_mul VALUES (7,5,'-1361421264394.416135'); -INSERT INTO num_exp_div VALUES (7,5,'-5063.62688881730941836574'); -INSERT INTO num_exp_add VALUES (7,6,'-82934583.42236974'); -INSERT INTO num_exp_sub VALUES (7,6,'-83122386.57763026'); -INSERT INTO num_exp_mul VALUES (7,6,'-7796505729750.37795610'); -INSERT INTO num_exp_div VALUES (7,6,'-884.20756174009028770294'); -INSERT INTO num_exp_add VALUES (7,7,'-166056970'); -INSERT INTO num_exp_sub VALUES (7,7,'0'); -INSERT INTO num_exp_mul VALUES (7,7,'6893729321395225'); -INSERT INTO num_exp_div VALUES (7,7,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (7,8,'-82953604'); -INSERT INTO num_exp_sub VALUES (7,8,'-83103366'); -INSERT INTO num_exp_mul VALUES (7,8,'-6217255985285'); -INSERT INTO num_exp_div VALUES (7,8,'-1108.80577182462841041118'); -INSERT INTO num_exp_add VALUES (7,9,'-107955289.045047420'); -INSERT INTO num_exp_sub VALUES (7,9,'-58101680.954952580'); -INSERT INTO num_exp_mul VALUES (7,9,'2069634775752159.035758700'); -INSERT INTO num_exp_div VALUES (7,9,'3.33089171198810413382'); -INSERT INTO num_exp_add VALUES (8,0,'74881'); -INSERT INTO num_exp_sub VALUES (8,0,'74881'); -INSERT INTO num_exp_mul VALUES (8,0,'0'); -INSERT INTO num_exp_div VALUES (8,0,'NaN'); -INSERT INTO num_exp_add VALUES (8,1,'74881'); -INSERT INTO num_exp_sub VALUES (8,1,'74881'); -INSERT INTO num_exp_mul VALUES (8,1,'0'); -INSERT INTO num_exp_div VALUES (8,1,'NaN'); -INSERT INTO num_exp_add VALUES (8,2,'-34263611.215397047'); -INSERT INTO num_exp_sub VALUES (8,2,'34413373.215397047'); -INSERT INTO num_exp_mul VALUES (8,2,'-2571300635581.146276407'); -INSERT INTO num_exp_div VALUES (8,2,'-.00218067233500788615'); -INSERT INTO num_exp_add VALUES (8,3,'74885.31'); -INSERT INTO num_exp_sub VALUES (8,3,'74876.69'); -INSERT INTO num_exp_mul VALUES (8,3,'322737.11'); -INSERT INTO num_exp_div VALUES (8,3,'17373.78190255220417633410'); -INSERT INTO num_exp_add VALUES (8,4,'7874342.4119'); -INSERT INTO num_exp_sub VALUES (8,4,'-7724580.4119'); -INSERT INTO num_exp_mul VALUES (8,4,'584031469984.4839'); -INSERT INTO num_exp_div VALUES (8,4,'.00960079113741758956'); -INSERT INTO num_exp_add VALUES (8,5,'91278.038491'); -INSERT INTO num_exp_sub VALUES (8,5,'58483.961509'); -INSERT INTO num_exp_mul VALUES (8,5,'1227826639.244571'); -INSERT INTO num_exp_div VALUES (8,5,'4.56673929509287019456'); -INSERT INTO num_exp_add VALUES (8,6,'168782.57763026'); -INSERT INTO num_exp_sub VALUES (8,6,'-19020.57763026'); -INSERT INTO num_exp_mul VALUES (8,6,'7031444034.53149906'); -INSERT INTO num_exp_div VALUES (8,6,'.79744134113322314424'); -INSERT INTO num_exp_add VALUES (8,7,'-82953604'); -INSERT INTO num_exp_sub VALUES (8,7,'83103366'); -INSERT INTO num_exp_mul VALUES (8,7,'-6217255985285'); -INSERT INTO num_exp_div VALUES (8,7,'-.00090187120721280172'); -INSERT INTO num_exp_add VALUES (8,8,'149762'); -INSERT INTO num_exp_sub VALUES (8,8,'0'); -INSERT INTO num_exp_mul VALUES (8,8,'5607164161'); -INSERT INTO num_exp_div VALUES (8,8,'1.00000000000000000000'); -INSERT INTO num_exp_add VALUES (8,9,'-24851923.045047420'); -INSERT INTO num_exp_sub VALUES (8,9,'25001685.045047420'); -INSERT INTO num_exp_mul VALUES (8,9,'-1866544013697.195857020'); -INSERT INTO num_exp_div VALUES (8,9,'-.00300403532938582735'); -INSERT INTO num_exp_add VALUES (9,0,'-24926804.045047420'); -INSERT INTO num_exp_sub VALUES (9,0,'-24926804.045047420'); -INSERT INTO num_exp_mul VALUES (9,0,'0'); -INSERT INTO num_exp_div VALUES (9,0,'NaN'); -INSERT INTO num_exp_add VALUES (9,1,'-24926804.045047420'); -INSERT INTO num_exp_sub VALUES (9,1,'-24926804.045047420'); -INSERT INTO num_exp_mul VALUES (9,1,'0'); -INSERT INTO num_exp_div VALUES (9,1,'NaN'); -INSERT INTO num_exp_add VALUES (9,2,'-59265296.260444467'); -INSERT INTO num_exp_sub VALUES (9,2,'9411688.170349627'); -INSERT INTO num_exp_mul VALUES (9,2,'855948866655588.453741509242968740'); -INSERT INTO num_exp_div VALUES (9,2,'.72591434384152961526'); -INSERT INTO num_exp_add VALUES (9,3,'-24926799.735047420'); -INSERT INTO num_exp_sub VALUES (9,3,'-24926808.355047420'); -INSERT INTO num_exp_mul VALUES (9,3,'-107434525.43415438020'); -INSERT INTO num_exp_div VALUES (9,3,'-5783481.21694835730858468677'); -INSERT INTO num_exp_add VALUES (9,4,'-17127342.633147420'); -INSERT INTO num_exp_sub VALUES (9,4,'-32726265.456947420'); -INSERT INTO num_exp_mul VALUES (9,4,'-194415646271340.1815956522980'); -INSERT INTO num_exp_div VALUES (9,4,'-3.19596478892958416484'); -INSERT INTO num_exp_add VALUES (9,5,'-24910407.006556420'); -INSERT INTO num_exp_sub VALUES (9,5,'-24943201.083538420'); -INSERT INTO num_exp_mul VALUES (9,5,'-408725765384.257043660243220'); -INSERT INTO num_exp_div VALUES (9,5,'-1520.20159364322004505807'); -INSERT INTO num_exp_add VALUES (9,6,'-24832902.467417160'); -INSERT INTO num_exp_sub VALUES (9,6,'-25020705.622677680'); -INSERT INTO num_exp_mul VALUES (9,6,'-2340666225110.29929521292692920'); -INSERT INTO num_exp_div VALUES (9,6,'-265.45671195426965751280'); -INSERT INTO num_exp_add VALUES (9,7,'-107955289.045047420'); -INSERT INTO num_exp_sub VALUES (9,7,'58101680.954952580'); -INSERT INTO num_exp_mul VALUES (9,7,'2069634775752159.035758700'); -INSERT INTO num_exp_div VALUES (9,7,'.30021990699995814689'); -INSERT INTO num_exp_add VALUES (9,8,'-24851923.045047420'); -INSERT INTO num_exp_sub VALUES (9,8,'-25001685.045047420'); -INSERT INTO num_exp_mul VALUES (9,8,'-1866544013697.195857020'); -INSERT INTO num_exp_div VALUES (9,8,'-332.88556569820675471748'); -INSERT INTO num_exp_add VALUES (9,9,'-49853608.090094840'); -INSERT INTO num_exp_sub VALUES (9,9,'0'); -INSERT INTO num_exp_mul VALUES (9,9,'621345559900192.420120630048656400'); -INSERT INTO num_exp_div VALUES (9,9,'1.00000000000000000000'); -COMMIT TRANSACTION; -BEGIN TRANSACTION; -INSERT INTO num_exp_sqrt VALUES (0,'0'); -INSERT INTO num_exp_sqrt VALUES (1,'0'); -INSERT INTO num_exp_sqrt VALUES (2,'5859.90547836712524903505'); -INSERT INTO num_exp_sqrt VALUES (3,'2.07605394920266944396'); -INSERT INTO num_exp_sqrt VALUES (4,'2792.75158435189147418923'); -INSERT INTO num_exp_sqrt VALUES (5,'128.05092147657509145473'); -INSERT INTO num_exp_sqrt VALUES (6,'306.43364311096782703406'); -INSERT INTO num_exp_sqrt VALUES (7,'9111.99676251039939975230'); -INSERT INTO num_exp_sqrt VALUES (8,'273.64392922189960397542'); -INSERT INTO num_exp_sqrt VALUES (9,'4992.67503899937593364766'); -COMMIT TRANSACTION; -BEGIN TRANSACTION; -INSERT INTO num_exp_ln VALUES (0,'NaN'); -INSERT INTO num_exp_ln VALUES (1,'NaN'); -INSERT INTO num_exp_ln VALUES (2,'17.35177750493897715514'); -INSERT INTO num_exp_ln VALUES (3,'1.46093790411565641971'); -INSERT INTO num_exp_ln VALUES (4,'15.86956523951936572464'); -INSERT INTO num_exp_ln VALUES (5,'9.70485601768871834038'); -INSERT INTO num_exp_ln VALUES (6,'11.45000246622944403127'); -INSERT INTO num_exp_ln VALUES (7,'18.23469429965478772991'); -INSERT INTO num_exp_ln VALUES (8,'11.22365546576315513668'); -INSERT INTO num_exp_ln VALUES (9,'17.03145425013166006962'); -COMMIT TRANSACTION; -BEGIN TRANSACTION; -INSERT INTO num_exp_log10 VALUES (0,'NaN'); -INSERT INTO num_exp_log10 VALUES (1,'NaN'); -INSERT INTO num_exp_log10 VALUES (2,'7.53578122160797276459'); -INSERT INTO num_exp_log10 VALUES (3,'.63447727016073160075'); -INSERT INTO num_exp_log10 VALUES (4,'6.89206461372691743345'); -INSERT INTO num_exp_log10 VALUES (5,'4.21476541614777768626'); -INSERT INTO num_exp_log10 VALUES (6,'4.97267288886207207671'); -INSERT INTO num_exp_log10 VALUES (7,'7.91922711353275546914'); -INSERT INTO num_exp_log10 VALUES (8,'4.87437163556421004138'); -INSERT INTO num_exp_log10 VALUES (9,'7.39666659961986567059'); -COMMIT TRANSACTION; -BEGIN TRANSACTION; -INSERT INTO num_exp_power_10_ln VALUES (0,'NaN'); -INSERT INTO num_exp_power_10_ln VALUES (1,'NaN'); -INSERT INTO num_exp_power_10_ln VALUES (2,'224790267919917955.13261618583642653184'); -INSERT INTO num_exp_power_10_ln VALUES (3,'28.90266599445155957393'); -INSERT INTO num_exp_power_10_ln VALUES (4,'7405685069594999.07733999469386277636'); -INSERT INTO num_exp_power_10_ln VALUES (5,'5068226527.32127265408584640098'); -INSERT INTO num_exp_power_10_ln VALUES (6,'281839893606.99372343357047819067'); -INSERT INTO num_exp_power_10_ln VALUES (7,'1716699575118597095.42330819910640247627'); -INSERT INTO num_exp_power_10_ln VALUES (8,'167361463828.07491320069016125952'); -INSERT INTO num_exp_power_10_ln VALUES (9,'107511333880052007.04141124673540337457'); -COMMIT TRANSACTION; -BEGIN TRANSACTION; -INSERT INTO num_data VALUES (0, '0'); -INSERT INTO num_data VALUES (1, '0'); -INSERT INTO num_data VALUES (2, '-34338492.215397047'); -INSERT INTO num_data VALUES (3, '4.31'); -INSERT INTO num_data VALUES (4, '7799461.4119'); -INSERT INTO num_data VALUES (5, '16397.038491'); -INSERT INTO num_data VALUES (6, '93901.57763026'); -INSERT INTO num_data VALUES (7, '-83028485'); -INSERT INTO num_data VALUES (8, '74881'); -INSERT INTO num_data VALUES (9, '-24926804.045047420'); -COMMIT TRANSACTION; - --- ****************************** --- * Create indices for faster checks --- ****************************** - -CREATE UNIQUE INDEX num_exp_add_idx ON num_exp_add (id1, id2); -CREATE UNIQUE INDEX num_exp_sub_idx ON num_exp_sub (id1, id2); -CREATE UNIQUE INDEX num_exp_div_idx ON num_exp_div (id1, id2); -CREATE UNIQUE INDEX num_exp_mul_idx ON num_exp_mul (id1, id2); -CREATE UNIQUE INDEX num_exp_sqrt_idx ON num_exp_sqrt (id); -CREATE UNIQUE INDEX num_exp_ln_idx ON num_exp_ln (id); -CREATE UNIQUE INDEX num_exp_log10_idx ON num_exp_log10 (id); -CREATE UNIQUE INDEX num_exp_power_10_ln_idx ON num_exp_power_10_ln (id); - -VACUUM ANALYZE num_exp_add; -VACUUM ANALYZE num_exp_sub; -VACUUM ANALYZE num_exp_div; -VACUUM ANALYZE num_exp_mul; -VACUUM ANALYZE num_exp_sqrt; -VACUUM ANALYZE num_exp_ln; -VACUUM ANALYZE num_exp_log10; -VACUUM ANALYZE num_exp_power_10_ln; - --- ****************************** --- * Now check the behaviour of the NUMERIC type --- ****************************** - --- ****************************** --- * Addition check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, t1.val + t2.val - FROM num_data t1, num_data t2; -SELECT t1.id1, t1.id2, t1.result, t2.expected - FROM num_result t1, num_exp_add t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != t2.expected; - -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, round(t1.val + t2.val, 10) - FROM num_data t1, num_data t2; -SELECT t1.id1, t1.id2, t1.result, round(t2.expected, 10) as expected - FROM num_result t1, num_exp_add t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != round(t2.expected, 10); - --- ****************************** --- * Subtraction check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, t1.val - t2.val - FROM num_data t1, num_data t2; -SELECT t1.id1, t1.id2, t1.result, t2.expected - FROM num_result t1, num_exp_sub t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != t2.expected; - -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, round(t1.val - t2.val, 40) - FROM num_data t1, num_data t2; -SELECT t1.id1, t1.id2, t1.result, round(t2.expected, 40) - FROM num_result t1, num_exp_sub t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != round(t2.expected, 40); - --- ****************************** --- * Multiply check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, t1.val * t2.val - FROM num_data t1, num_data t2; -SELECT t1.id1, t1.id2, t1.result, t2.expected - FROM num_result t1, num_exp_mul t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != t2.expected; - -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, round(t1.val * t2.val, 30) - FROM num_data t1, num_data t2; -SELECT t1.id1, t1.id2, t1.result, round(t2.expected, 30) as expected - FROM num_result t1, num_exp_mul t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != round(t2.expected, 30); - --- ****************************** --- * Division check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, t1.val / t2.val - FROM num_data t1, num_data t2 - WHERE t2.val != '0.0'; -SELECT t1.id1, t1.id2, t1.result, t2.expected - FROM num_result t1, num_exp_div t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != t2.expected; - -DELETE FROM num_result; -INSERT INTO num_result SELECT t1.id, t2.id, round(t1.val / t2.val, 80) - FROM num_data t1, num_data t2 - WHERE t2.val != '0.0'; -SELECT t1.id1, t1.id2, t1.result, round(t2.expected, 80) as expected - FROM num_result t1, num_exp_div t2 - WHERE t1.id1 = t2.id1 AND t1.id2 = t2.id2 - AND t1.result != round(t2.expected, 80); - --- ****************************** --- * Square root check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT id, 0, SQRT(ABS(val)) - FROM num_data; -SELECT t1.id1, t1.result, t2.expected - FROM num_result t1, num_exp_sqrt t2 - WHERE t1.id1 = t2.id - AND t1.result != t2.expected; - --- ****************************** --- * Natural logarithm check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT id, 0, LN(ABS(val)) - FROM num_data - WHERE val != '0.0'; -SELECT t1.id1, t1.result, t2.expected - FROM num_result t1, num_exp_ln t2 - WHERE t1.id1 = t2.id - AND t1.result != t2.expected; - --- ****************************** --- * Logarithm base 10 check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT id, 0, LOG(numeric '10', ABS(val)) - FROM num_data - WHERE val != '0.0'; -SELECT t1.id1, t1.result, t2.expected - FROM num_result t1, num_exp_log10 t2 - WHERE t1.id1 = t2.id - AND t1.result != t2.expected; - --- ****************************** --- * POWER(10, LN(value)) check --- ****************************** -DELETE FROM num_result; -INSERT INTO num_result SELECT id, 0, POWER(numeric '10', LN(ABS(round(val,200)))) - FROM num_data - WHERE val != '0.0'; -SELECT t1.id1, t1.result, t2.expected - FROM num_result t1, num_exp_power_10_ln t2 - WHERE t1.id1 = t2.id - AND t1.result != t2.expected; - --- ****************************** --- * Check behavior with Inf and NaN inputs. It's easiest to handle these --- * separately from the num_data framework used above, because some input --- * combinations will throw errors. --- ****************************** - -WITH v(x) AS - (VALUES('0'::numeric),('1'),('-1'),('4.2'),('inf'),('-inf'),('nan')) -SELECT x1, x2, - x1 + x2 AS sum, - x1 - x2 AS diff, - x1 * x2 AS prod -FROM v AS v1(x1), v AS v2(x2); - -WITH v(x) AS - (VALUES('0'::numeric),('1'),('-1'),('4.2'),('inf'),('-inf'),('nan')) -SELECT x1, x2, - x1 / x2 AS quot, - x1 % x2 AS mod, - div(x1, x2) AS div -FROM v AS v1(x1), v AS v2(x2) WHERE x2 != 0; - -SELECT 'inf'::numeric / '0'; -SELECT '-inf'::numeric / '0'; -SELECT 'nan'::numeric / '0'; -SELECT '0'::numeric / '0'; -SELECT 'inf'::numeric % '0'; -SELECT '-inf'::numeric % '0'; -SELECT 'nan'::numeric % '0'; -SELECT '0'::numeric % '0'; -SELECT div('inf'::numeric, '0'); -SELECT div('-inf'::numeric, '0'); -SELECT div('nan'::numeric, '0'); -SELECT div('0'::numeric, '0'); - -WITH v(x) AS - (VALUES('0'::numeric),('1'),('-1'),('4.2'),('-7.777'),('inf'),('-inf'),('nan')) -SELECT x, -x as minusx, abs(x), floor(x), ceil(x), sign(x), numeric_inc(x) as inc -FROM v; - -WITH v(x) AS - (VALUES('0'::numeric),('1'),('-1'),('4.2'),('-7.777'),('inf'),('-inf'),('nan')) -SELECT x, round(x), round(x,1) as round1, trunc(x), trunc(x,1) as trunc1 -FROM v; - --- the large values fall into the numeric abbreviation code's maximal classes -WITH v(x) AS - (VALUES('0'::numeric),('1'),('-1'),('4.2'),('-7.777'),('1e340'),('-1e340'), - ('inf'),('-inf'),('nan'), - ('inf'),('-inf'),('nan')) -SELECT substring(x::text, 1, 32) -FROM v ORDER BY x; - -WITH v(x) AS - (VALUES('0'::numeric),('1'),('4.2'),('inf'),('nan')) -SELECT x, sqrt(x) -FROM v; - -SELECT sqrt('-1'::numeric); -SELECT sqrt('-inf'::numeric); - -WITH v(x) AS - (VALUES('1'::numeric),('4.2'),('inf'),('nan')) -SELECT x, - log(x), - log10(x), - ln(x) -FROM v; - -SELECT ln('0'::numeric); -SELECT ln('-1'::numeric); -SELECT ln('-inf'::numeric); - -WITH v(x) AS - (VALUES('2'::numeric),('4.2'),('inf'),('nan')) -SELECT x1, x2, - log(x1, x2) -FROM v AS v1(x1), v AS v2(x2); - -SELECT log('0'::numeric, '10'); -SELECT log('10'::numeric, '0'); -SELECT log('-inf'::numeric, '10'); -SELECT log('10'::numeric, '-inf'); -SELECT log('inf'::numeric, '0'); -SELECT log('inf'::numeric, '-inf'); -SELECT log('-inf'::numeric, 'inf'); - -WITH v(x) AS - (VALUES('0'::numeric),('1'),('2'),('4.2'),('inf'),('nan')) -SELECT x1, x2, - power(x1, x2) -FROM v AS v1(x1), v AS v2(x2) WHERE x1 != 0 OR x2 >= 0; - -SELECT power('0'::numeric, '-1'); -SELECT power('0'::numeric, '-inf'); -SELECT power('-1'::numeric, 'inf'); -SELECT power('-2'::numeric, '3'); -SELECT power('-2'::numeric, '3.3'); -SELECT power('-2'::numeric, '-1'); -SELECT power('-2'::numeric, '-1.5'); -SELECT power('-2'::numeric, 'inf'); -SELECT power('-2'::numeric, '-inf'); -SELECT power('inf'::numeric, '-2'); -SELECT power('inf'::numeric, '-inf'); -SELECT power('-inf'::numeric, '2'); -SELECT power('-inf'::numeric, '3'); -SELECT power('-inf'::numeric, '4.5'); -SELECT power('-inf'::numeric, '-2'); -SELECT power('-inf'::numeric, '-3'); -SELECT power('-inf'::numeric, '0'); -SELECT power('-inf'::numeric, 'inf'); -SELECT power('-inf'::numeric, '-inf'); - --- ****************************** --- * miscellaneous checks for things that have been broken in the past... --- ****************************** --- numeric AVG used to fail on some platforms -SELECT AVG(val) FROM num_data; -SELECT MAX(val) FROM num_data; -SELECT MIN(val) FROM num_data; -SELECT STDDEV(val) FROM num_data; -SELECT VARIANCE(val) FROM num_data; - --- Check for appropriate rounding and overflow -CREATE TABLE fract_only (id int, val numeric(4,4)); -INSERT INTO fract_only VALUES (1, '0.0'); -INSERT INTO fract_only VALUES (2, '0.1'); -INSERT INTO fract_only VALUES (3, '1.0'); -- should fail -INSERT INTO fract_only VALUES (4, '-0.9999'); -INSERT INTO fract_only VALUES (5, '0.99994'); -INSERT INTO fract_only VALUES (6, '0.99995'); -- should fail -INSERT INTO fract_only VALUES (7, '0.00001'); -INSERT INTO fract_only VALUES (8, '0.00017'); -INSERT INTO fract_only VALUES (9, 'NaN'); -INSERT INTO fract_only VALUES (10, 'Inf'); -- should fail -INSERT INTO fract_only VALUES (11, '-Inf'); -- should fail -SELECT * FROM fract_only; -DROP TABLE fract_only; - --- Check conversion to integers -SELECT (-9223372036854775808.5)::int8; -- should fail -SELECT (-9223372036854775808.4)::int8; -- ok -SELECT 9223372036854775807.4::int8; -- ok -SELECT 9223372036854775807.5::int8; -- should fail -SELECT (-2147483648.5)::int4; -- should fail -SELECT (-2147483648.4)::int4; -- ok -SELECT 2147483647.4::int4; -- ok -SELECT 2147483647.5::int4; -- should fail -SELECT (-32768.5)::int2; -- should fail -SELECT (-32768.4)::int2; -- ok -SELECT 32767.4::int2; -- ok -SELECT 32767.5::int2; -- should fail - --- Check inf/nan conversion behavior -SELECT 'NaN'::float8::numeric; -SELECT 'Infinity'::float8::numeric; -SELECT '-Infinity'::float8::numeric; -SELECT 'NaN'::numeric::float8; -SELECT 'Infinity'::numeric::float8; -SELECT '-Infinity'::numeric::float8; -SELECT 'NaN'::float4::numeric; -SELECT 'Infinity'::float4::numeric; -SELECT '-Infinity'::float4::numeric; -SELECT 'NaN'::numeric::float4; -SELECT 'Infinity'::numeric::float4; -SELECT '-Infinity'::numeric::float4; -SELECT '42'::int2::numeric; -SELECT 'NaN'::numeric::int2; -SELECT 'Infinity'::numeric::int2; -SELECT '-Infinity'::numeric::int2; -SELECT 'NaN'::numeric::int4; -SELECT 'Infinity'::numeric::int4; -SELECT '-Infinity'::numeric::int4; -SELECT 'NaN'::numeric::int8; -SELECT 'Infinity'::numeric::int8; -SELECT '-Infinity'::numeric::int8; - --- Simple check that ceil(), floor(), and round() work correctly -CREATE TABLE ceil_floor_round (a numeric); -INSERT INTO ceil_floor_round VALUES ('-5.5'); -INSERT INTO ceil_floor_round VALUES ('-5.499999'); -INSERT INTO ceil_floor_round VALUES ('9.5'); -INSERT INTO ceil_floor_round VALUES ('9.4999999'); -INSERT INTO ceil_floor_round VALUES ('0.0'); -INSERT INTO ceil_floor_round VALUES ('0.0000001'); -INSERT INTO ceil_floor_round VALUES ('-0.000001'); -SELECT a, ceil(a), ceiling(a), floor(a), round(a) FROM ceil_floor_round; -DROP TABLE ceil_floor_round; - --- Check rounding, it should round ties away from zero. -SELECT i as pow, - round((-2.5 * 10 ^ i)::numeric, -i), - round((-1.5 * 10 ^ i)::numeric, -i), - round((-0.5 * 10 ^ i)::numeric, -i), - round((0.5 * 10 ^ i)::numeric, -i), - round((1.5 * 10 ^ i)::numeric, -i), - round((2.5 * 10 ^ i)::numeric, -i) -FROM generate_series(-5,5) AS t(i); - --- Testing for width_bucket(). For convenience, we test both the --- numeric and float8 versions of the function in this file. - --- errors -SELECT width_bucket(5.0, 3.0, 4.0, 0); -SELECT width_bucket(5.0, 3.0, 4.0, -5); -SELECT width_bucket(3.5, 3.0, 3.0, 888); -SELECT width_bucket(5.0::float8, 3.0::float8, 4.0::float8, 0); -SELECT width_bucket(5.0::float8, 3.0::float8, 4.0::float8, -5); -SELECT width_bucket(3.5::float8, 3.0::float8, 3.0::float8, 888); -SELECT width_bucket('NaN', 3.0, 4.0, 888); -SELECT width_bucket(0::float8, 'NaN', 4.0::float8, 888); -SELECT width_bucket(2.0, 3.0, '-inf', 888); -SELECT width_bucket(0::float8, '-inf', 4.0::float8, 888); - --- normal operation -CREATE TABLE width_bucket_test (operand_num numeric, operand_f8 float8); - -COPY width_bucket_test (operand_num) FROM stdin; --5.2 --0.0000000001 -0.000000000001 -1 -1.99999999999999 -2 -2.00000000000001 -3 -4 -4.5 -5 -5.5 -6 -7 -8 -9 -9.99999999999999 -10 -10.0000000000001 -\. - -UPDATE width_bucket_test SET operand_f8 = operand_num::float8; - -SELECT - operand_num, - width_bucket(operand_num, 0, 10, 5) AS wb_1, - width_bucket(operand_f8, 0, 10, 5) AS wb_1f, - width_bucket(operand_num, 10, 0, 5) AS wb_2, - width_bucket(operand_f8, 10, 0, 5) AS wb_2f, - width_bucket(operand_num, 2, 8, 4) AS wb_3, - width_bucket(operand_f8, 2, 8, 4) AS wb_3f, - width_bucket(operand_num, 5.0, 5.5, 20) AS wb_4, - width_bucket(operand_f8, 5.0, 5.5, 20) AS wb_4f, - width_bucket(operand_num, -25, 25, 10) AS wb_5, - width_bucket(operand_f8, -25, 25, 10) AS wb_5f - FROM width_bucket_test; - --- Check positive and negative infinity: we require --- finite bucket bounds, but allow an infinite operand -SELECT width_bucket(0.0::numeric, 'Infinity'::numeric, 5, 10); -- error -SELECT width_bucket(0.0::numeric, 5, '-Infinity'::numeric, 20); -- error -SELECT width_bucket('Infinity'::numeric, 1, 10, 10), - width_bucket('-Infinity'::numeric, 1, 10, 10); -SELECT width_bucket(0.0::float8, 'Infinity'::float8, 5, 10); -- error -SELECT width_bucket(0.0::float8, 5, '-Infinity'::float8, 20); -- error -SELECT width_bucket('Infinity'::float8, 1, 10, 10), - width_bucket('-Infinity'::float8, 1, 10, 10); - -DROP TABLE width_bucket_test; - --- Simple test for roundoff error when results should be exact -SELECT x, width_bucket(x::float8, 10, 100, 9) as flt, - width_bucket(x::numeric, 10, 100, 9) as num -FROM generate_series(0, 110, 10) x; -SELECT x, width_bucket(x::float8, 100, 10, 9) as flt, - width_bucket(x::numeric, 100, 10, 9) as num -FROM generate_series(0, 110, 10) x; - --- --- TO_CHAR() --- -SELECT to_char(val, '9G999G999G999G999G999') - FROM num_data; - -SELECT to_char(val, '9G999G999G999G999G999D999G999G999G999G999') - FROM num_data; - -SELECT to_char(val, '9999999999999999.999999999999999PR') - FROM num_data; - -SELECT to_char(val, '9999999999999999.999999999999999S') - FROM num_data; - -SELECT to_char(val, 'MI9999999999999999.999999999999999') FROM num_data; -SELECT to_char(val, 'FMS9999999999999999.999999999999999') FROM num_data; -SELECT to_char(val, 'FM9999999999999999.999999999999999THPR') FROM num_data; -SELECT to_char(val, 'SG9999999999999999.999999999999999th') FROM num_data; -SELECT to_char(val, '0999999999999999.999999999999999') FROM num_data; -SELECT to_char(val, 'S0999999999999999.999999999999999') FROM num_data; -SELECT to_char(val, 'FM0999999999999999.999999999999999') FROM num_data; -SELECT to_char(val, 'FM9999999999999999.099999999999999') FROM num_data; -SELECT to_char(val, 'FM9999999999990999.990999999999999') FROM num_data; -SELECT to_char(val, 'FM0999999999999999.999909999999999') FROM num_data; -SELECT to_char(val, 'FM9999999990999999.099999999999999') FROM num_data; -SELECT to_char(val, 'L9999999999999999.099999999999999') FROM num_data; -SELECT to_char(val, 'FM9999999999999999.99999999999999') FROM num_data; -SELECT to_char(val, 'S 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 . 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9') FROM num_data; -SELECT to_char(val, 'FMS 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 . 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9') FROM num_data; -SELECT to_char(val, E'99999 "text" 9999 "9999" 999 "\\"text between quote marks\\"" 9999') FROM num_data; -SELECT to_char(val, '999999SG9999999999') FROM num_data; -SELECT to_char(val, 'FM9999999999999999.999999999999999') FROM num_data; -SELECT to_char(val, '9.999EEEE') FROM num_data; - -WITH v(val) AS - (VALUES('0'::numeric),('-4.2'),('4.2e9'),('1.2e-5'),('inf'),('-inf'),('nan')) -SELECT val, - to_char(val, '9.999EEEE') as numeric, - to_char(val::float8, '9.999EEEE') as float8, - to_char(val::float4, '9.999EEEE') as float4 -FROM v; - -WITH v(exp) AS - (VALUES(-16379),(-16378),(-1234),(-789),(-45),(-5),(-4),(-3),(-2),(-1),(0), - (1),(2),(3),(4),(5),(38),(275),(2345),(45678),(131070),(131071)) -SELECT exp, - to_char(('1.2345e'||exp)::numeric, '9.999EEEE') as numeric -FROM v; - -WITH v(val) AS - (VALUES('0'::numeric),('-4.2'),('4.2e9'),('1.2e-5'),('inf'),('-inf'),('nan')) -SELECT val, - to_char(val, 'MI9999999999.99') as numeric, - to_char(val::float8, 'MI9999999999.99') as float8, - to_char(val::float4, 'MI9999999999.99') as float4 -FROM v; - -WITH v(val) AS - (VALUES('0'::numeric),('-4.2'),('4.2e9'),('1.2e-5'),('inf'),('-inf'),('nan')) -SELECT val, - to_char(val, 'MI99.99') as numeric, - to_char(val::float8, 'MI99.99') as float8, - to_char(val::float4, 'MI99.99') as float4 -FROM v; - -SELECT to_char('100'::numeric, 'FM999.9'); -SELECT to_char('100'::numeric, 'FM999.'); -SELECT to_char('100'::numeric, 'FM999'); - --- Check parsing of literal text in a format string -SELECT to_char('100'::numeric, 'foo999'); -SELECT to_char('100'::numeric, 'f\oo999'); -SELECT to_char('100'::numeric, 'f\\oo999'); -SELECT to_char('100'::numeric, 'f\"oo999'); -SELECT to_char('100'::numeric, 'f\\"oo999'); -SELECT to_char('100'::numeric, 'f"ool"999'); -SELECT to_char('100'::numeric, 'f"\ool"999'); -SELECT to_char('100'::numeric, 'f"\\ool"999'); -SELECT to_char('100'::numeric, 'f"ool\"999'); -SELECT to_char('100'::numeric, 'f"ool\\"999'); - --- TO_NUMBER() --- -SET lc_numeric = 'C'; -SELECT to_number('-34,338,492', '99G999G999'); -SELECT to_number('-34,338,492.654,878', '99G999G999D999G999'); -SELECT to_number('<564646.654564>', '999999.999999PR'); -SELECT to_number('0.00001-', '9.999999S'); -SELECT to_number('5.01-', 'FM9.999999S'); -SELECT to_number('5.01-', 'FM9.999999MI'); -SELECT to_number('5 4 4 4 4 8 . 7 8', '9 9 9 9 9 9 . 9 9'); -SELECT to_number('.01', 'FM9.99'); -SELECT to_number('.0', '99999999.99999999'); -SELECT to_number('0', '99.99'); -SELECT to_number('.-01', 'S99.99'); -SELECT to_number('.01-', '99.99S'); -SELECT to_number(' . 0 1-', ' 9 9 . 9 9 S'); -SELECT to_number('34,50','999,99'); -SELECT to_number('123,000','999G'); -SELECT to_number('123456','999G999'); -SELECT to_number('$1234.56','L9,999.99'); -SELECT to_number('$1234.56','L99,999.99'); -SELECT to_number('$1,234.56','L99,999.99'); -SELECT to_number('1234.56','L99,999.99'); -SELECT to_number('1,234.56','L99,999.99'); -SELECT to_number('42nd', '99th'); -RESET lc_numeric; - --- --- Input syntax --- - -CREATE TABLE num_input_test (n1 numeric); - --- good inputs -INSERT INTO num_input_test(n1) VALUES (' 123'); -INSERT INTO num_input_test(n1) VALUES (' 3245874 '); -INSERT INTO num_input_test(n1) VALUES (' -93853'); -INSERT INTO num_input_test(n1) VALUES ('555.50'); -INSERT INTO num_input_test(n1) VALUES ('-555.50'); -INSERT INTO num_input_test(n1) VALUES ('NaN '); -INSERT INTO num_input_test(n1) VALUES (' nan'); -INSERT INTO num_input_test(n1) VALUES (' inf '); -INSERT INTO num_input_test(n1) VALUES (' +inf '); -INSERT INTO num_input_test(n1) VALUES (' -inf '); -INSERT INTO num_input_test(n1) VALUES (' Infinity '); -INSERT INTO num_input_test(n1) VALUES (' +inFinity '); -INSERT INTO num_input_test(n1) VALUES (' -INFINITY '); - --- bad inputs -INSERT INTO num_input_test(n1) VALUES (' '); -INSERT INTO num_input_test(n1) VALUES (' 1234 %'); -INSERT INTO num_input_test(n1) VALUES ('xyz'); -INSERT INTO num_input_test(n1) VALUES ('- 1234'); -INSERT INTO num_input_test(n1) VALUES ('5 . 0'); -INSERT INTO num_input_test(n1) VALUES ('5. 0 '); -INSERT INTO num_input_test(n1) VALUES (''); -INSERT INTO num_input_test(n1) VALUES (' N aN '); -INSERT INTO num_input_test(n1) VALUES ('+ infinity'); - -SELECT * FROM num_input_test; - --- --- Test precision and scale typemods --- - -CREATE TABLE num_typemod_test ( - millions numeric(3, -6), - thousands numeric(3, -3), - units numeric(3, 0), - thousandths numeric(3, 3), - millionths numeric(3, 6) -); -\d num_typemod_test - --- rounding of valid inputs -INSERT INTO num_typemod_test VALUES (123456, 123, 0.123, 0.000123, 0.000000123); -INSERT INTO num_typemod_test VALUES (654321, 654, 0.654, 0.000654, 0.000000654); -INSERT INTO num_typemod_test VALUES (2345678, 2345, 2.345, 0.002345, 0.000002345); -INSERT INTO num_typemod_test VALUES (7654321, 7654, 7.654, 0.007654, 0.000007654); -INSERT INTO num_typemod_test VALUES (12345678, 12345, 12.345, 0.012345, 0.000012345); -INSERT INTO num_typemod_test VALUES (87654321, 87654, 87.654, 0.087654, 0.000087654); -INSERT INTO num_typemod_test VALUES (123456789, 123456, 123.456, 0.123456, 0.000123456); -INSERT INTO num_typemod_test VALUES (987654321, 987654, 987.654, 0.987654, 0.000987654); -INSERT INTO num_typemod_test VALUES ('NaN', 'NaN', 'NaN', 'NaN', 'NaN'); - -SELECT scale(millions), * FROM num_typemod_test ORDER BY millions; - --- invalid inputs -INSERT INTO num_typemod_test (millions) VALUES ('inf'); -INSERT INTO num_typemod_test (millions) VALUES (999500000); -INSERT INTO num_typemod_test (thousands) VALUES (999500); -INSERT INTO num_typemod_test (units) VALUES (999.5); -INSERT INTO num_typemod_test (thousandths) VALUES (0.9995); -INSERT INTO num_typemod_test (millionths) VALUES (0.0009995); - --- --- Test some corner cases for multiplication --- - -select 4790999999999999999999999999999999999999999999999999999999999999999999999999999999999999 * 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; - -select 4789999999999999999999999999999999999999999999999999999999999999999999999999999999999999 * 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; - -select 4770999999999999999999999999999999999999999999999999999999999999999999999999999999999999 * 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; - -select 4769999999999999999999999999999999999999999999999999999999999999999999999999999999999999 * 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; - -select trim_scale((0.1 - 2e-16383) * (0.1 - 3e-16383)); - --- --- Test some corner cases for division --- - -select 999999999999999999999::numeric/1000000000000000000000; -select div(999999999999999999999::numeric,1000000000000000000000); -select mod(999999999999999999999::numeric,1000000000000000000000); -select div(-9999999999999999999999::numeric,1000000000000000000000); -select mod(-9999999999999999999999::numeric,1000000000000000000000); -select div(-9999999999999999999999::numeric,1000000000000000000000)*1000000000000000000000 + mod(-9999999999999999999999::numeric,1000000000000000000000); -select mod (70.0,70) ; -select div (70.0,70) ; -select 70.0 / 70 ; -select 12345678901234567890 % 123; -select 12345678901234567890 / 123; -select div(12345678901234567890, 123); -select div(12345678901234567890, 123) * 123 + 12345678901234567890 % 123; - --- --- Test some corner cases for square root --- - -select sqrt(1.000000000000003::numeric); -select sqrt(1.000000000000004::numeric); -select sqrt(96627521408608.56340355805::numeric); -select sqrt(96627521408608.56340355806::numeric); -select sqrt(515549506212297735.073688290367::numeric); -select sqrt(515549506212297735.073688290368::numeric); -select sqrt(8015491789940783531003294973900306::numeric); -select sqrt(8015491789940783531003294973900307::numeric); - --- --- Test code path for raising to integer powers --- - -select 10.0 ^ -2147483648 as rounds_to_zero; -select 10.0 ^ -2147483647 as rounds_to_zero; -select 10.0 ^ 2147483647 as overflows; -select 117743296169.0 ^ 1000000000 as overflows; - --- cases that used to return inaccurate results -select 3.789 ^ 21; -select 3.789 ^ 35; -select 1.2 ^ 345; -select 0.12 ^ (-20); -select 1.000000000123 ^ (-2147483648); -select coalesce(nullif(0.9999999999 ^ 23300000000000, 0), 0) as rounds_to_zero; -select round(((1 - 1.500012345678e-1000) ^ 1.45e1003) * 1e1000); - --- cases that used to error out -select 0.12 ^ (-25); -select 0.5678 ^ (-85); -select coalesce(nullif(0.9999999999 ^ 70000000000000, 0), 0) as underflows; - --- negative base to integer powers -select (-1.0) ^ 2147483646; -select (-1.0) ^ 2147483647; -select (-1.0) ^ 2147483648; -select (-1.0) ^ 1000000000000000; -select (-1.0) ^ 1000000000000001; - --- --- Tests for raising to non-integer powers --- - --- special cases -select 0.0 ^ 0.0; -select (-12.34) ^ 0.0; -select 12.34 ^ 0.0; -select 0.0 ^ 12.34; - --- NaNs -select 'NaN'::numeric ^ 'NaN'::numeric; -select 'NaN'::numeric ^ 0; -select 'NaN'::numeric ^ 1; -select 0 ^ 'NaN'::numeric; -select 1 ^ 'NaN'::numeric; - --- invalid inputs -select 0.0 ^ (-12.34); -select (-12.34) ^ 1.2; - --- cases that used to generate inaccurate results -select 32.1 ^ 9.8; -select 32.1 ^ (-9.8); -select 12.3 ^ 45.6; -select 12.3 ^ (-45.6); - --- big test -select 1.234 ^ 5678; - --- --- Tests for EXP() --- - --- special cases -select exp(0.0); -select exp(1.0); -select exp(1.0::numeric(71,70)); -select exp('nan'::numeric); -select exp('inf'::numeric); -select exp('-inf'::numeric); -select coalesce(nullif(exp(-5000::numeric), 0), 0) as rounds_to_zero; -select coalesce(nullif(exp(-10000::numeric), 0), 0) as underflows; - --- cases that used to generate inaccurate results -select exp(32.999); -select exp(-32.999); -select exp(123.456); -select exp(-123.456); - --- big test -select exp(1234.5678); - --- --- Tests for generate_series --- -select * from generate_series(0.0::numeric, 4.0::numeric); -select * from generate_series(0.1::numeric, 4.0::numeric, 1.3::numeric); -select * from generate_series(4.0::numeric, -1.5::numeric, -2.2::numeric); --- Trigger errors -select * from generate_series(-100::numeric, 100::numeric, 0::numeric); -select * from generate_series(-100::numeric, 100::numeric, 'nan'::numeric); -select * from generate_series('nan'::numeric, 100::numeric, 10::numeric); -select * from generate_series(0::numeric, 'nan'::numeric, 10::numeric); -select * from generate_series('inf'::numeric, 'inf'::numeric, 10::numeric); -select * from generate_series(0::numeric, 'inf'::numeric, 10::numeric); -select * from generate_series(0::numeric, '42'::numeric, '-inf'::numeric); --- Checks maximum, output is truncated -select (i / (10::numeric ^ 131071))::numeric(1,0) - from generate_series(6 * (10::numeric ^ 131071), - 9 * (10::numeric ^ 131071), - 10::numeric ^ 131071) as a(i); --- Check usage with variables -select * from generate_series(1::numeric, 3::numeric) i, generate_series(i,3) j; -select * from generate_series(1::numeric, 3::numeric) i, generate_series(1,i) j; -select * from generate_series(1::numeric, 3::numeric) i, generate_series(1,5,i) j; - --- --- Tests for LN() --- - --- Invalid inputs -select ln(-12.34); -select ln(0.0); - --- Some random tests -select ln(1.2345678e-28); -select ln(0.0456789); -select ln(0.349873948359354029493948309745709580730482050975); -select ln(0.99949452); -select ln(1.00049687395); -select ln(1234.567890123456789); -select ln(5.80397490724e5); -select ln(9.342536355e34); - --- --- Tests for LOG() (base 10) --- - --- invalid inputs -select log(-12.34); -select log(0.0); - --- some random tests -select log(1.234567e-89); -select log(3.4634998359873254962349856073435545); -select log(9.999999999999999999); -select log(10.00000000000000000); -select log(10.00000000000000001); -select log(590489.45235237); - --- --- Tests for LOG() (arbitrary base) --- - --- invalid inputs -select log(-12.34, 56.78); -select log(-12.34, -56.78); -select log(12.34, -56.78); -select log(0.0, 12.34); -select log(12.34, 0.0); -select log(1.0, 12.34); - --- some random tests -select log(1.23e-89, 6.4689e45); -select log(0.99923, 4.58934e34); -select log(1.000016, 8.452010e18); -select log(3.1954752e47, 9.4792021e-73); - --- --- Tests for scale() --- - -select scale(numeric 'NaN'); -select scale(numeric 'inf'); -select scale(NULL::numeric); -select scale(1.12); -select scale(0); -select scale(0.00); -select scale(1.12345); -select scale(110123.12475871856128); -select scale(-1123.12471856128); -select scale(-13.000000000000000); - --- --- Tests for min_scale() --- - -select min_scale(numeric 'NaN') is NULL; -- should be true -select min_scale(numeric 'inf') is NULL; -- should be true -select min_scale(0); -- no digits -select min_scale(0.00); -- no digits again -select min_scale(1.0); -- no scale -select min_scale(1.1); -- scale 1 -select min_scale(1.12); -- scale 2 -select min_scale(1.123); -- scale 3 -select min_scale(1.1234); -- scale 4, filled digit -select min_scale(1.12345); -- scale 5, 2 NDIGITS -select min_scale(1.1000); -- 1 pos in NDIGITS -select min_scale(1e100); -- very big number - --- --- Tests for trim_scale() --- - -select trim_scale(numeric 'NaN'); -select trim_scale(numeric 'inf'); -select trim_scale(1.120); -select trim_scale(0); -select trim_scale(0.00); -select trim_scale(1.1234500); -select trim_scale(110123.12475871856128000); -select trim_scale(-1123.124718561280000000); -select trim_scale(-13.00000000000000000000); -select trim_scale(1e100); - --- --- Tests for SUM() --- - --- cases that need carry propagation -SELECT SUM(9999::numeric) FROM generate_series(1, 100000); -SELECT SUM((-9999)::numeric) FROM generate_series(1, 100000); - --- --- Tests for VARIANCE() --- -CREATE TABLE num_variance (a numeric); -INSERT INTO num_variance VALUES (0); -INSERT INTO num_variance VALUES (3e-500); -INSERT INTO num_variance VALUES (-3e-500); -INSERT INTO num_variance VALUES (4e-500 - 1e-16383); -INSERT INTO num_variance VALUES (-4e-500 + 1e-16383); - --- variance is just under 12.5e-1000 and so should round down to 12e-1000 -SELECT trim_scale(variance(a) * 1e1000) FROM num_variance; - --- check that parallel execution produces the same result -BEGIN; -ALTER TABLE num_variance SET (parallel_workers = 4); -SET LOCAL parallel_setup_cost = 0; -SET LOCAL max_parallel_workers_per_gather = 4; -SELECT trim_scale(variance(a) * 1e1000) FROM num_variance; -ROLLBACK; - --- case where sum of squares would overflow but variance does not -DELETE FROM num_variance; -INSERT INTO num_variance SELECT 9e131071 + x FROM generate_series(1, 5) x; -SELECT variance(a) FROM num_variance; - --- check that parallel execution produces the same result -BEGIN; -ALTER TABLE num_variance SET (parallel_workers = 4); -SET LOCAL parallel_setup_cost = 0; -SET LOCAL max_parallel_workers_per_gather = 4; -SELECT variance(a) FROM num_variance; -ROLLBACK; - -DROP TABLE num_variance; - --- --- Tests for GCD() --- -SELECT a, b, gcd(a, b), gcd(a, -b), gcd(-b, a), gcd(-b, -a) -FROM (VALUES (0::numeric, 0::numeric), - (0::numeric, numeric 'NaN'), - (0::numeric, 46375::numeric), - (433125::numeric, 46375::numeric), - (43312.5::numeric, 4637.5::numeric), - (4331.250::numeric, 463.75000::numeric), - ('inf', '0'), - ('inf', '42'), - ('inf', 'inf') - ) AS v(a, b); - --- --- Tests for LCM() --- -SELECT a,b, lcm(a, b), lcm(a, -b), lcm(-b, a), lcm(-b, -a) -FROM (VALUES (0::numeric, 0::numeric), - (0::numeric, numeric 'NaN'), - (0::numeric, 13272::numeric), - (13272::numeric, 13272::numeric), - (423282::numeric, 13272::numeric), - (42328.2::numeric, 1327.2::numeric), - (4232.820::numeric, 132.72000::numeric), - ('inf', '0'), - ('inf', '42'), - ('inf', 'inf') - ) AS v(a, b); - -SELECT lcm(9999 * (10::numeric)^131068 + (10::numeric^131068 - 1), 2); -- overflow - --- --- Tests for factorial --- -SELECT factorial(4); -SELECT factorial(15); -SELECT factorial(100000); -SELECT factorial(0); -SELECT factorial(-4); - --- --- Tests for pg_lsn() --- -SELECT pg_lsn(23783416::numeric); -SELECT pg_lsn(0::numeric); -SELECT pg_lsn(18446744073709551615::numeric); -SELECT pg_lsn(-1::numeric); -SELECT pg_lsn(18446744073709551616::numeric); -SELECT pg_lsn('NaN'::numeric); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fobject_address.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fobject_address.sql deleted file mode 100644 index acd0468a9d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fobject_address.sql +++ /dev/null @@ -1,290 +0,0 @@ --- --- Test for pg_get_object_address --- - --- Clean up in case a prior regression run failed -SET client_min_messages TO 'warning'; -DROP ROLE IF EXISTS regress_addr_user; -RESET client_min_messages; - -CREATE USER regress_addr_user; - --- Test generic object addressing/identification functions -CREATE SCHEMA addr_nsp; -SET search_path TO 'addr_nsp'; -CREATE FOREIGN DATA WRAPPER addr_fdw; -CREATE SERVER addr_fserv FOREIGN DATA WRAPPER addr_fdw; -CREATE TEXT SEARCH DICTIONARY addr_ts_dict (template=simple); -CREATE TEXT SEARCH CONFIGURATION addr_ts_conf (copy=english); -CREATE TEXT SEARCH TEMPLATE addr_ts_temp (lexize=dsimple_lexize); -CREATE TEXT SEARCH PARSER addr_ts_prs - (start = prsd_start, gettoken = prsd_nexttoken, end = prsd_end, lextypes = prsd_lextype); -CREATE TABLE addr_nsp.gentable ( - a serial primary key CONSTRAINT a_chk CHECK (a > 0), - b text DEFAULT 'hello'); -CREATE TABLE addr_nsp.parttable ( - a int PRIMARY KEY -) PARTITION BY RANGE (a); -CREATE VIEW addr_nsp.genview AS SELECT * from addr_nsp.gentable; -CREATE MATERIALIZED VIEW addr_nsp.genmatview AS SELECT * FROM addr_nsp.gentable; -CREATE TYPE addr_nsp.gencomptype AS (a int); -CREATE TYPE addr_nsp.genenum AS ENUM ('one', 'two'); -CREATE FOREIGN TABLE addr_nsp.genftable (a int) SERVER addr_fserv; -CREATE AGGREGATE addr_nsp.genaggr(int4) (sfunc = int4pl, stype = int4); -CREATE DOMAIN addr_nsp.gendomain AS int4 CONSTRAINT domconstr CHECK (value > 0); -CREATE FUNCTION addr_nsp.trig() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN END; $$; -CREATE TRIGGER t BEFORE INSERT ON addr_nsp.gentable FOR EACH ROW EXECUTE PROCEDURE addr_nsp.trig(); -CREATE POLICY genpol ON addr_nsp.gentable; -CREATE PROCEDURE addr_nsp.proc(int4) LANGUAGE SQL AS $$ $$; -CREATE SERVER "integer" FOREIGN DATA WRAPPER addr_fdw; -CREATE USER MAPPING FOR regress_addr_user SERVER "integer"; -ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user IN SCHEMA public GRANT ALL ON TABLES TO regress_addr_user; -ALTER DEFAULT PRIVILEGES FOR ROLE regress_addr_user REVOKE DELETE ON TABLES FROM regress_addr_user; --- this transform would be quite unsafe to leave lying around, --- except that the SQL language pays no attention to transforms: -CREATE TRANSFORM FOR int LANGUAGE SQL ( - FROM SQL WITH FUNCTION prsd_lextype(internal), - TO SQL WITH FUNCTION int4recv(internal)); --- suppress warning that depends on wal_level -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION addr_pub FOR TABLE addr_nsp.gentable; -CREATE PUBLICATION addr_pub_schema FOR ALL TABLES IN SCHEMA addr_nsp; -RESET client_min_messages; -CREATE SUBSCRIPTION regress_addr_sub CONNECTION '' PUBLICATION bar WITH (connect = false, slot_name = NONE); -CREATE STATISTICS addr_nsp.gentable_stat ON a, b FROM addr_nsp.gentable; - --- test some error cases -SELECT pg_get_object_address('stone', '{}', '{}'); -SELECT pg_get_object_address('table', '{}', '{}'); -SELECT pg_get_object_address('table', '{NULL}', '{}'); - --- unrecognized object types -DO $$ -DECLARE - objtype text; -BEGIN - FOR objtype IN VALUES ('toast table'), ('index column'), ('sequence column'), - ('toast table column'), ('view column'), ('materialized view column') - LOOP - BEGIN - PERFORM pg_get_object_address(objtype, '{one}', '{}'); - EXCEPTION WHEN invalid_parameter_value THEN - RAISE WARNING 'error for %: %', objtype, sqlerrm; - END; - END LOOP; -END; -$$; - --- miscellaneous other errors -select * from pg_get_object_address('operator of access method', '{btree,integer_ops,1}', '{int4,bool}'); -select * from pg_get_object_address('operator of access method', '{btree,integer_ops,99}', '{int4,int4}'); -select * from pg_get_object_address('function of access method', '{btree,integer_ops,1}', '{int4,bool}'); -select * from pg_get_object_address('function of access method', '{btree,integer_ops,99}', '{int4,int4}'); - -DO $$ -DECLARE - objtype text; - names text[]; - args text[]; -BEGIN - FOR objtype IN VALUES - ('table'), ('index'), ('sequence'), ('view'), - ('materialized view'), ('foreign table'), - ('table column'), ('foreign table column'), - ('aggregate'), ('function'), ('procedure'), ('type'), ('cast'), - ('table constraint'), ('domain constraint'), ('conversion'), ('default value'), - ('operator'), ('operator class'), ('operator family'), ('rule'), ('trigger'), - ('text search parser'), ('text search dictionary'), - ('text search template'), ('text search configuration'), - ('policy'), ('user mapping'), ('default acl'), ('transform'), - ('operator of access method'), ('function of access method'), - ('publication relation') - LOOP - FOR names IN VALUES ('{eins}'), ('{addr_nsp, zwei}'), ('{eins, zwei, drei}') - LOOP - FOR args IN VALUES ('{}'), ('{integer}') - LOOP - BEGIN - PERFORM pg_get_object_address(objtype, names, args); - EXCEPTION WHEN OTHERS THEN - RAISE WARNING 'error for %,%,%: %', objtype, names, args, sqlerrm; - END; - END LOOP; - END LOOP; - END LOOP; -END; -$$; - --- these object types cannot be qualified names -SELECT pg_get_object_address('language', '{one}', '{}'); -SELECT pg_get_object_address('language', '{one,two}', '{}'); -SELECT pg_get_object_address('large object', '{123}', '{}'); -SELECT pg_get_object_address('large object', '{123,456}', '{}'); -SELECT pg_get_object_address('large object', '{blargh}', '{}'); -SELECT pg_get_object_address('schema', '{one}', '{}'); -SELECT pg_get_object_address('schema', '{one,two}', '{}'); -SELECT pg_get_object_address('role', '{one}', '{}'); -SELECT pg_get_object_address('role', '{one,two}', '{}'); -SELECT pg_get_object_address('database', '{one}', '{}'); -SELECT pg_get_object_address('database', '{one,two}', '{}'); -SELECT pg_get_object_address('tablespace', '{one}', '{}'); -SELECT pg_get_object_address('tablespace', '{one,two}', '{}'); -SELECT pg_get_object_address('foreign-data wrapper', '{one}', '{}'); -SELECT pg_get_object_address('foreign-data wrapper', '{one,two}', '{}'); -SELECT pg_get_object_address('server', '{one}', '{}'); -SELECT pg_get_object_address('server', '{one,two}', '{}'); -SELECT pg_get_object_address('extension', '{one}', '{}'); -SELECT pg_get_object_address('extension', '{one,two}', '{}'); -SELECT pg_get_object_address('event trigger', '{one}', '{}'); -SELECT pg_get_object_address('event trigger', '{one,two}', '{}'); -SELECT pg_get_object_address('access method', '{one}', '{}'); -SELECT pg_get_object_address('access method', '{one,two}', '{}'); -SELECT pg_get_object_address('publication', '{one}', '{}'); -SELECT pg_get_object_address('publication', '{one,two}', '{}'); -SELECT pg_get_object_address('subscription', '{one}', '{}'); -SELECT pg_get_object_address('subscription', '{one,two}', '{}'); - --- test successful cases -WITH objects (type, name, args) AS (VALUES - ('table', '{addr_nsp, gentable}'::text[], '{}'::text[]), - ('table', '{addr_nsp, parttable}'::text[], '{}'::text[]), - ('index', '{addr_nsp, gentable_pkey}', '{}'), - ('index', '{addr_nsp, parttable_pkey}', '{}'), - ('sequence', '{addr_nsp, gentable_a_seq}', '{}'), - -- toast table - ('view', '{addr_nsp, genview}', '{}'), - ('materialized view', '{addr_nsp, genmatview}', '{}'), - ('foreign table', '{addr_nsp, genftable}', '{}'), - ('table column', '{addr_nsp, gentable, b}', '{}'), - ('foreign table column', '{addr_nsp, genftable, a}', '{}'), - ('aggregate', '{addr_nsp, genaggr}', '{int4}'), - ('function', '{pg_catalog, pg_identify_object}', '{pg_catalog.oid, pg_catalog.oid, int4}'), - ('procedure', '{addr_nsp, proc}', '{int4}'), - ('type', '{pg_catalog._int4}', '{}'), - ('type', '{addr_nsp.gendomain}', '{}'), - ('type', '{addr_nsp.gencomptype}', '{}'), - ('type', '{addr_nsp.genenum}', '{}'), - ('cast', '{int8}', '{int4}'), - ('collation', '{default}', '{}'), - ('table constraint', '{addr_nsp, gentable, a_chk}', '{}'), - ('domain constraint', '{addr_nsp.gendomain}', '{domconstr}'), - ('conversion', '{pg_catalog, koi8_r_to_mic}', '{}'), - ('default value', '{addr_nsp, gentable, b}', '{}'), - ('language', '{plpgsql}', '{}'), - -- large object - ('operator', '{+}', '{int4, int4}'), - ('operator class', '{btree, int4_ops}', '{}'), - ('operator family', '{btree, integer_ops}', '{}'), - ('operator of access method', '{btree,integer_ops,1}', '{integer,integer}'), - ('function of access method', '{btree,integer_ops,2}', '{integer,integer}'), - ('rule', '{addr_nsp, genview, _RETURN}', '{}'), - ('trigger', '{addr_nsp, gentable, t}', '{}'), - ('schema', '{addr_nsp}', '{}'), - ('text search parser', '{addr_ts_prs}', '{}'), - ('text search dictionary', '{addr_ts_dict}', '{}'), - ('text search template', '{addr_ts_temp}', '{}'), - ('text search configuration', '{addr_ts_conf}', '{}'), - ('role', '{regress_addr_user}', '{}'), - -- database - -- tablespace - ('foreign-data wrapper', '{addr_fdw}', '{}'), - ('server', '{addr_fserv}', '{}'), - ('user mapping', '{regress_addr_user}', '{integer}'), - ('default acl', '{regress_addr_user,public}', '{r}'), - ('default acl', '{regress_addr_user}', '{r}'), - -- extension - -- event trigger - ('policy', '{addr_nsp, gentable, genpol}', '{}'), - ('transform', '{int}', '{sql}'), - ('access method', '{btree}', '{}'), - ('publication', '{addr_pub}', '{}'), - ('publication namespace', '{addr_nsp}', '{addr_pub_schema}'), - ('publication relation', '{addr_nsp, gentable}', '{addr_pub}'), - ('subscription', '{regress_addr_sub}', '{}'), - ('statistics object', '{addr_nsp, gentable_stat}', '{}') - ) -SELECT (pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)).*, - -- test roundtrip through pg_identify_object_as_address - ROW(pg_identify_object(addr1.classid, addr1.objid, addr1.objsubid)) = - ROW(pg_identify_object(addr2.classid, addr2.objid, addr2.objsubid)) - FROM objects, pg_get_object_address(type, name, args) addr1, - pg_identify_object_as_address(classid, objid, objsubid) ioa(typ,nms,args), - pg_get_object_address(typ, nms, ioa.args) as addr2 - ORDER BY addr1.classid, addr1.objid, addr1.objsubid; - ---- ---- Cleanup resources ---- -DROP FOREIGN DATA WRAPPER addr_fdw CASCADE; -DROP PUBLICATION addr_pub; -DROP PUBLICATION addr_pub_schema; -DROP SUBSCRIPTION regress_addr_sub; - -DROP SCHEMA addr_nsp CASCADE; - -DROP OWNED BY regress_addr_user; -DROP USER regress_addr_user; - --- --- Checks for invalid objects --- --- Make sure that NULL handling is correct. -\pset null 'NULL' --- Temporarily disable fancy output, so as future additions never create --- a large amount of diffs. -\a\t - --- Keep this list in the same order as getObjectIdentityParts() --- in objectaddress.c. -WITH objects (classid, objid, objsubid) AS (VALUES - ('pg_class'::regclass, 0, 0), -- no relation - ('pg_class'::regclass, 'pg_class'::regclass, 100), -- no column for relation - ('pg_proc'::regclass, 0, 0), -- no function - ('pg_type'::regclass, 0, 0), -- no type - ('pg_cast'::regclass, 0, 0), -- no cast - ('pg_collation'::regclass, 0, 0), -- no collation - ('pg_constraint'::regclass, 0, 0), -- no constraint - ('pg_conversion'::regclass, 0, 0), -- no conversion - ('pg_attrdef'::regclass, 0, 0), -- no default attribute - ('pg_language'::regclass, 0, 0), -- no language - ('pg_largeobject'::regclass, 0, 0), -- no large object, no error - ('pg_operator'::regclass, 0, 0), -- no operator - ('pg_opclass'::regclass, 0, 0), -- no opclass, no need to check for no access method - ('pg_opfamily'::regclass, 0, 0), -- no opfamily - ('pg_am'::regclass, 0, 0), -- no access method - ('pg_amop'::regclass, 0, 0), -- no AM operator - ('pg_amproc'::regclass, 0, 0), -- no AM proc - ('pg_rewrite'::regclass, 0, 0), -- no rewrite - ('pg_trigger'::regclass, 0, 0), -- no trigger - ('pg_namespace'::regclass, 0, 0), -- no schema - ('pg_statistic_ext'::regclass, 0, 0), -- no statistics - ('pg_ts_parser'::regclass, 0, 0), -- no TS parser - ('pg_ts_dict'::regclass, 0, 0), -- no TS dictionary - ('pg_ts_template'::regclass, 0, 0), -- no TS template - ('pg_ts_config'::regclass, 0, 0), -- no TS configuration - ('pg_authid'::regclass, 0, 0), -- no role - ('pg_database'::regclass, 0, 0), -- no database - ('pg_tablespace'::regclass, 0, 0), -- no tablespace - ('pg_foreign_data_wrapper'::regclass, 0, 0), -- no FDW - ('pg_foreign_server'::regclass, 0, 0), -- no server - ('pg_user_mapping'::regclass, 0, 0), -- no user mapping - ('pg_default_acl'::regclass, 0, 0), -- no default ACL - ('pg_extension'::regclass, 0, 0), -- no extension - ('pg_event_trigger'::regclass, 0, 0), -- no event trigger - ('pg_policy'::regclass, 0, 0), -- no policy - ('pg_publication'::regclass, 0, 0), -- no publication - ('pg_publication_rel'::regclass, 0, 0), -- no publication relation - ('pg_subscription'::regclass, 0, 0), -- no subscription - ('pg_transform'::regclass, 0, 0) -- no transformation - ) -SELECT ROW(pg_identify_object(objects.classid, objects.objid, objects.objsubid)) - AS ident, - ROW(pg_identify_object_as_address(objects.classid, objects.objid, objects.objsubid)) - AS addr, - pg_describe_object(objects.classid, objects.objid, objects.objsubid) - AS descr -FROM objects -ORDER BY objects.classid, objects.objid, objects.objsubid; - --- restore normal output mode -\a\t diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpartition_prune.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpartition_prune.sql deleted file mode 100644 index d70bd8610c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpartition_prune.sql +++ /dev/null @@ -1,1189 +0,0 @@ --- --- Test partitioning planner code --- - --- Force generic plans to be used for all prepared statements in this file. -set plan_cache_mode = force_generic_plan; - -create table lp (a char) partition by list (a); -create table lp_default partition of lp default; -create table lp_ef partition of lp for values in ('e', 'f'); -create table lp_ad partition of lp for values in ('a', 'd'); -create table lp_bc partition of lp for values in ('b', 'c'); -create table lp_g partition of lp for values in ('g'); -create table lp_null partition of lp for values in (null); -explain (costs off) select * from lp; -explain (costs off) select * from lp where a > 'a' and a < 'd'; -explain (costs off) select * from lp where a > 'a' and a <= 'd'; -explain (costs off) select * from lp where a = 'a'; -explain (costs off) select * from lp where 'a' = a; /* commuted */ -explain (costs off) select * from lp where a is not null; -explain (costs off) select * from lp where a is null; -explain (costs off) select * from lp where a = 'a' or a = 'c'; -explain (costs off) select * from lp where a is not null and (a = 'a' or a = 'c'); -explain (costs off) select * from lp where a <> 'g'; -explain (costs off) select * from lp where a <> 'a' and a <> 'd'; -explain (costs off) select * from lp where a not in ('a', 'd'); - --- collation matches the partitioning collation, pruning works -create table coll_pruning (a text collate "C") partition by list (a); -create table coll_pruning_a partition of coll_pruning for values in ('a'); -create table coll_pruning_b partition of coll_pruning for values in ('b'); -create table coll_pruning_def partition of coll_pruning default; -explain (costs off) select * from coll_pruning where a collate "C" = 'a' collate "C"; --- collation doesn't match the partitioning collation, no pruning occurs -explain (costs off) select * from coll_pruning where a collate "POSIX" = 'a' collate "POSIX"; - -create table rlp (a int, b varchar) partition by range (a); -create table rlp_default partition of rlp default partition by list (a); -create table rlp_default_default partition of rlp_default default; -create table rlp_default_10 partition of rlp_default for values in (10); -create table rlp_default_30 partition of rlp_default for values in (30); -create table rlp_default_null partition of rlp_default for values in (null); -create table rlp1 partition of rlp for values from (minvalue) to (1); -create table rlp2 partition of rlp for values from (1) to (10); - -create table rlp3 (b varchar, a int) partition by list (b varchar_ops); -create table rlp3_default partition of rlp3 default; -create table rlp3abcd partition of rlp3 for values in ('ab', 'cd'); -create table rlp3efgh partition of rlp3 for values in ('ef', 'gh'); -create table rlp3nullxy partition of rlp3 for values in (null, 'xy'); -alter table rlp attach partition rlp3 for values from (15) to (20); - -create table rlp4 partition of rlp for values from (20) to (30) partition by range (a); -create table rlp4_default partition of rlp4 default; -create table rlp4_1 partition of rlp4 for values from (20) to (25); -create table rlp4_2 partition of rlp4 for values from (25) to (29); - -create table rlp5 partition of rlp for values from (31) to (maxvalue) partition by range (a); -create table rlp5_default partition of rlp5 default; -create table rlp5_1 partition of rlp5 for values from (31) to (40); - -explain (costs off) select * from rlp where a < 1; -explain (costs off) select * from rlp where 1 > a; /* commuted */ -explain (costs off) select * from rlp where a <= 1; -explain (costs off) select * from rlp where a = 1; -explain (costs off) select * from rlp where a = 1::bigint; /* same as above */ -explain (costs off) select * from rlp where a = 1::numeric; /* no pruning */ -explain (costs off) select * from rlp where a <= 10; -explain (costs off) select * from rlp where a > 10; -explain (costs off) select * from rlp where a < 15; -explain (costs off) select * from rlp where a <= 15; -explain (costs off) select * from rlp where a > 15 and b = 'ab'; -explain (costs off) select * from rlp where a = 16; -explain (costs off) select * from rlp where a = 16 and b in ('not', 'in', 'here'); -explain (costs off) select * from rlp where a = 16 and b < 'ab'; -explain (costs off) select * from rlp where a = 16 and b <= 'ab'; -explain (costs off) select * from rlp where a = 16 and b is null; -explain (costs off) select * from rlp where a = 16 and b is not null; -explain (costs off) select * from rlp where a is null; -explain (costs off) select * from rlp where a is not null; -explain (costs off) select * from rlp where a > 30; -explain (costs off) select * from rlp where a = 30; /* only default is scanned */ -explain (costs off) select * from rlp where a <= 31; -explain (costs off) select * from rlp where a = 1 or a = 7; -explain (costs off) select * from rlp where a = 1 or b = 'ab'; - -explain (costs off) select * from rlp where a > 20 and a < 27; -explain (costs off) select * from rlp where a = 29; -explain (costs off) select * from rlp where a >= 29; -explain (costs off) select * from rlp where a < 1 or (a > 20 and a < 25); - --- where clause contradicts sub-partition's constraint -explain (costs off) select * from rlp where a = 20 or a = 40; -explain (costs off) select * from rlp3 where a = 20; /* empty */ - --- redundant clauses are eliminated -explain (costs off) select * from rlp where a > 1 and a = 10; /* only default */ -explain (costs off) select * from rlp where a > 1 and a >=15; /* rlp3 onwards, including default */ -explain (costs off) select * from rlp where a = 1 and a = 3; /* empty */ -explain (costs off) select * from rlp where (a = 1 and a = 3) or (a > 1 and a = 15); - --- multi-column keys -create table mc3p (a int, b int, c int) partition by range (a, abs(b), c); -create table mc3p_default partition of mc3p default; -create table mc3p0 partition of mc3p for values from (minvalue, minvalue, minvalue) to (1, 1, 1); -create table mc3p1 partition of mc3p for values from (1, 1, 1) to (10, 5, 10); -create table mc3p2 partition of mc3p for values from (10, 5, 10) to (10, 10, 10); -create table mc3p3 partition of mc3p for values from (10, 10, 10) to (10, 10, 20); -create table mc3p4 partition of mc3p for values from (10, 10, 20) to (10, maxvalue, maxvalue); -create table mc3p5 partition of mc3p for values from (11, 1, 1) to (20, 10, 10); -create table mc3p6 partition of mc3p for values from (20, 10, 10) to (20, 20, 20); -create table mc3p7 partition of mc3p for values from (20, 20, 20) to (maxvalue, maxvalue, maxvalue); - -explain (costs off) select * from mc3p where a = 1; -explain (costs off) select * from mc3p where a = 1 and abs(b) < 1; -explain (costs off) select * from mc3p where a = 1 and abs(b) = 1; -explain (costs off) select * from mc3p where a = 1 and abs(b) = 1 and c < 8; -explain (costs off) select * from mc3p where a = 10 and abs(b) between 5 and 35; -explain (costs off) select * from mc3p where a > 10; -explain (costs off) select * from mc3p where a >= 10; -explain (costs off) select * from mc3p where a < 10; -explain (costs off) select * from mc3p where a <= 10 and abs(b) < 10; -explain (costs off) select * from mc3p where a = 11 and abs(b) = 0; -explain (costs off) select * from mc3p where a = 20 and abs(b) = 10 and c = 100; -explain (costs off) select * from mc3p where a > 20; -explain (costs off) select * from mc3p where a >= 20; -explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1 and c = 1) or (a = 10 and abs(b) = 5 and c = 10) or (a > 11 and a < 20); -explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1 and c = 1) or (a = 10 and abs(b) = 5 and c = 10) or (a > 11 and a < 20) or a < 1; -explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1 and c = 1) or (a = 10 and abs(b) = 5 and c = 10) or (a > 11 and a < 20) or a < 1 or a = 1; -explain (costs off) select * from mc3p where a = 1 or abs(b) = 1 or c = 1; -explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1) or (a = 10 and abs(b) = 10); -explain (costs off) select * from mc3p where (a = 1 and abs(b) = 1) or (a = 10 and abs(b) = 9); - --- a simpler multi-column keys case -create table mc2p (a int, b int) partition by range (a, b); -create table mc2p_default partition of mc2p default; -create table mc2p0 partition of mc2p for values from (minvalue, minvalue) to (1, minvalue); -create table mc2p1 partition of mc2p for values from (1, minvalue) to (1, 1); -create table mc2p2 partition of mc2p for values from (1, 1) to (2, minvalue); -create table mc2p3 partition of mc2p for values from (2, minvalue) to (2, 1); -create table mc2p4 partition of mc2p for values from (2, 1) to (2, maxvalue); -create table mc2p5 partition of mc2p for values from (2, maxvalue) to (maxvalue, maxvalue); - -explain (costs off) select * from mc2p where a < 2; -explain (costs off) select * from mc2p where a = 2 and b < 1; -explain (costs off) select * from mc2p where a > 1; -explain (costs off) select * from mc2p where a = 1 and b > 1; - --- all partitions but the default one should be pruned -explain (costs off) select * from mc2p where a = 1 and b is null; -explain (costs off) select * from mc2p where a is null and b is null; -explain (costs off) select * from mc2p where a is null and b = 1; -explain (costs off) select * from mc2p where a is null; -explain (costs off) select * from mc2p where b is null; - --- boolean partitioning -create table boolpart (a bool) partition by list (a); -create table boolpart_default partition of boolpart default; -create table boolpart_t partition of boolpart for values in ('true'); -create table boolpart_f partition of boolpart for values in ('false'); - -explain (costs off) select * from boolpart where a in (true, false); -explain (costs off) select * from boolpart where a = false; -explain (costs off) select * from boolpart where not a = false; -explain (costs off) select * from boolpart where a is true or a is not true; -explain (costs off) select * from boolpart where a is not true; -explain (costs off) select * from boolpart where a is not true and a is not false; -explain (costs off) select * from boolpart where a is unknown; -explain (costs off) select * from boolpart where a is not unknown; - -create table boolrangep (a bool, b bool, c int) partition by range (a,b,c); -create table boolrangep_tf partition of boolrangep for values from ('true', 'false', 0) to ('true', 'false', 100); -create table boolrangep_ft partition of boolrangep for values from ('false', 'true', 0) to ('false', 'true', 100); -create table boolrangep_ff1 partition of boolrangep for values from ('false', 'false', 0) to ('false', 'false', 50); -create table boolrangep_ff2 partition of boolrangep for values from ('false', 'false', 50) to ('false', 'false', 100); - --- try a more complex case that's been known to trip up pruning in the past -explain (costs off) select * from boolrangep where not a and not b and c = 25; - --- test scalar-to-array operators -create table coercepart (a varchar) partition by list (a); -create table coercepart_ab partition of coercepart for values in ('ab'); -create table coercepart_bc partition of coercepart for values in ('bc'); -create table coercepart_cd partition of coercepart for values in ('cd'); - -explain (costs off) select * from coercepart where a in ('ab', to_char(125, '999')); -explain (costs off) select * from coercepart where a ~ any ('{ab}'); -explain (costs off) select * from coercepart where a !~ all ('{ab}'); -explain (costs off) select * from coercepart where a ~ any ('{ab,bc}'); -explain (costs off) select * from coercepart where a !~ all ('{ab,bc}'); -explain (costs off) select * from coercepart where a = any ('{ab,bc}'); -explain (costs off) select * from coercepart where a = any ('{ab,null}'); -explain (costs off) select * from coercepart where a = any (null::text[]); -explain (costs off) select * from coercepart where a = all ('{ab}'); -explain (costs off) select * from coercepart where a = all ('{ab,bc}'); -explain (costs off) select * from coercepart where a = all ('{ab,null}'); -explain (costs off) select * from coercepart where a = all (null::text[]); - -drop table coercepart; - -CREATE TABLE part (a INT, b INT) PARTITION BY LIST (a); -CREATE TABLE part_p1 PARTITION OF part FOR VALUES IN (-2,-1,0,1,2); -CREATE TABLE part_p2 PARTITION OF part DEFAULT PARTITION BY RANGE(a); -CREATE TABLE part_p2_p1 PARTITION OF part_p2 DEFAULT; -CREATE TABLE part_rev (b INT, c INT, a INT); -ALTER TABLE part ATTACH PARTITION part_rev FOR VALUES IN (3); -- fail -ALTER TABLE part_rev DROP COLUMN c; -ALTER TABLE part ATTACH PARTITION part_rev FOR VALUES IN (3); -- now it's ok -INSERT INTO part VALUES (-1,-1), (1,1), (2,NULL), (NULL,-2),(NULL,NULL); -EXPLAIN (COSTS OFF) SELECT tableoid::regclass as part, a, b FROM part WHERE a IS NULL ORDER BY 1, 2, 3; -EXPLAIN (VERBOSE, COSTS OFF) SELECT * FROM part p(x) ORDER BY x; - --- --- some more cases --- - --- --- pruning for partitioned table appearing inside a sub-query --- --- pruning won't work for mc3p, because some keys are Params -explain (costs off) select * from mc2p t1, lateral (select count(*) from mc3p t2 where t2.a = t1.b and abs(t2.b) = 1 and t2.c = 1) s where t1.a = 1; - --- pruning should work fine, because values for a prefix of keys (a, b) are --- available -explain (costs off) select * from mc2p t1, lateral (select count(*) from mc3p t2 where t2.c = t1.b and abs(t2.b) = 1 and t2.a = 1) s where t1.a = 1; - --- also here, because values for all keys are provided -explain (costs off) select * from mc2p t1, lateral (select count(*) from mc3p t2 where t2.a = 1 and abs(t2.b) = 1 and t2.c = 1) s where t1.a = 1; - --- --- pruning with clauses containing <> operator --- - --- doesn't prune range partitions -create table rp (a int) partition by range (a); -create table rp0 partition of rp for values from (minvalue) to (1); -create table rp1 partition of rp for values from (1) to (2); -create table rp2 partition of rp for values from (2) to (maxvalue); - -explain (costs off) select * from rp where a <> 1; -explain (costs off) select * from rp where a <> 1 and a <> 2; - --- null partition should be eliminated due to strict <> clause. -explain (costs off) select * from lp where a <> 'a'; - --- ensure we detect contradictions in clauses; a can't be NULL and NOT NULL. -explain (costs off) select * from lp where a <> 'a' and a is null; -explain (costs off) select * from lp where (a <> 'a' and a <> 'd') or a is null; - --- check that it also works for a partitioned table that's not root, --- which in this case are partitions of rlp that are themselves --- list-partitioned on b -explain (costs off) select * from rlp where a = 15 and b <> 'ab' and b <> 'cd' and b <> 'xy' and b is not null; - --- --- different collations for different keys with same expression --- -create table coll_pruning_multi (a text) partition by range (substr(a, 1) collate "POSIX", substr(a, 1) collate "C"); -create table coll_pruning_multi1 partition of coll_pruning_multi for values from ('a', 'a') to ('a', 'e'); -create table coll_pruning_multi2 partition of coll_pruning_multi for values from ('a', 'e') to ('a', 'z'); -create table coll_pruning_multi3 partition of coll_pruning_multi for values from ('b', 'a') to ('b', 'e'); - --- no pruning, because no value for the leading key -explain (costs off) select * from coll_pruning_multi where substr(a, 1) = 'e' collate "C"; - --- pruning, with a value provided for the leading key -explain (costs off) select * from coll_pruning_multi where substr(a, 1) = 'a' collate "POSIX"; - --- pruning, with values provided for both keys -explain (costs off) select * from coll_pruning_multi where substr(a, 1) = 'e' collate "C" and substr(a, 1) = 'a' collate "POSIX"; - --- --- LIKE operators don't prune --- -create table like_op_noprune (a text) partition by list (a); -create table like_op_noprune1 partition of like_op_noprune for values in ('ABC'); -create table like_op_noprune2 partition of like_op_noprune for values in ('BCD'); -explain (costs off) select * from like_op_noprune where a like '%BC'; - --- --- tests wherein clause value requires a cross-type comparison function --- -create table lparted_by_int2 (a smallint) partition by list (a); -create table lparted_by_int2_1 partition of lparted_by_int2 for values in (1); -create table lparted_by_int2_16384 partition of lparted_by_int2 for values in (16384); -explain (costs off) select * from lparted_by_int2 where a = 100000000000000; - -create table rparted_by_int2 (a smallint) partition by range (a); -create table rparted_by_int2_1 partition of rparted_by_int2 for values from (1) to (10); -create table rparted_by_int2_16384 partition of rparted_by_int2 for values from (10) to (16384); --- all partitions pruned -explain (costs off) select * from rparted_by_int2 where a > 100000000000000; -create table rparted_by_int2_maxvalue partition of rparted_by_int2 for values from (16384) to (maxvalue); --- all partitions but rparted_by_int2_maxvalue pruned -explain (costs off) select * from rparted_by_int2 where a > 100000000000000; - -drop table lp, coll_pruning, rlp, mc3p, mc2p, boolpart, boolrangep, rp, coll_pruning_multi, like_op_noprune, lparted_by_int2, rparted_by_int2; - --- --- Test Partition pruning for HASH partitioning --- --- Use hand-rolled hash functions and operator classes to get predictable --- result on different machines. See the definitions of --- part_part_test_int4_ops and part_test_text_ops in insert.sql. --- - -create table hp (a int, b text, c int) - partition by hash (a part_test_int4_ops, b part_test_text_ops); -create table hp0 partition of hp for values with (modulus 4, remainder 0); -create table hp3 partition of hp for values with (modulus 4, remainder 3); -create table hp1 partition of hp for values with (modulus 4, remainder 1); -create table hp2 partition of hp for values with (modulus 4, remainder 2); - -insert into hp values (null, null, 0); -insert into hp values (1, null, 1); -insert into hp values (1, 'xxx', 2); -insert into hp values (null, 'xxx', 3); -insert into hp values (2, 'xxx', 4); -insert into hp values (1, 'abcde', 5); -select tableoid::regclass, * from hp order by c; - --- partial keys won't prune, nor would non-equality conditions -explain (costs off) select * from hp where a = 1; -explain (costs off) select * from hp where b = 'xxx'; -explain (costs off) select * from hp where a is null; -explain (costs off) select * from hp where b is null; -explain (costs off) select * from hp where a < 1 and b = 'xxx'; -explain (costs off) select * from hp where a <> 1 and b = 'yyy'; -explain (costs off) select * from hp where a <> 1 and b <> 'xxx'; - --- pruning should work if either a value or a IS NULL clause is provided for --- each of the keys -explain (costs off) select * from hp where a is null and b is null; -explain (costs off) select * from hp where a = 1 and b is null; -explain (costs off) select * from hp where a = 1 and b = 'xxx'; -explain (costs off) select * from hp where a is null and b = 'xxx'; -explain (costs off) select * from hp where a = 2 and b = 'xxx'; -explain (costs off) select * from hp where a = 1 and b = 'abcde'; -explain (costs off) select * from hp where (a = 1 and b = 'abcde') or (a = 2 and b = 'xxx') or (a is null and b is null); - --- test pruning when not all the partitions exist -drop table hp1; -drop table hp3; -explain (costs off) select * from hp where a = 1 and b = 'abcde'; -explain (costs off) select * from hp where a = 1 and b = 'abcde' and - (c = 2 or c = 3); -drop table hp2; -explain (costs off) select * from hp where a = 1 and b = 'abcde' and - (c = 2 or c = 3); - -drop table hp; - --- --- Test runtime partition pruning --- -create table ab (a int not null, b int not null) partition by list (a); -create table ab_a2 partition of ab for values in(2) partition by list (b); -create table ab_a2_b1 partition of ab_a2 for values in (1); -create table ab_a2_b2 partition of ab_a2 for values in (2); -create table ab_a2_b3 partition of ab_a2 for values in (3); -create table ab_a1 partition of ab for values in(1) partition by list (b); -create table ab_a1_b1 partition of ab_a1 for values in (1); -create table ab_a1_b2 partition of ab_a1 for values in (2); -create table ab_a1_b3 partition of ab_a1 for values in (3); -create table ab_a3 partition of ab for values in(3) partition by list (b); -create table ab_a3_b1 partition of ab_a3 for values in (1); -create table ab_a3_b2 partition of ab_a3 for values in (2); -create table ab_a3_b3 partition of ab_a3 for values in (3); - --- Disallow index only scans as concurrent transactions may stop visibility --- bits being set causing "Heap Fetches" to be unstable in the EXPLAIN ANALYZE --- output. -set enable_indexonlyscan = off; - -prepare ab_q1 (int, int, int) as -select * from ab where a between $1 and $2 and b <= $3; - -explain (analyze, costs off, summary off, timing off) execute ab_q1 (2, 2, 3); -explain (analyze, costs off, summary off, timing off) execute ab_q1 (1, 2, 3); - -deallocate ab_q1; - --- Runtime pruning after optimizer pruning -prepare ab_q1 (int, int) as -select a from ab where a between $1 and $2 and b < 3; - -explain (analyze, costs off, summary off, timing off) execute ab_q1 (2, 2); -explain (analyze, costs off, summary off, timing off) execute ab_q1 (2, 4); - --- Ensure a mix of PARAM_EXTERN and PARAM_EXEC Params work together at --- different levels of partitioning. -prepare ab_q2 (int, int) as -select a from ab where a between $1 and $2 and b < (select 3); - -explain (analyze, costs off, summary off, timing off) execute ab_q2 (2, 2); - --- As above, but swap the PARAM_EXEC Param to the first partition level -prepare ab_q3 (int, int) as -select a from ab where b between $1 and $2 and a < (select 3); - -explain (analyze, costs off, summary off, timing off) execute ab_q3 (2, 2); - --- Test a backwards Append scan -create table list_part (a int) partition by list (a); -create table list_part1 partition of list_part for values in (1); -create table list_part2 partition of list_part for values in (2); -create table list_part3 partition of list_part for values in (3); -create table list_part4 partition of list_part for values in (4); - -insert into list_part select generate_series(1,4); - -begin; - --- Don't select an actual value out of the table as the order of the Append's --- subnodes may not be stable. -declare cur SCROLL CURSOR for select 1 from list_part where a > (select 1) and a < (select 4); - --- move beyond the final row -move 3 from cur; - --- Ensure we get two rows. -fetch backward all from cur; - -commit; - -begin; - --- Test run-time pruning using stable functions -create function list_part_fn(int) returns int as $$ begin return $1; end;$$ language plpgsql stable; - --- Ensure pruning works using a stable function containing no Vars -explain (analyze, costs off, summary off, timing off) select * from list_part where a = list_part_fn(1); - --- Ensure pruning does not take place when the function has a Var parameter -explain (analyze, costs off, summary off, timing off) select * from list_part where a = list_part_fn(a); - --- Ensure pruning does not take place when the expression contains a Var. -explain (analyze, costs off, summary off, timing off) select * from list_part where a = list_part_fn(1) + a; - -rollback; - -drop table list_part; - --- Parallel append - --- Parallel queries won't necessarily get as many workers as the planner --- asked for. This affects not only the "Workers Launched:" field of EXPLAIN --- results, but also row counts and loop counts for parallel scans, Gathers, --- and everything in between. This function filters out the values we can't --- rely on to be stable. --- This removes enough info that you might wonder why bother with EXPLAIN --- ANALYZE at all. The answer is that we need to see '(never executed)' --- notations because that's the only way to verify runtime pruning. -create function explain_parallel_append(text) returns setof text -language plpgsql as -$$ -declare - ln text; -begin - for ln in - execute format('explain (analyze, costs off, summary off, timing off) %s', - $1) - loop - ln := regexp_replace(ln, 'Workers Launched: \d+', 'Workers Launched: N'); - ln := regexp_replace(ln, 'actual rows=\d+ loops=\d+', 'actual rows=N loops=N'); - ln := regexp_replace(ln, 'Rows Removed by Filter: \d+', 'Rows Removed by Filter: N'); - return next ln; - end loop; -end; -$$; - -prepare ab_q4 (int, int) as -select avg(a) from ab where a between $1 and $2 and b < 4; - --- Encourage use of parallel plans -set parallel_setup_cost = 0; -set parallel_tuple_cost = 0; -set min_parallel_table_scan_size = 0; -set max_parallel_workers_per_gather = 2; - -select explain_parallel_append('execute ab_q4 (2, 2)'); - --- Test run-time pruning with IN lists. -prepare ab_q5 (int, int, int) as -select avg(a) from ab where a in($1,$2,$3) and b < 4; - -select explain_parallel_append('execute ab_q5 (1, 1, 1)'); -select explain_parallel_append('execute ab_q5 (2, 3, 3)'); - --- Try some params whose values do not belong to any partition. -select explain_parallel_append('execute ab_q5 (33, 44, 55)'); - --- Test Parallel Append with PARAM_EXEC Params -select explain_parallel_append('select count(*) from ab where (a = (select 1) or a = (select 3)) and b = 2'); - --- Test pruning during parallel nested loop query -create table lprt_a (a int not null); --- Insert some values we won't find in ab -insert into lprt_a select 0 from generate_series(1,100); - --- and insert some values that we should find. -insert into lprt_a values(1),(1); - -analyze lprt_a; - -create index ab_a2_b1_a_idx on ab_a2_b1 (a); -create index ab_a2_b2_a_idx on ab_a2_b2 (a); -create index ab_a2_b3_a_idx on ab_a2_b3 (a); -create index ab_a1_b1_a_idx on ab_a1_b1 (a); -create index ab_a1_b2_a_idx on ab_a1_b2 (a); -create index ab_a1_b3_a_idx on ab_a1_b3 (a); -create index ab_a3_b1_a_idx on ab_a3_b1 (a); -create index ab_a3_b2_a_idx on ab_a3_b2 (a); -create index ab_a3_b3_a_idx on ab_a3_b3 (a); - -set enable_hashjoin = 0; -set enable_mergejoin = 0; -set enable_memoize = 0; - -select explain_parallel_append('select avg(ab.a) from ab inner join lprt_a a on ab.a = a.a where a.a in(0, 0, 1)'); - --- Ensure the same partitions are pruned when we make the nested loop --- parameter an Expr rather than a plain Param. -select explain_parallel_append('select avg(ab.a) from ab inner join lprt_a a on ab.a = a.a + 0 where a.a in(0, 0, 1)'); - -insert into lprt_a values(3),(3); - -select explain_parallel_append('select avg(ab.a) from ab inner join lprt_a a on ab.a = a.a where a.a in(1, 0, 3)'); -select explain_parallel_append('select avg(ab.a) from ab inner join lprt_a a on ab.a = a.a where a.a in(1, 0, 0)'); - -delete from lprt_a where a = 1; - -select explain_parallel_append('select avg(ab.a) from ab inner join lprt_a a on ab.a = a.a where a.a in(1, 0, 0)'); - -reset enable_hashjoin; -reset enable_mergejoin; -reset enable_memoize; -reset parallel_setup_cost; -reset parallel_tuple_cost; -reset min_parallel_table_scan_size; -reset max_parallel_workers_per_gather; - --- Test run-time partition pruning with an initplan -explain (analyze, costs off, summary off, timing off) -select * from ab where a = (select max(a) from lprt_a) and b = (select max(a)-1 from lprt_a); - --- Test run-time partition pruning with UNION ALL parents -explain (analyze, costs off, summary off, timing off) -select * from (select * from ab where a = 1 union all select * from ab) ab where b = (select 1); - --- A case containing a UNION ALL with a non-partitioned child. -explain (analyze, costs off, summary off, timing off) -select * from (select * from ab where a = 1 union all (values(10,5)) union all select * from ab) ab where b = (select 1); - --- Another UNION ALL test, but containing a mix of exec init and exec run-time pruning. -create table xy_1 (x int, y int); -insert into xy_1 values(100,-10); - -set enable_bitmapscan = 0; -set enable_indexscan = 0; - -prepare ab_q6 as -select * from ( - select tableoid::regclass,a,b from ab -union all - select tableoid::regclass,x,y from xy_1 -union all - select tableoid::regclass,a,b from ab -) ab where a = $1 and b = (select -10); - --- Ensure the xy_1 subplan is not pruned. -explain (analyze, costs off, summary off, timing off) execute ab_q6(1); - --- Ensure we see just the xy_1 row. -execute ab_q6(100); - -reset enable_bitmapscan; -reset enable_indexscan; - -deallocate ab_q1; -deallocate ab_q2; -deallocate ab_q3; -deallocate ab_q4; -deallocate ab_q5; -deallocate ab_q6; - --- UPDATE on a partition subtree has been seen to have problems. -insert into ab values (1,2); -explain (analyze, costs off, summary off, timing off) -update ab_a1 set b = 3 from ab where ab.a = 1 and ab.a = ab_a1.a; -table ab; - --- Test UPDATE where source relation has run-time pruning enabled -truncate ab; -insert into ab values (1, 1), (1, 2), (1, 3), (2, 1); -explain (analyze, costs off, summary off, timing off) -update ab_a1 set b = 3 from ab_a2 where ab_a2.b = (select 1); -select tableoid::regclass, * from ab; - -drop table ab, lprt_a; - --- Join -create table tbl1(col1 int); -insert into tbl1 values (501), (505); - --- Basic table -create table tprt (col1 int) partition by range (col1); -create table tprt_1 partition of tprt for values from (1) to (501); -create table tprt_2 partition of tprt for values from (501) to (1001); -create table tprt_3 partition of tprt for values from (1001) to (2001); -create table tprt_4 partition of tprt for values from (2001) to (3001); -create table tprt_5 partition of tprt for values from (3001) to (4001); -create table tprt_6 partition of tprt for values from (4001) to (5001); - -create index tprt1_idx on tprt_1 (col1); -create index tprt2_idx on tprt_2 (col1); -create index tprt3_idx on tprt_3 (col1); -create index tprt4_idx on tprt_4 (col1); -create index tprt5_idx on tprt_5 (col1); -create index tprt6_idx on tprt_6 (col1); - -insert into tprt values (10), (20), (501), (502), (505), (1001), (4500); - -set enable_hashjoin = off; -set enable_mergejoin = off; - -explain (analyze, costs off, summary off, timing off) -select * from tbl1 join tprt on tbl1.col1 > tprt.col1; - -explain (analyze, costs off, summary off, timing off) -select * from tbl1 join tprt on tbl1.col1 = tprt.col1; - -select tbl1.col1, tprt.col1 from tbl1 -inner join tprt on tbl1.col1 > tprt.col1 -order by tbl1.col1, tprt.col1; - -select tbl1.col1, tprt.col1 from tbl1 -inner join tprt on tbl1.col1 = tprt.col1 -order by tbl1.col1, tprt.col1; - --- Multiple partitions -insert into tbl1 values (1001), (1010), (1011); -explain (analyze, costs off, summary off, timing off) -select * from tbl1 inner join tprt on tbl1.col1 > tprt.col1; - -explain (analyze, costs off, summary off, timing off) -select * from tbl1 inner join tprt on tbl1.col1 = tprt.col1; - -select tbl1.col1, tprt.col1 from tbl1 -inner join tprt on tbl1.col1 > tprt.col1 -order by tbl1.col1, tprt.col1; - -select tbl1.col1, tprt.col1 from tbl1 -inner join tprt on tbl1.col1 = tprt.col1 -order by tbl1.col1, tprt.col1; - --- Last partition -delete from tbl1; -insert into tbl1 values (4400); -explain (analyze, costs off, summary off, timing off) -select * from tbl1 join tprt on tbl1.col1 < tprt.col1; - -select tbl1.col1, tprt.col1 from tbl1 -inner join tprt on tbl1.col1 < tprt.col1 -order by tbl1.col1, tprt.col1; - --- No matching partition -delete from tbl1; -insert into tbl1 values (10000); -explain (analyze, costs off, summary off, timing off) -select * from tbl1 join tprt on tbl1.col1 = tprt.col1; - -select tbl1.col1, tprt.col1 from tbl1 -inner join tprt on tbl1.col1 = tprt.col1 -order by tbl1.col1, tprt.col1; - -drop table tbl1, tprt; - --- Test with columns defined in varying orders between each level -create table part_abc (a int not null, b int not null, c int not null) partition by list (a); -create table part_bac (b int not null, a int not null, c int not null) partition by list (b); -create table part_cab (c int not null, a int not null, b int not null) partition by list (c); -create table part_abc_p1 (a int not null, b int not null, c int not null); - -alter table part_abc attach partition part_bac for values in(1); -alter table part_bac attach partition part_cab for values in(2); -alter table part_cab attach partition part_abc_p1 for values in(3); - -prepare part_abc_q1 (int, int, int) as -select * from part_abc where a = $1 and b = $2 and c = $3; - --- Single partition should be scanned. -explain (analyze, costs off, summary off, timing off) execute part_abc_q1 (1, 2, 3); - -deallocate part_abc_q1; - -drop table part_abc; - --- Ensure that an Append node properly handles a sub-partitioned table --- matching without any of its leaf partitions matching the clause. -create table listp (a int, b int) partition by list (a); -create table listp_1 partition of listp for values in(1) partition by list (b); -create table listp_1_1 partition of listp_1 for values in(1); -create table listp_2 partition of listp for values in(2) partition by list (b); -create table listp_2_1 partition of listp_2 for values in(2); -select * from listp where b = 1; - --- Ensure that an Append node properly can handle selection of all first level --- partitions before finally detecting the correct set of 2nd level partitions --- which match the given parameter. -prepare q1 (int,int) as select * from listp where b in ($1,$2); - -explain (analyze, costs off, summary off, timing off) execute q1 (1,1); - -explain (analyze, costs off, summary off, timing off) execute q1 (2,2); - --- Try with no matching partitions. -explain (analyze, costs off, summary off, timing off) execute q1 (0,0); - -deallocate q1; - --- Test more complex cases where a not-equal condition further eliminates partitions. -prepare q1 (int,int,int,int) as select * from listp where b in($1,$2) and $3 <> b and $4 <> b; - --- Both partitions allowed by IN clause, but one disallowed by <> clause -explain (analyze, costs off, summary off, timing off) execute q1 (1,2,2,0); - --- Both partitions allowed by IN clause, then both excluded again by <> clauses. -explain (analyze, costs off, summary off, timing off) execute q1 (1,2,2,1); - --- Ensure Params that evaluate to NULL properly prune away all partitions -explain (analyze, costs off, summary off, timing off) -select * from listp where a = (select null::int); - -drop table listp; - --- --- check that stable query clauses are only used in run-time pruning --- -create table stable_qual_pruning (a timestamp) partition by range (a); -create table stable_qual_pruning1 partition of stable_qual_pruning - for values from ('2000-01-01') to ('2000-02-01'); -create table stable_qual_pruning2 partition of stable_qual_pruning - for values from ('2000-02-01') to ('2000-03-01'); -create table stable_qual_pruning3 partition of stable_qual_pruning - for values from ('3000-02-01') to ('3000-03-01'); - --- comparison against a stable value requires run-time pruning -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning where a < localtimestamp; - --- timestamp < timestamptz comparison is only stable, not immutable -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning where a < '2000-02-01'::timestamptz; - --- check ScalarArrayOp cases -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning - where a = any(array['2010-02-01', '2020-01-01']::timestamp[]); -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning - where a = any(array['2000-02-01', '2010-01-01']::timestamp[]); -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning - where a = any(array['2000-02-01', localtimestamp]::timestamp[]); -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning - where a = any(array['2010-02-01', '2020-01-01']::timestamptz[]); -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning - where a = any(array['2000-02-01', '2010-01-01']::timestamptz[]); -explain (analyze, costs off, summary off, timing off) -select * from stable_qual_pruning - where a = any(null::timestamptz[]); - -drop table stable_qual_pruning; - --- --- Check that pruning with composite range partitioning works correctly when --- it must ignore clauses for trailing keys once it has seen a clause with --- non-inclusive operator for an earlier key --- -create table mc3p (a int, b int, c int) partition by range (a, abs(b), c); -create table mc3p0 partition of mc3p - for values from (0, 0, 0) to (0, maxvalue, maxvalue); -create table mc3p1 partition of mc3p - for values from (1, 1, 1) to (2, minvalue, minvalue); -create table mc3p2 partition of mc3p - for values from (2, minvalue, minvalue) to (3, maxvalue, maxvalue); -insert into mc3p values (0, 1, 1), (1, 1, 1), (2, 1, 1); - -explain (analyze, costs off, summary off, timing off) -select * from mc3p where a < 3 and abs(b) = 1; - --- --- Check that pruning with composite range partitioning works correctly when --- a combination of runtime parameters is specified, not all of whose values --- are available at the same time --- -prepare ps1 as - select * from mc3p where a = $1 and abs(b) < (select 3); -explain (analyze, costs off, summary off, timing off) -execute ps1(1); -deallocate ps1; -prepare ps2 as - select * from mc3p where a <= $1 and abs(b) < (select 3); -explain (analyze, costs off, summary off, timing off) -execute ps2(1); -deallocate ps2; - -drop table mc3p; - --- Ensure runtime pruning works with initplans params with boolean types -create table boolvalues (value bool not null); -insert into boolvalues values('t'),('f'); - -create table boolp (a bool) partition by list (a); -create table boolp_t partition of boolp for values in('t'); -create table boolp_f partition of boolp for values in('f'); - -explain (analyze, costs off, summary off, timing off) -select * from boolp where a = (select value from boolvalues where value); - -explain (analyze, costs off, summary off, timing off) -select * from boolp where a = (select value from boolvalues where not value); - -drop table boolp; - --- --- Test run-time pruning of MergeAppend subnodes --- -set enable_seqscan = off; -set enable_sort = off; -create table ma_test (a int, b int) partition by range (a); -create table ma_test_p1 partition of ma_test for values from (0) to (10); -create table ma_test_p2 partition of ma_test for values from (10) to (20); -create table ma_test_p3 partition of ma_test for values from (20) to (30); -insert into ma_test select x,x from generate_series(0,29) t(x); -create index on ma_test (b); - -analyze ma_test; -prepare mt_q1 (int) as select a from ma_test where a >= $1 and a % 10 = 5 order by b; - -explain (analyze, costs off, summary off, timing off) execute mt_q1(15); -execute mt_q1(15); -explain (analyze, costs off, summary off, timing off) execute mt_q1(25); -execute mt_q1(25); --- Ensure MergeAppend behaves correctly when no subplans match -explain (analyze, costs off, summary off, timing off) execute mt_q1(35); -execute mt_q1(35); - -deallocate mt_q1; - -prepare mt_q2 (int) as select * from ma_test where a >= $1 order by b limit 1; - --- Ensure output list looks sane when the MergeAppend has no subplans. -explain (analyze, verbose, costs off, summary off, timing off) execute mt_q2 (35); - -deallocate mt_q2; - --- ensure initplan params properly prune partitions -explain (analyze, costs off, summary off, timing off) select * from ma_test where a >= (select min(b) from ma_test_p2) order by b; - -reset enable_seqscan; -reset enable_sort; - -drop table ma_test; - -reset enable_indexonlyscan; - --- --- check that pruning works properly when the partition key is of a --- pseudotype --- - --- array type list partition key -create table pp_arrpart (a int[]) partition by list (a); -create table pp_arrpart1 partition of pp_arrpart for values in ('{1}'); -create table pp_arrpart2 partition of pp_arrpart for values in ('{2, 3}', '{4, 5}'); -explain (costs off) select * from pp_arrpart where a = '{1}'; -explain (costs off) select * from pp_arrpart where a = '{1, 2}'; -explain (costs off) select * from pp_arrpart where a in ('{4, 5}', '{1}'); -explain (costs off) update pp_arrpart set a = a where a = '{1}'; -explain (costs off) delete from pp_arrpart where a = '{1}'; -drop table pp_arrpart; - --- array type hash partition key -create table pph_arrpart (a int[]) partition by hash (a); -create table pph_arrpart1 partition of pph_arrpart for values with (modulus 2, remainder 0); -create table pph_arrpart2 partition of pph_arrpart for values with (modulus 2, remainder 1); -insert into pph_arrpart values ('{1}'), ('{1, 2}'), ('{4, 5}'); -select tableoid::regclass, * from pph_arrpart order by 1; -explain (costs off) select * from pph_arrpart where a = '{1}'; -explain (costs off) select * from pph_arrpart where a = '{1, 2}'; -explain (costs off) select * from pph_arrpart where a in ('{4, 5}', '{1}'); -drop table pph_arrpart; - --- enum type list partition key -create type pp_colors as enum ('green', 'blue', 'black'); -create table pp_enumpart (a pp_colors) partition by list (a); -create table pp_enumpart_green partition of pp_enumpart for values in ('green'); -create table pp_enumpart_blue partition of pp_enumpart for values in ('blue'); -explain (costs off) select * from pp_enumpart where a = 'blue'; -explain (costs off) select * from pp_enumpart where a = 'black'; -drop table pp_enumpart; -drop type pp_colors; - --- record type as partition key -create type pp_rectype as (a int, b int); -create table pp_recpart (a pp_rectype) partition by list (a); -create table pp_recpart_11 partition of pp_recpart for values in ('(1,1)'); -create table pp_recpart_23 partition of pp_recpart for values in ('(2,3)'); -explain (costs off) select * from pp_recpart where a = '(1,1)'::pp_rectype; -explain (costs off) select * from pp_recpart where a = '(1,2)'::pp_rectype; -drop table pp_recpart; -drop type pp_rectype; - --- range type partition key -create table pp_intrangepart (a int4range) partition by list (a); -create table pp_intrangepart12 partition of pp_intrangepart for values in ('[1,2]'); -create table pp_intrangepart2inf partition of pp_intrangepart for values in ('[2,)'); -explain (costs off) select * from pp_intrangepart where a = '[1,2]'::int4range; -explain (costs off) select * from pp_intrangepart where a = '(1,2)'::int4range; -drop table pp_intrangepart; - --- --- Ensure the enable_partition_prune GUC properly disables partition pruning. --- - -create table pp_lp (a int, value int) partition by list (a); -create table pp_lp1 partition of pp_lp for values in(1); -create table pp_lp2 partition of pp_lp for values in(2); - -explain (costs off) select * from pp_lp where a = 1; -explain (costs off) update pp_lp set value = 10 where a = 1; -explain (costs off) delete from pp_lp where a = 1; - -set enable_partition_pruning = off; - -set constraint_exclusion = 'partition'; -- this should not affect the result. - -explain (costs off) select * from pp_lp where a = 1; -explain (costs off) update pp_lp set value = 10 where a = 1; -explain (costs off) delete from pp_lp where a = 1; - -set constraint_exclusion = 'off'; -- this should not affect the result. - -explain (costs off) select * from pp_lp where a = 1; -explain (costs off) update pp_lp set value = 10 where a = 1; -explain (costs off) delete from pp_lp where a = 1; - -drop table pp_lp; - --- Ensure enable_partition_prune does not affect non-partitioned tables. - -create table inh_lp (a int, value int); -create table inh_lp1 (a int, value int, check(a = 1)) inherits (inh_lp); -create table inh_lp2 (a int, value int, check(a = 2)) inherits (inh_lp); - -set constraint_exclusion = 'partition'; - --- inh_lp2 should be removed in the following 3 cases. -explain (costs off) select * from inh_lp where a = 1; -explain (costs off) update inh_lp set value = 10 where a = 1; -explain (costs off) delete from inh_lp where a = 1; - --- Ensure we don't exclude normal relations when we only expect to exclude --- inheritance children -explain (costs off) update inh_lp1 set value = 10 where a = 2; - -drop table inh_lp cascade; - -reset enable_partition_pruning; -reset constraint_exclusion; - --- Check pruning for a partition tree containing only temporary relations -create temp table pp_temp_parent (a int) partition by list (a); -create temp table pp_temp_part_1 partition of pp_temp_parent for values in (1); -create temp table pp_temp_part_def partition of pp_temp_parent default; -explain (costs off) select * from pp_temp_parent where true; -explain (costs off) select * from pp_temp_parent where a = 2; -drop table pp_temp_parent; - --- Stress run-time partition pruning a bit more, per bug reports -create temp table p (a int, b int, c int) partition by list (a); -create temp table p1 partition of p for values in (1); -create temp table p2 partition of p for values in (2); -create temp table q (a int, b int, c int) partition by list (a); -create temp table q1 partition of q for values in (1) partition by list (b); -create temp table q11 partition of q1 for values in (1) partition by list (c); -create temp table q111 partition of q11 for values in (1); -create temp table q2 partition of q for values in (2) partition by list (b); -create temp table q21 partition of q2 for values in (1); -create temp table q22 partition of q2 for values in (2); - -insert into q22 values (2, 2, 3); - -explain (costs off) -select * -from ( - select * from p - union all - select * from q1 - union all - select 1, 1, 1 - ) s(a, b, c) -where s.a = 1 and s.b = 1 and s.c = (select 1); - -select * -from ( - select * from p - union all - select * from q1 - union all - select 1, 1, 1 - ) s(a, b, c) -where s.a = 1 and s.b = 1 and s.c = (select 1); - -prepare q (int, int) as -select * -from ( - select * from p - union all - select * from q1 - union all - select 1, 1, 1 - ) s(a, b, c) -where s.a = $1 and s.b = $2 and s.c = (select 1); - -explain (costs off) execute q (1, 1); -execute q (1, 1); - -drop table p, q; - --- Ensure run-time pruning works correctly when we match a partitioned table --- on the first level but find no matching partitions on the second level. -create table listp (a int, b int) partition by list (a); -create table listp1 partition of listp for values in(1); -create table listp2 partition of listp for values in(2) partition by list(b); -create table listp2_10 partition of listp2 for values in (10); - -explain (analyze, costs off, summary off, timing off) -select * from listp where a = (select 2) and b <> 10; - --- --- check that a partition directly accessed in a query is excluded with --- constraint_exclusion = on --- - --- turn off partition pruning, so that it doesn't interfere -set enable_partition_pruning to off; - --- setting constraint_exclusion to 'partition' disables exclusion -set constraint_exclusion to 'partition'; -explain (costs off) select * from listp1 where a = 2; -explain (costs off) update listp1 set a = 1 where a = 2; --- constraint exclusion enabled -set constraint_exclusion to 'on'; -explain (costs off) select * from listp1 where a = 2; -explain (costs off) update listp1 set a = 1 where a = 2; - -reset constraint_exclusion; -reset enable_partition_pruning; - -drop table listp; - --- Ensure run-time pruning works correctly for nested Append nodes -set parallel_setup_cost to 0; -set parallel_tuple_cost to 0; - -create table listp (a int) partition by list(a); -create table listp_12 partition of listp for values in(1,2) partition by list(a); -create table listp_12_1 partition of listp_12 for values in(1); -create table listp_12_2 partition of listp_12 for values in(2); - --- Force the 2nd subnode of the Append to be non-parallel. This results in --- a nested Append node because the mixed parallel / non-parallel paths cannot --- be pulled into the top-level Append. -alter table listp_12_1 set (parallel_workers = 0); - --- Ensure that listp_12_2 is not scanned. (The nested Append is not seen in --- the plan as it's pulled in setref.c due to having just a single subnode). -select explain_parallel_append('select * from listp where a = (select 1);'); - --- Like the above but throw some more complexity at the planner by adding --- a UNION ALL. We expect both sides of the union not to scan the --- non-required partitions. -select explain_parallel_append( -'select * from listp where a = (select 1) - union all -select * from listp where a = (select 2);'); - -drop table listp; -reset parallel_tuple_cost; -reset parallel_setup_cost; - --- Test case for run-time pruning with a nested Merge Append -set enable_sort to 0; -create table rangep (a int, b int) partition by range (a); -create table rangep_0_to_100 partition of rangep for values from (0) to (100) partition by list (b); --- We need 3 sub-partitions. 1 to validate pruning worked and another two --- because a single remaining partition would be pulled up to the main Append. -create table rangep_0_to_100_1 partition of rangep_0_to_100 for values in(1); -create table rangep_0_to_100_2 partition of rangep_0_to_100 for values in(2); -create table rangep_0_to_100_3 partition of rangep_0_to_100 for values in(3); -create table rangep_100_to_200 partition of rangep for values from (100) to (200); -create index on rangep (a); - --- Ensure run-time pruning works on the nested Merge Append -explain (analyze on, costs off, timing off, summary off) -select * from rangep where b IN((select 1),(select 2)) order by a; -reset enable_sort; -drop table rangep; - --- --- Check that gen_prune_steps_from_opexps() works well for various cases of --- clauses for different partition keys --- - -create table rp_prefix_test1 (a int, b varchar) partition by range(a, b); -create table rp_prefix_test1_p1 partition of rp_prefix_test1 for values from (1, 'a') to (1, 'b'); -create table rp_prefix_test1_p2 partition of rp_prefix_test1 for values from (2, 'a') to (2, 'b'); - --- Don't call get_steps_using_prefix() with the last partition key b plus --- an empty prefix -explain (costs off) select * from rp_prefix_test1 where a <= 1 and b = 'a'; - -create table rp_prefix_test2 (a int, b int, c int) partition by range(a, b, c); -create table rp_prefix_test2_p1 partition of rp_prefix_test2 for values from (1, 1, 0) to (1, 1, 10); -create table rp_prefix_test2_p2 partition of rp_prefix_test2 for values from (2, 2, 0) to (2, 2, 10); - --- Don't call get_steps_using_prefix() with the last partition key c plus --- an invalid prefix (ie, b = 1) -explain (costs off) select * from rp_prefix_test2 where a <= 1 and b = 1 and c >= 0; - -create table rp_prefix_test3 (a int, b int, c int, d int) partition by range(a, b, c, d); -create table rp_prefix_test3_p1 partition of rp_prefix_test3 for values from (1, 1, 1, 0) to (1, 1, 1, 10); -create table rp_prefix_test3_p2 partition of rp_prefix_test3 for values from (2, 2, 2, 0) to (2, 2, 2, 10); - --- Test that get_steps_using_prefix() handles a prefix that contains multiple --- clauses for the partition key b (ie, b >= 1 and b >= 2) -explain (costs off) select * from rp_prefix_test3 where a >= 1 and b >= 1 and b >= 2 and c >= 2 and d >= 0; - --- Test that get_steps_using_prefix() handles a prefix that contains multiple --- clauses for the partition key b (ie, b >= 1 and b = 2) (This also tests --- that the caller arranges clauses in that prefix in the required order) -explain (costs off) select * from rp_prefix_test3 where a >= 1 and b >= 1 and b = 2 and c = 2 and d >= 0; - -create table hp_prefix_test (a int, b int, c int, d int) partition by hash (a part_test_int4_ops, b part_test_int4_ops, c part_test_int4_ops, d part_test_int4_ops); -create table hp_prefix_test_p1 partition of hp_prefix_test for values with (modulus 2, remainder 0); -create table hp_prefix_test_p2 partition of hp_prefix_test for values with (modulus 2, remainder 1); - --- Test that get_steps_using_prefix() handles non-NULL step_nullkeys -explain (costs off) select * from hp_prefix_test where a = 1 and b is null and c = 1 and d = 1; - -drop table rp_prefix_test1; -drop table rp_prefix_test2; -drop table rp_prefix_test3; -drop table hp_prefix_test; - --- --- Check that gen_partprune_steps() detects self-contradiction from clauses --- regardless of the order of the clauses (Here we use a custom operator to --- prevent the equivclass.c machinery from reordering the clauses) --- - -create operator === ( - leftarg = int4, - rightarg = int4, - procedure = int4eq, - commutator = ===, - hashes -); -create operator class part_test_int4_ops2 -for type int4 -using hash as -operator 1 ===, -function 2 part_hashint4_noop(int4, int8); - -create table hp_contradict_test (a int, b int) partition by hash (a part_test_int4_ops2, b part_test_int4_ops2); -create table hp_contradict_test_p1 partition of hp_contradict_test for values with (modulus 2, remainder 0); -create table hp_contradict_test_p2 partition of hp_contradict_test for values with (modulus 2, remainder 1); - -explain (costs off) select * from hp_contradict_test where a is null and a === 1 and b === 1; -explain (costs off) select * from hp_contradict_test where a === 1 and b === 1 and a is null; - -drop table hp_contradict_test; -drop operator class part_test_int4_ops2 using hash; -drop operator ===(int4, int4); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fplancache.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fplancache.sql deleted file mode 100644 index 4b2f11dcc6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fplancache.sql +++ /dev/null @@ -1,225 +0,0 @@ --- --- Tests to exercise the plan caching/invalidation mechanism --- - -CREATE TEMP TABLE pcachetest AS SELECT * FROM int8_tbl; - --- create and use a cached plan -PREPARE prepstmt AS SELECT * FROM pcachetest; - -EXECUTE prepstmt; - --- and one with parameters -PREPARE prepstmt2(bigint) AS SELECT * FROM pcachetest WHERE q1 = $1; - -EXECUTE prepstmt2(123); - --- invalidate the plans and see what happens -DROP TABLE pcachetest; - -EXECUTE prepstmt; -EXECUTE prepstmt2(123); - --- recreate the temp table (this demonstrates that the raw plan is --- purely textual and doesn't depend on OIDs, for instance) -CREATE TEMP TABLE pcachetest AS SELECT * FROM int8_tbl ORDER BY 2; - -EXECUTE prepstmt; -EXECUTE prepstmt2(123); - --- prepared statements should prevent change in output tupdesc, --- since clients probably aren't expecting that to change on the fly -ALTER TABLE pcachetest ADD COLUMN q3 bigint; - -EXECUTE prepstmt; -EXECUTE prepstmt2(123); - --- but we're nice guys and will let you undo your mistake -ALTER TABLE pcachetest DROP COLUMN q3; - -EXECUTE prepstmt; -EXECUTE prepstmt2(123); - --- Try it with a view, which isn't directly used in the resulting plan --- but should trigger invalidation anyway -CREATE TEMP VIEW pcacheview AS - SELECT * FROM pcachetest; - -PREPARE vprep AS SELECT * FROM pcacheview; - -EXECUTE vprep; - -CREATE OR REPLACE TEMP VIEW pcacheview AS - SELECT q1, q2/2 AS q2 FROM pcachetest; - -EXECUTE vprep; - --- Check basic SPI plan invalidation - -create function cache_test(int) returns int as $$ -declare total int; -begin - create temp table t1(f1 int); - insert into t1 values($1); - insert into t1 values(11); - insert into t1 values(12); - insert into t1 values(13); - select sum(f1) into total from t1; - drop table t1; - return total; -end -$$ language plpgsql; - -select cache_test(1); -select cache_test(2); -select cache_test(3); - --- Check invalidation of plpgsql "simple expression" - -create temp view v1 as - select 2+2 as f1; - -create function cache_test_2() returns int as $$ -begin - return f1 from v1; -end$$ language plpgsql; - -select cache_test_2(); - -create or replace temp view v1 as - select 2+2+4 as f1; -select cache_test_2(); - -create or replace temp view v1 as - select 2+2+4+(select max(unique1) from tenk1) as f1; -select cache_test_2(); - ---- Check that change of search_path is honored when re-using cached plan - -create schema s1 - create table abc (f1 int); - -create schema s2 - create table abc (f1 int); - -insert into s1.abc values(123); -insert into s2.abc values(456); - -set search_path = s1; - -prepare p1 as select f1 from abc; - -execute p1; - -set search_path = s2; - -select f1 from abc; - -execute p1; - -alter table s1.abc add column f2 float8; -- force replan - -execute p1; - -drop schema s1 cascade; -drop schema s2 cascade; - -reset search_path; - --- Check that invalidation deals with regclass constants - -create temp sequence seq; - -prepare p2 as select nextval('seq'); - -execute p2; - -drop sequence seq; - -create temp sequence seq; - -execute p2; - --- Check DDL via SPI, immediately followed by SPI plan re-use --- (bug in original coding) - -create function cachebug() returns void as $$ -declare r int; -begin - drop table if exists temptable cascade; - create temp table temptable as select * from generate_series(1,3) as f1; - create temp view vv as select * from temptable; - for r in select * from vv loop - raise notice '%', r; - end loop; -end$$ language plpgsql; - -select cachebug(); -select cachebug(); - --- Check that addition or removal of any partition is correctly dealt with by --- default partition table when it is being used in prepared statement. -create table pc_list_parted (a int) partition by list(a); -create table pc_list_part_null partition of pc_list_parted for values in (null); -create table pc_list_part_1 partition of pc_list_parted for values in (1); -create table pc_list_part_def partition of pc_list_parted default; -prepare pstmt_def_insert (int) as insert into pc_list_part_def values($1); --- should fail -execute pstmt_def_insert(null); -execute pstmt_def_insert(1); -create table pc_list_part_2 partition of pc_list_parted for values in (2); -execute pstmt_def_insert(2); -alter table pc_list_parted detach partition pc_list_part_null; --- should be ok -execute pstmt_def_insert(null); -drop table pc_list_part_1; --- should be ok -execute pstmt_def_insert(1); -drop table pc_list_parted, pc_list_part_null; -deallocate pstmt_def_insert; - --- Test plan_cache_mode - -create table test_mode (a int); -insert into test_mode select 1 from generate_series(1,1000) union all select 2; -create index on test_mode (a); -analyze test_mode; - -prepare test_mode_pp (int) as select count(*) from test_mode where a = $1; -select name, generic_plans, custom_plans from pg_prepared_statements - where name = 'test_mode_pp'; - --- up to 5 executions, custom plan is used -set plan_cache_mode to auto; -explain (costs off) execute test_mode_pp(2); -select name, generic_plans, custom_plans from pg_prepared_statements - where name = 'test_mode_pp'; - --- force generic plan -set plan_cache_mode to force_generic_plan; -explain (costs off) execute test_mode_pp(2); -select name, generic_plans, custom_plans from pg_prepared_statements - where name = 'test_mode_pp'; - --- get to generic plan by 5 executions -set plan_cache_mode to auto; -execute test_mode_pp(1); -- 1x -execute test_mode_pp(1); -- 2x -execute test_mode_pp(1); -- 3x -execute test_mode_pp(1); -- 4x -select name, generic_plans, custom_plans from pg_prepared_statements - where name = 'test_mode_pp'; -execute test_mode_pp(1); -- 5x -select name, generic_plans, custom_plans from pg_prepared_statements - where name = 'test_mode_pp'; - --- we should now get a really bad plan -explain (costs off) execute test_mode_pp(2); - --- but we can force a custom plan -set plan_cache_mode to force_custom_plan; -explain (costs off) execute test_mode_pp(2); -select name, generic_plans, custom_plans from pg_prepared_statements - where name = 'test_mode_pp'; - -drop table test_mode; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fplpgsql.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fplpgsql.sql deleted file mode 100644 index 588c331033..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fplpgsql.sql +++ /dev/null @@ -1,4713 +0,0 @@ --- --- PLPGSQL --- --- Scenario: --- --- A building with a modern TP cable installation where any --- of the wall connectors can be used to plug in phones, --- ethernet interfaces or local office hubs. The backside --- of the wall connectors is wired to one of several patch- --- fields in the building. --- --- In the patchfields, there are hubs and all the slots --- representing the wall connectors. In addition there are --- slots that can represent a phone line from the central --- phone system. --- --- Triggers ensure consistency of the patching information. --- --- Functions are used to build up powerful views that let --- you look behind the wall when looking at a patchfield --- or into a room. --- - - -create table Room ( - roomno char(8), - comment text -); - -create unique index Room_rno on Room using btree (roomno bpchar_ops); - - -create table WSlot ( - slotname char(20), - roomno char(8), - slotlink char(20), - backlink char(20) -); - -create unique index WSlot_name on WSlot using btree (slotname bpchar_ops); - - -create table PField ( - name text, - comment text -); - -create unique index PField_name on PField using btree (name text_ops); - - -create table PSlot ( - slotname char(20), - pfname text, - slotlink char(20), - backlink char(20) -); - -create unique index PSlot_name on PSlot using btree (slotname bpchar_ops); - - -create table PLine ( - slotname char(20), - phonenumber char(20), - comment text, - backlink char(20) -); - -create unique index PLine_name on PLine using btree (slotname bpchar_ops); - - -create table Hub ( - name char(14), - comment text, - nslots integer -); - -create unique index Hub_name on Hub using btree (name bpchar_ops); - - -create table HSlot ( - slotname char(20), - hubname char(14), - slotno integer, - slotlink char(20) -); - -create unique index HSlot_name on HSlot using btree (slotname bpchar_ops); -create index HSlot_hubname on HSlot using btree (hubname bpchar_ops); - - -create table System ( - name text, - comment text -); - -create unique index System_name on System using btree (name text_ops); - - -create table IFace ( - slotname char(20), - sysname text, - ifname text, - slotlink char(20) -); - -create unique index IFace_name on IFace using btree (slotname bpchar_ops); - - -create table PHone ( - slotname char(20), - comment text, - slotlink char(20) -); - -create unique index PHone_name on PHone using btree (slotname bpchar_ops); - - --- ************************************************************ --- * --- * Trigger procedures and functions for the patchfield --- * test of PL/pgSQL --- * --- ************************************************************ - - --- ************************************************************ --- * AFTER UPDATE on Room --- * - If room no changes let wall slots follow --- ************************************************************ -create function tg_room_au() returns trigger as ' -begin - if new.roomno != old.roomno then - update WSlot set roomno = new.roomno where roomno = old.roomno; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_room_au after update - on Room for each row execute procedure tg_room_au(); - - --- ************************************************************ --- * AFTER DELETE on Room --- * - delete wall slots in this room --- ************************************************************ -create function tg_room_ad() returns trigger as ' -begin - delete from WSlot where roomno = old.roomno; - return old; -end; -' language plpgsql; - -create trigger tg_room_ad after delete - on Room for each row execute procedure tg_room_ad(); - - --- ************************************************************ --- * BEFORE INSERT or UPDATE on WSlot --- * - Check that room exists --- ************************************************************ -create function tg_wslot_biu() returns trigger as $$ -begin - if count(*) = 0 from Room where roomno = new.roomno then - raise exception 'Room % does not exist', new.roomno; - end if; - return new; -end; -$$ language plpgsql; - -create trigger tg_wslot_biu before insert or update - on WSlot for each row execute procedure tg_wslot_biu(); - - --- ************************************************************ --- * AFTER UPDATE on PField --- * - Let PSlots of this field follow --- ************************************************************ -create function tg_pfield_au() returns trigger as ' -begin - if new.name != old.name then - update PSlot set pfname = new.name where pfname = old.name; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_pfield_au after update - on PField for each row execute procedure tg_pfield_au(); - - --- ************************************************************ --- * AFTER DELETE on PField --- * - Remove all slots of this patchfield --- ************************************************************ -create function tg_pfield_ad() returns trigger as ' -begin - delete from PSlot where pfname = old.name; - return old; -end; -' language plpgsql; - -create trigger tg_pfield_ad after delete - on PField for each row execute procedure tg_pfield_ad(); - - --- ************************************************************ --- * BEFORE INSERT or UPDATE on PSlot --- * - Ensure that our patchfield does exist --- ************************************************************ -create function tg_pslot_biu() returns trigger as $proc$ -declare - pfrec record; - ps alias for new; -begin - select into pfrec * from PField where name = ps.pfname; - if not found then - raise exception $$Patchfield "%" does not exist$$, ps.pfname; - end if; - return ps; -end; -$proc$ language plpgsql; - -create trigger tg_pslot_biu before insert or update - on PSlot for each row execute procedure tg_pslot_biu(); - - --- ************************************************************ --- * AFTER UPDATE on System --- * - If system name changes let interfaces follow --- ************************************************************ -create function tg_system_au() returns trigger as ' -begin - if new.name != old.name then - update IFace set sysname = new.name where sysname = old.name; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_system_au after update - on System for each row execute procedure tg_system_au(); - - --- ************************************************************ --- * BEFORE INSERT or UPDATE on IFace --- * - set the slotname to IF.sysname.ifname --- ************************************************************ -create function tg_iface_biu() returns trigger as $$ -declare - sname text; - sysrec record; -begin - select into sysrec * from system where name = new.sysname; - if not found then - raise exception $q$system "%" does not exist$q$, new.sysname; - end if; - sname := 'IF.' || new.sysname; - sname := sname || '.'; - sname := sname || new.ifname; - if length(sname) > 20 then - raise exception 'IFace slotname "%" too long (20 char max)', sname; - end if; - new.slotname := sname; - return new; -end; -$$ language plpgsql; - -create trigger tg_iface_biu before insert or update - on IFace for each row execute procedure tg_iface_biu(); - - --- ************************************************************ --- * AFTER INSERT or UPDATE or DELETE on Hub --- * - insert/delete/rename slots as required --- ************************************************************ -create function tg_hub_a() returns trigger as ' -declare - hname text; - dummy integer; -begin - if tg_op = ''INSERT'' then - dummy := tg_hub_adjustslots(new.name, 0, new.nslots); - return new; - end if; - if tg_op = ''UPDATE'' then - if new.name != old.name then - update HSlot set hubname = new.name where hubname = old.name; - end if; - dummy := tg_hub_adjustslots(new.name, old.nslots, new.nslots); - return new; - end if; - if tg_op = ''DELETE'' then - dummy := tg_hub_adjustslots(old.name, old.nslots, 0); - return old; - end if; -end; -' language plpgsql; - -create trigger tg_hub_a after insert or update or delete - on Hub for each row execute procedure tg_hub_a(); - - --- ************************************************************ --- * Support function to add/remove slots of Hub --- ************************************************************ -create function tg_hub_adjustslots(hname bpchar, - oldnslots integer, - newnslots integer) -returns integer as ' -begin - if newnslots = oldnslots then - return 0; - end if; - if newnslots < oldnslots then - delete from HSlot where hubname = hname and slotno > newnslots; - return 0; - end if; - for i in oldnslots + 1 .. newnslots loop - insert into HSlot (slotname, hubname, slotno, slotlink) - values (''HS.dummy'', hname, i, ''''); - end loop; - return 0; -end -' language plpgsql; - --- Test comments -COMMENT ON FUNCTION tg_hub_adjustslots_wrong(bpchar, integer, integer) IS 'function with args'; -COMMENT ON FUNCTION tg_hub_adjustslots(bpchar, integer, integer) IS 'function with args'; -COMMENT ON FUNCTION tg_hub_adjustslots(bpchar, integer, integer) IS NULL; - --- ************************************************************ --- * BEFORE INSERT or UPDATE on HSlot --- * - prevent from manual manipulation --- * - set the slotname to HS.hubname.slotno --- ************************************************************ -create function tg_hslot_biu() returns trigger as ' -declare - sname text; - xname HSlot.slotname%TYPE; - hubrec record; -begin - select into hubrec * from Hub where name = new.hubname; - if not found then - raise exception ''no manual manipulation of HSlot''; - end if; - if new.slotno < 1 or new.slotno > hubrec.nslots then - raise exception ''no manual manipulation of HSlot''; - end if; - if tg_op = ''UPDATE'' and new.hubname != old.hubname then - if count(*) > 0 from Hub where name = old.hubname then - raise exception ''no manual manipulation of HSlot''; - end if; - end if; - sname := ''HS.'' || trim(new.hubname); - sname := sname || ''.''; - sname := sname || new.slotno::text; - if length(sname) > 20 then - raise exception ''HSlot slotname "%" too long (20 char max)'', sname; - end if; - new.slotname := sname; - return new; -end; -' language plpgsql; - -create trigger tg_hslot_biu before insert or update - on HSlot for each row execute procedure tg_hslot_biu(); - - --- ************************************************************ --- * BEFORE DELETE on HSlot --- * - prevent from manual manipulation --- ************************************************************ -create function tg_hslot_bd() returns trigger as ' -declare - hubrec record; -begin - select into hubrec * from Hub where name = old.hubname; - if not found then - return old; - end if; - if old.slotno > hubrec.nslots then - return old; - end if; - raise exception ''no manual manipulation of HSlot''; -end; -' language plpgsql; - -create trigger tg_hslot_bd before delete - on HSlot for each row execute procedure tg_hslot_bd(); - - --- ************************************************************ --- * BEFORE INSERT on all slots --- * - Check name prefix --- ************************************************************ -create function tg_chkslotname() returns trigger as ' -begin - if substr(new.slotname, 1, 2) != tg_argv[0] then - raise exception ''slotname must begin with %'', tg_argv[0]; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_chkslotname before insert - on PSlot for each row execute procedure tg_chkslotname('PS'); - -create trigger tg_chkslotname before insert - on WSlot for each row execute procedure tg_chkslotname('WS'); - -create trigger tg_chkslotname before insert - on PLine for each row execute procedure tg_chkslotname('PL'); - -create trigger tg_chkslotname before insert - on IFace for each row execute procedure tg_chkslotname('IF'); - -create trigger tg_chkslotname before insert - on PHone for each row execute procedure tg_chkslotname('PH'); - - --- ************************************************************ --- * BEFORE INSERT or UPDATE on all slots with slotlink --- * - Set slotlink to empty string if NULL value given --- ************************************************************ -create function tg_chkslotlink() returns trigger as ' -begin - if new.slotlink isnull then - new.slotlink := ''''; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_chkslotlink before insert or update - on PSlot for each row execute procedure tg_chkslotlink(); - -create trigger tg_chkslotlink before insert or update - on WSlot for each row execute procedure tg_chkslotlink(); - -create trigger tg_chkslotlink before insert or update - on IFace for each row execute procedure tg_chkslotlink(); - -create trigger tg_chkslotlink before insert or update - on HSlot for each row execute procedure tg_chkslotlink(); - -create trigger tg_chkslotlink before insert or update - on PHone for each row execute procedure tg_chkslotlink(); - - --- ************************************************************ --- * BEFORE INSERT or UPDATE on all slots with backlink --- * - Set backlink to empty string if NULL value given --- ************************************************************ -create function tg_chkbacklink() returns trigger as ' -begin - if new.backlink isnull then - new.backlink := ''''; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_chkbacklink before insert or update - on PSlot for each row execute procedure tg_chkbacklink(); - -create trigger tg_chkbacklink before insert or update - on WSlot for each row execute procedure tg_chkbacklink(); - -create trigger tg_chkbacklink before insert or update - on PLine for each row execute procedure tg_chkbacklink(); - - --- ************************************************************ --- * BEFORE UPDATE on PSlot --- * - do delete/insert instead of update if name changes --- ************************************************************ -create function tg_pslot_bu() returns trigger as ' -begin - if new.slotname != old.slotname then - delete from PSlot where slotname = old.slotname; - insert into PSlot ( - slotname, - pfname, - slotlink, - backlink - ) values ( - new.slotname, - new.pfname, - new.slotlink, - new.backlink - ); - return null; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_pslot_bu before update - on PSlot for each row execute procedure tg_pslot_bu(); - - --- ************************************************************ --- * BEFORE UPDATE on WSlot --- * - do delete/insert instead of update if name changes --- ************************************************************ -create function tg_wslot_bu() returns trigger as ' -begin - if new.slotname != old.slotname then - delete from WSlot where slotname = old.slotname; - insert into WSlot ( - slotname, - roomno, - slotlink, - backlink - ) values ( - new.slotname, - new.roomno, - new.slotlink, - new.backlink - ); - return null; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_wslot_bu before update - on WSlot for each row execute procedure tg_Wslot_bu(); - - --- ************************************************************ --- * BEFORE UPDATE on PLine --- * - do delete/insert instead of update if name changes --- ************************************************************ -create function tg_pline_bu() returns trigger as ' -begin - if new.slotname != old.slotname then - delete from PLine where slotname = old.slotname; - insert into PLine ( - slotname, - phonenumber, - comment, - backlink - ) values ( - new.slotname, - new.phonenumber, - new.comment, - new.backlink - ); - return null; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_pline_bu before update - on PLine for each row execute procedure tg_pline_bu(); - - --- ************************************************************ --- * BEFORE UPDATE on IFace --- * - do delete/insert instead of update if name changes --- ************************************************************ -create function tg_iface_bu() returns trigger as ' -begin - if new.slotname != old.slotname then - delete from IFace where slotname = old.slotname; - insert into IFace ( - slotname, - sysname, - ifname, - slotlink - ) values ( - new.slotname, - new.sysname, - new.ifname, - new.slotlink - ); - return null; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_iface_bu before update - on IFace for each row execute procedure tg_iface_bu(); - - --- ************************************************************ --- * BEFORE UPDATE on HSlot --- * - do delete/insert instead of update if name changes --- ************************************************************ -create function tg_hslot_bu() returns trigger as ' -begin - if new.slotname != old.slotname or new.hubname != old.hubname then - delete from HSlot where slotname = old.slotname; - insert into HSlot ( - slotname, - hubname, - slotno, - slotlink - ) values ( - new.slotname, - new.hubname, - new.slotno, - new.slotlink - ); - return null; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_hslot_bu before update - on HSlot for each row execute procedure tg_hslot_bu(); - - --- ************************************************************ --- * BEFORE UPDATE on PHone --- * - do delete/insert instead of update if name changes --- ************************************************************ -create function tg_phone_bu() returns trigger as ' -begin - if new.slotname != old.slotname then - delete from PHone where slotname = old.slotname; - insert into PHone ( - slotname, - comment, - slotlink - ) values ( - new.slotname, - new.comment, - new.slotlink - ); - return null; - end if; - return new; -end; -' language plpgsql; - -create trigger tg_phone_bu before update - on PHone for each row execute procedure tg_phone_bu(); - - --- ************************************************************ --- * AFTER INSERT or UPDATE or DELETE on slot with backlink --- * - Ensure that the opponent correctly points back to us --- ************************************************************ -create function tg_backlink_a() returns trigger as ' -declare - dummy integer; -begin - if tg_op = ''INSERT'' then - if new.backlink != '''' then - dummy := tg_backlink_set(new.backlink, new.slotname); - end if; - return new; - end if; - if tg_op = ''UPDATE'' then - if new.backlink != old.backlink then - if old.backlink != '''' then - dummy := tg_backlink_unset(old.backlink, old.slotname); - end if; - if new.backlink != '''' then - dummy := tg_backlink_set(new.backlink, new.slotname); - end if; - else - if new.slotname != old.slotname and new.backlink != '''' then - dummy := tg_slotlink_set(new.backlink, new.slotname); - end if; - end if; - return new; - end if; - if tg_op = ''DELETE'' then - if old.backlink != '''' then - dummy := tg_backlink_unset(old.backlink, old.slotname); - end if; - return old; - end if; -end; -' language plpgsql; - - -create trigger tg_backlink_a after insert or update or delete - on PSlot for each row execute procedure tg_backlink_a('PS'); - -create trigger tg_backlink_a after insert or update or delete - on WSlot for each row execute procedure tg_backlink_a('WS'); - -create trigger tg_backlink_a after insert or update or delete - on PLine for each row execute procedure tg_backlink_a('PL'); - - --- ************************************************************ --- * Support function to set the opponents backlink field --- * if it does not already point to the requested slot --- ************************************************************ -create function tg_backlink_set(myname bpchar, blname bpchar) -returns integer as ' -declare - mytype char(2); - link char(4); - rec record; -begin - mytype := substr(myname, 1, 2); - link := mytype || substr(blname, 1, 2); - if link = ''PLPL'' then - raise exception - ''backlink between two phone lines does not make sense''; - end if; - if link in (''PLWS'', ''WSPL'') then - raise exception - ''direct link of phone line to wall slot not permitted''; - end if; - if mytype = ''PS'' then - select into rec * from PSlot where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.backlink != blname then - update PSlot set backlink = blname where slotname = myname; - end if; - return 0; - end if; - if mytype = ''WS'' then - select into rec * from WSlot where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.backlink != blname then - update WSlot set backlink = blname where slotname = myname; - end if; - return 0; - end if; - if mytype = ''PL'' then - select into rec * from PLine where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.backlink != blname then - update PLine set backlink = blname where slotname = myname; - end if; - return 0; - end if; - raise exception ''illegal backlink beginning with %'', mytype; -end; -' language plpgsql; - - --- ************************************************************ --- * Support function to clear out the backlink field if --- * it still points to specific slot --- ************************************************************ -create function tg_backlink_unset(bpchar, bpchar) -returns integer as ' -declare - myname alias for $1; - blname alias for $2; - mytype char(2); - rec record; -begin - mytype := substr(myname, 1, 2); - if mytype = ''PS'' then - select into rec * from PSlot where slotname = myname; - if not found then - return 0; - end if; - if rec.backlink = blname then - update PSlot set backlink = '''' where slotname = myname; - end if; - return 0; - end if; - if mytype = ''WS'' then - select into rec * from WSlot where slotname = myname; - if not found then - return 0; - end if; - if rec.backlink = blname then - update WSlot set backlink = '''' where slotname = myname; - end if; - return 0; - end if; - if mytype = ''PL'' then - select into rec * from PLine where slotname = myname; - if not found then - return 0; - end if; - if rec.backlink = blname then - update PLine set backlink = '''' where slotname = myname; - end if; - return 0; - end if; -end -' language plpgsql; - - --- ************************************************************ --- * AFTER INSERT or UPDATE or DELETE on slot with slotlink --- * - Ensure that the opponent correctly points back to us --- ************************************************************ -create function tg_slotlink_a() returns trigger as ' -declare - dummy integer; -begin - if tg_op = ''INSERT'' then - if new.slotlink != '''' then - dummy := tg_slotlink_set(new.slotlink, new.slotname); - end if; - return new; - end if; - if tg_op = ''UPDATE'' then - if new.slotlink != old.slotlink then - if old.slotlink != '''' then - dummy := tg_slotlink_unset(old.slotlink, old.slotname); - end if; - if new.slotlink != '''' then - dummy := tg_slotlink_set(new.slotlink, new.slotname); - end if; - else - if new.slotname != old.slotname and new.slotlink != '''' then - dummy := tg_slotlink_set(new.slotlink, new.slotname); - end if; - end if; - return new; - end if; - if tg_op = ''DELETE'' then - if old.slotlink != '''' then - dummy := tg_slotlink_unset(old.slotlink, old.slotname); - end if; - return old; - end if; -end; -' language plpgsql; - - -create trigger tg_slotlink_a after insert or update or delete - on PSlot for each row execute procedure tg_slotlink_a('PS'); - -create trigger tg_slotlink_a after insert or update or delete - on WSlot for each row execute procedure tg_slotlink_a('WS'); - -create trigger tg_slotlink_a after insert or update or delete - on IFace for each row execute procedure tg_slotlink_a('IF'); - -create trigger tg_slotlink_a after insert or update or delete - on HSlot for each row execute procedure tg_slotlink_a('HS'); - -create trigger tg_slotlink_a after insert or update or delete - on PHone for each row execute procedure tg_slotlink_a('PH'); - - --- ************************************************************ --- * Support function to set the opponents slotlink field --- * if it does not already point to the requested slot --- ************************************************************ -create function tg_slotlink_set(bpchar, bpchar) -returns integer as ' -declare - myname alias for $1; - blname alias for $2; - mytype char(2); - link char(4); - rec record; -begin - mytype := substr(myname, 1, 2); - link := mytype || substr(blname, 1, 2); - if link = ''PHPH'' then - raise exception - ''slotlink between two phones does not make sense''; - end if; - if link in (''PHHS'', ''HSPH'') then - raise exception - ''link of phone to hub does not make sense''; - end if; - if link in (''PHIF'', ''IFPH'') then - raise exception - ''link of phone to hub does not make sense''; - end if; - if link in (''PSWS'', ''WSPS'') then - raise exception - ''slotlink from patchslot to wallslot not permitted''; - end if; - if mytype = ''PS'' then - select into rec * from PSlot where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.slotlink != blname then - update PSlot set slotlink = blname where slotname = myname; - end if; - return 0; - end if; - if mytype = ''WS'' then - select into rec * from WSlot where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.slotlink != blname then - update WSlot set slotlink = blname where slotname = myname; - end if; - return 0; - end if; - if mytype = ''IF'' then - select into rec * from IFace where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.slotlink != blname then - update IFace set slotlink = blname where slotname = myname; - end if; - return 0; - end if; - if mytype = ''HS'' then - select into rec * from HSlot where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.slotlink != blname then - update HSlot set slotlink = blname where slotname = myname; - end if; - return 0; - end if; - if mytype = ''PH'' then - select into rec * from PHone where slotname = myname; - if not found then - raise exception ''% does not exist'', myname; - end if; - if rec.slotlink != blname then - update PHone set slotlink = blname where slotname = myname; - end if; - return 0; - end if; - raise exception ''illegal slotlink beginning with %'', mytype; -end; -' language plpgsql; - - --- ************************************************************ --- * Support function to clear out the slotlink field if --- * it still points to specific slot --- ************************************************************ -create function tg_slotlink_unset(bpchar, bpchar) -returns integer as ' -declare - myname alias for $1; - blname alias for $2; - mytype char(2); - rec record; -begin - mytype := substr(myname, 1, 2); - if mytype = ''PS'' then - select into rec * from PSlot where slotname = myname; - if not found then - return 0; - end if; - if rec.slotlink = blname then - update PSlot set slotlink = '''' where slotname = myname; - end if; - return 0; - end if; - if mytype = ''WS'' then - select into rec * from WSlot where slotname = myname; - if not found then - return 0; - end if; - if rec.slotlink = blname then - update WSlot set slotlink = '''' where slotname = myname; - end if; - return 0; - end if; - if mytype = ''IF'' then - select into rec * from IFace where slotname = myname; - if not found then - return 0; - end if; - if rec.slotlink = blname then - update IFace set slotlink = '''' where slotname = myname; - end if; - return 0; - end if; - if mytype = ''HS'' then - select into rec * from HSlot where slotname = myname; - if not found then - return 0; - end if; - if rec.slotlink = blname then - update HSlot set slotlink = '''' where slotname = myname; - end if; - return 0; - end if; - if mytype = ''PH'' then - select into rec * from PHone where slotname = myname; - if not found then - return 0; - end if; - if rec.slotlink = blname then - update PHone set slotlink = '''' where slotname = myname; - end if; - return 0; - end if; -end; -' language plpgsql; - - --- ************************************************************ --- * Describe the backside of a patchfield slot --- ************************************************************ -create function pslot_backlink_view(bpchar) -returns text as ' -<> -declare - rec record; - bltype char(2); - retval text; -begin - select into rec * from PSlot where slotname = $1; - if not found then - return ''''; - end if; - if rec.backlink = '''' then - return ''-''; - end if; - bltype := substr(rec.backlink, 1, 2); - if bltype = ''PL'' then - declare - rec record; - begin - select into rec * from PLine where slotname = "outer".rec.backlink; - retval := ''Phone line '' || trim(rec.phonenumber); - if rec.comment != '''' then - retval := retval || '' (''; - retval := retval || rec.comment; - retval := retval || '')''; - end if; - return retval; - end; - end if; - if bltype = ''WS'' then - select into rec * from WSlot where slotname = rec.backlink; - retval := trim(rec.slotname) || '' in room ''; - retval := retval || trim(rec.roomno); - retval := retval || '' -> ''; - return retval || wslot_slotlink_view(rec.slotname); - end if; - return rec.backlink; -end; -' language plpgsql; - - --- ************************************************************ --- * Describe the front of a patchfield slot --- ************************************************************ -create function pslot_slotlink_view(bpchar) -returns text as ' -declare - psrec record; - sltype char(2); - retval text; -begin - select into psrec * from PSlot where slotname = $1; - if not found then - return ''''; - end if; - if psrec.slotlink = '''' then - return ''-''; - end if; - sltype := substr(psrec.slotlink, 1, 2); - if sltype = ''PS'' then - retval := trim(psrec.slotlink) || '' -> ''; - return retval || pslot_backlink_view(psrec.slotlink); - end if; - if sltype = ''HS'' then - retval := comment from Hub H, HSlot HS - where HS.slotname = psrec.slotlink - and H.name = HS.hubname; - retval := retval || '' slot ''; - retval := retval || slotno::text from HSlot - where slotname = psrec.slotlink; - return retval; - end if; - return psrec.slotlink; -end; -' language plpgsql; - - --- ************************************************************ --- * Describe the front of a wall connector slot --- ************************************************************ -create function wslot_slotlink_view(bpchar) -returns text as ' -declare - rec record; - sltype char(2); - retval text; -begin - select into rec * from WSlot where slotname = $1; - if not found then - return ''''; - end if; - if rec.slotlink = '''' then - return ''-''; - end if; - sltype := substr(rec.slotlink, 1, 2); - if sltype = ''PH'' then - select into rec * from PHone where slotname = rec.slotlink; - retval := ''Phone '' || trim(rec.slotname); - if rec.comment != '''' then - retval := retval || '' (''; - retval := retval || rec.comment; - retval := retval || '')''; - end if; - return retval; - end if; - if sltype = ''IF'' then - declare - syrow System%RowType; - ifrow IFace%ROWTYPE; - begin - select into ifrow * from IFace where slotname = rec.slotlink; - select into syrow * from System where name = ifrow.sysname; - retval := syrow.name || '' IF ''; - retval := retval || ifrow.ifname; - if syrow.comment != '''' then - retval := retval || '' (''; - retval := retval || syrow.comment; - retval := retval || '')''; - end if; - return retval; - end; - end if; - return rec.slotlink; -end; -' language plpgsql; - - - --- ************************************************************ --- * View of a patchfield describing backside and patches --- ************************************************************ -create view Pfield_v1 as select PF.pfname, PF.slotname, - pslot_backlink_view(PF.slotname) as backside, - pslot_slotlink_view(PF.slotname) as patch - from PSlot PF; - - --- --- First we build the house - so we create the rooms --- -insert into Room values ('001', 'Entrance'); -insert into Room values ('002', 'Office'); -insert into Room values ('003', 'Office'); -insert into Room values ('004', 'Technical'); -insert into Room values ('101', 'Office'); -insert into Room values ('102', 'Conference'); -insert into Room values ('103', 'Restroom'); -insert into Room values ('104', 'Technical'); -insert into Room values ('105', 'Office'); -insert into Room values ('106', 'Office'); - --- --- Second we install the wall connectors --- -insert into WSlot values ('WS.001.1a', '001', '', ''); -insert into WSlot values ('WS.001.1b', '001', '', ''); -insert into WSlot values ('WS.001.2a', '001', '', ''); -insert into WSlot values ('WS.001.2b', '001', '', ''); -insert into WSlot values ('WS.001.3a', '001', '', ''); -insert into WSlot values ('WS.001.3b', '001', '', ''); - -insert into WSlot values ('WS.002.1a', '002', '', ''); -insert into WSlot values ('WS.002.1b', '002', '', ''); -insert into WSlot values ('WS.002.2a', '002', '', ''); -insert into WSlot values ('WS.002.2b', '002', '', ''); -insert into WSlot values ('WS.002.3a', '002', '', ''); -insert into WSlot values ('WS.002.3b', '002', '', ''); - -insert into WSlot values ('WS.003.1a', '003', '', ''); -insert into WSlot values ('WS.003.1b', '003', '', ''); -insert into WSlot values ('WS.003.2a', '003', '', ''); -insert into WSlot values ('WS.003.2b', '003', '', ''); -insert into WSlot values ('WS.003.3a', '003', '', ''); -insert into WSlot values ('WS.003.3b', '003', '', ''); - -insert into WSlot values ('WS.101.1a', '101', '', ''); -insert into WSlot values ('WS.101.1b', '101', '', ''); -insert into WSlot values ('WS.101.2a', '101', '', ''); -insert into WSlot values ('WS.101.2b', '101', '', ''); -insert into WSlot values ('WS.101.3a', '101', '', ''); -insert into WSlot values ('WS.101.3b', '101', '', ''); - -insert into WSlot values ('WS.102.1a', '102', '', ''); -insert into WSlot values ('WS.102.1b', '102', '', ''); -insert into WSlot values ('WS.102.2a', '102', '', ''); -insert into WSlot values ('WS.102.2b', '102', '', ''); -insert into WSlot values ('WS.102.3a', '102', '', ''); -insert into WSlot values ('WS.102.3b', '102', '', ''); - -insert into WSlot values ('WS.105.1a', '105', '', ''); -insert into WSlot values ('WS.105.1b', '105', '', ''); -insert into WSlot values ('WS.105.2a', '105', '', ''); -insert into WSlot values ('WS.105.2b', '105', '', ''); -insert into WSlot values ('WS.105.3a', '105', '', ''); -insert into WSlot values ('WS.105.3b', '105', '', ''); - -insert into WSlot values ('WS.106.1a', '106', '', ''); -insert into WSlot values ('WS.106.1b', '106', '', ''); -insert into WSlot values ('WS.106.2a', '106', '', ''); -insert into WSlot values ('WS.106.2b', '106', '', ''); -insert into WSlot values ('WS.106.3a', '106', '', ''); -insert into WSlot values ('WS.106.3b', '106', '', ''); - --- --- Now create the patch fields and their slots --- -insert into PField values ('PF0_1', 'Wallslots basement'); - --- --- The cables for these will be made later, so they are unconnected for now --- -insert into PSlot values ('PS.base.a1', 'PF0_1', '', ''); -insert into PSlot values ('PS.base.a2', 'PF0_1', '', ''); -insert into PSlot values ('PS.base.a3', 'PF0_1', '', ''); -insert into PSlot values ('PS.base.a4', 'PF0_1', '', ''); -insert into PSlot values ('PS.base.a5', 'PF0_1', '', ''); -insert into PSlot values ('PS.base.a6', 'PF0_1', '', ''); - --- --- These are already wired to the wall connectors --- -insert into PSlot values ('PS.base.b1', 'PF0_1', '', 'WS.002.1a'); -insert into PSlot values ('PS.base.b2', 'PF0_1', '', 'WS.002.1b'); -insert into PSlot values ('PS.base.b3', 'PF0_1', '', 'WS.002.2a'); -insert into PSlot values ('PS.base.b4', 'PF0_1', '', 'WS.002.2b'); -insert into PSlot values ('PS.base.b5', 'PF0_1', '', 'WS.002.3a'); -insert into PSlot values ('PS.base.b6', 'PF0_1', '', 'WS.002.3b'); - -insert into PSlot values ('PS.base.c1', 'PF0_1', '', 'WS.003.1a'); -insert into PSlot values ('PS.base.c2', 'PF0_1', '', 'WS.003.1b'); -insert into PSlot values ('PS.base.c3', 'PF0_1', '', 'WS.003.2a'); -insert into PSlot values ('PS.base.c4', 'PF0_1', '', 'WS.003.2b'); -insert into PSlot values ('PS.base.c5', 'PF0_1', '', 'WS.003.3a'); -insert into PSlot values ('PS.base.c6', 'PF0_1', '', 'WS.003.3b'); - --- --- This patchfield will be renamed later into PF0_2 - so its --- slots references in pfname should follow --- -insert into PField values ('PF0_X', 'Phonelines basement'); - -insert into PSlot values ('PS.base.ta1', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.ta2', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.ta3', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.ta4', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.ta5', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.ta6', 'PF0_X', '', ''); - -insert into PSlot values ('PS.base.tb1', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.tb2', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.tb3', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.tb4', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.tb5', 'PF0_X', '', ''); -insert into PSlot values ('PS.base.tb6', 'PF0_X', '', ''); - -insert into PField values ('PF1_1', 'Wallslots first floor'); - -insert into PSlot values ('PS.first.a1', 'PF1_1', '', 'WS.101.1a'); -insert into PSlot values ('PS.first.a2', 'PF1_1', '', 'WS.101.1b'); -insert into PSlot values ('PS.first.a3', 'PF1_1', '', 'WS.101.2a'); -insert into PSlot values ('PS.first.a4', 'PF1_1', '', 'WS.101.2b'); -insert into PSlot values ('PS.first.a5', 'PF1_1', '', 'WS.101.3a'); -insert into PSlot values ('PS.first.a6', 'PF1_1', '', 'WS.101.3b'); - -insert into PSlot values ('PS.first.b1', 'PF1_1', '', 'WS.102.1a'); -insert into PSlot values ('PS.first.b2', 'PF1_1', '', 'WS.102.1b'); -insert into PSlot values ('PS.first.b3', 'PF1_1', '', 'WS.102.2a'); -insert into PSlot values ('PS.first.b4', 'PF1_1', '', 'WS.102.2b'); -insert into PSlot values ('PS.first.b5', 'PF1_1', '', 'WS.102.3a'); -insert into PSlot values ('PS.first.b6', 'PF1_1', '', 'WS.102.3b'); - -insert into PSlot values ('PS.first.c1', 'PF1_1', '', 'WS.105.1a'); -insert into PSlot values ('PS.first.c2', 'PF1_1', '', 'WS.105.1b'); -insert into PSlot values ('PS.first.c3', 'PF1_1', '', 'WS.105.2a'); -insert into PSlot values ('PS.first.c4', 'PF1_1', '', 'WS.105.2b'); -insert into PSlot values ('PS.first.c5', 'PF1_1', '', 'WS.105.3a'); -insert into PSlot values ('PS.first.c6', 'PF1_1', '', 'WS.105.3b'); - -insert into PSlot values ('PS.first.d1', 'PF1_1', '', 'WS.106.1a'); -insert into PSlot values ('PS.first.d2', 'PF1_1', '', 'WS.106.1b'); -insert into PSlot values ('PS.first.d3', 'PF1_1', '', 'WS.106.2a'); -insert into PSlot values ('PS.first.d4', 'PF1_1', '', 'WS.106.2b'); -insert into PSlot values ('PS.first.d5', 'PF1_1', '', 'WS.106.3a'); -insert into PSlot values ('PS.first.d6', 'PF1_1', '', 'WS.106.3b'); - --- --- Now we wire the wall connectors 1a-2a in room 001 to the --- patchfield. In the second update we make an error, and --- correct it after --- -update PSlot set backlink = 'WS.001.1a' where slotname = 'PS.base.a1'; -update PSlot set backlink = 'WS.001.1b' where slotname = 'PS.base.a3'; -select * from WSlot where roomno = '001' order by slotname; -select * from PSlot where slotname ~ 'PS.base.a' order by slotname; -update PSlot set backlink = 'WS.001.2a' where slotname = 'PS.base.a3'; -select * from WSlot where roomno = '001' order by slotname; -select * from PSlot where slotname ~ 'PS.base.a' order by slotname; -update PSlot set backlink = 'WS.001.1b' where slotname = 'PS.base.a2'; -select * from WSlot where roomno = '001' order by slotname; -select * from PSlot where slotname ~ 'PS.base.a' order by slotname; - --- --- Same procedure for 2b-3b but this time updating the WSlot instead --- of the PSlot. Due to the triggers the result is the same: --- WSlot and corresponding PSlot point to each other. --- -update WSlot set backlink = 'PS.base.a4' where slotname = 'WS.001.2b'; -update WSlot set backlink = 'PS.base.a6' where slotname = 'WS.001.3a'; -select * from WSlot where roomno = '001' order by slotname; -select * from PSlot where slotname ~ 'PS.base.a' order by slotname; -update WSlot set backlink = 'PS.base.a6' where slotname = 'WS.001.3b'; -select * from WSlot where roomno = '001' order by slotname; -select * from PSlot where slotname ~ 'PS.base.a' order by slotname; -update WSlot set backlink = 'PS.base.a5' where slotname = 'WS.001.3a'; -select * from WSlot where roomno = '001' order by slotname; -select * from PSlot where slotname ~ 'PS.base.a' order by slotname; - -insert into PField values ('PF1_2', 'Phonelines first floor'); - -insert into PSlot values ('PS.first.ta1', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.ta2', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.ta3', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.ta4', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.ta5', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.ta6', 'PF1_2', '', ''); - -insert into PSlot values ('PS.first.tb1', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.tb2', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.tb3', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.tb4', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.tb5', 'PF1_2', '', ''); -insert into PSlot values ('PS.first.tb6', 'PF1_2', '', ''); - --- --- Fix the wrong name for patchfield PF0_2 --- -update PField set name = 'PF0_2' where name = 'PF0_X'; - -select * from PSlot order by slotname; -select * from WSlot order by slotname; - --- --- Install the central phone system and create the phone numbers. --- They are wired on insert to the patchfields. Again the --- triggers automatically tell the PSlots to update their --- backlink field. --- -insert into PLine values ('PL.001', '-0', 'Central call', 'PS.base.ta1'); -insert into PLine values ('PL.002', '-101', '', 'PS.base.ta2'); -insert into PLine values ('PL.003', '-102', '', 'PS.base.ta3'); -insert into PLine values ('PL.004', '-103', '', 'PS.base.ta5'); -insert into PLine values ('PL.005', '-104', '', 'PS.base.ta6'); -insert into PLine values ('PL.006', '-106', '', 'PS.base.tb2'); -insert into PLine values ('PL.007', '-108', '', 'PS.base.tb3'); -insert into PLine values ('PL.008', '-109', '', 'PS.base.tb4'); -insert into PLine values ('PL.009', '-121', '', 'PS.base.tb5'); -insert into PLine values ('PL.010', '-122', '', 'PS.base.tb6'); -insert into PLine values ('PL.015', '-134', '', 'PS.first.ta1'); -insert into PLine values ('PL.016', '-137', '', 'PS.first.ta3'); -insert into PLine values ('PL.017', '-139', '', 'PS.first.ta4'); -insert into PLine values ('PL.018', '-362', '', 'PS.first.tb1'); -insert into PLine values ('PL.019', '-363', '', 'PS.first.tb2'); -insert into PLine values ('PL.020', '-364', '', 'PS.first.tb3'); -insert into PLine values ('PL.021', '-365', '', 'PS.first.tb5'); -insert into PLine values ('PL.022', '-367', '', 'PS.first.tb6'); -insert into PLine values ('PL.028', '-501', 'Fax entrance', 'PS.base.ta2'); -insert into PLine values ('PL.029', '-502', 'Fax first floor', 'PS.first.ta1'); - --- --- Buy some phones, plug them into the wall and patch the --- phone lines to the corresponding patchfield slots. --- -insert into PHone values ('PH.hc001', 'Hicom standard', 'WS.001.1a'); -update PSlot set slotlink = 'PS.base.ta1' where slotname = 'PS.base.a1'; -insert into PHone values ('PH.hc002', 'Hicom standard', 'WS.002.1a'); -update PSlot set slotlink = 'PS.base.ta5' where slotname = 'PS.base.b1'; -insert into PHone values ('PH.hc003', 'Hicom standard', 'WS.002.2a'); -update PSlot set slotlink = 'PS.base.tb2' where slotname = 'PS.base.b3'; -insert into PHone values ('PH.fax001', 'Canon fax', 'WS.001.2a'); -update PSlot set slotlink = 'PS.base.ta2' where slotname = 'PS.base.a3'; - --- --- Install a hub at one of the patchfields, plug a computers --- ethernet interface into the wall and patch it to the hub. --- -insert into Hub values ('base.hub1', 'Patchfield PF0_1 hub', 16); -insert into System values ('orion', 'PC'); -insert into IFace values ('IF', 'orion', 'eth0', 'WS.002.1b'); -update PSlot set slotlink = 'HS.base.hub1.1' where slotname = 'PS.base.b2'; - --- --- Now we take a look at the patchfield --- -select * from PField_v1 where pfname = 'PF0_1' order by slotname; -select * from PField_v1 where pfname = 'PF0_2' order by slotname; - --- --- Finally we want errors --- -insert into PField values ('PF1_1', 'should fail due to unique index'); -update PSlot set backlink = 'WS.not.there' where slotname = 'PS.base.a1'; -update PSlot set backlink = 'XX.illegal' where slotname = 'PS.base.a1'; -update PSlot set slotlink = 'PS.not.there' where slotname = 'PS.base.a1'; -update PSlot set slotlink = 'XX.illegal' where slotname = 'PS.base.a1'; -insert into HSlot values ('HS', 'base.hub1', 1, ''); -insert into HSlot values ('HS', 'base.hub1', 20, ''); -delete from HSlot; -insert into IFace values ('IF', 'notthere', 'eth0', ''); -insert into IFace values ('IF', 'orion', 'ethernet_interface_name_too_long', ''); - - --- --- The following tests are unrelated to the scenario outlined above; --- they merely exercise specific parts of PL/pgSQL --- - --- --- Test recursion, per bug report 7-Sep-01 --- -CREATE FUNCTION recursion_test(int,int) RETURNS text AS ' -DECLARE rslt text; -BEGIN - IF $1 <= 0 THEN - rslt = CAST($2 AS TEXT); - ELSE - rslt = CAST($1 AS TEXT) || '','' || recursion_test($1 - 1, $2); - END IF; - RETURN rslt; -END;' LANGUAGE plpgsql; - -SELECT recursion_test(4,3); - --- --- Test the FOUND magic variable --- -CREATE TABLE found_test_tbl (a int); - -create function test_found() - returns boolean as ' - declare - begin - insert into found_test_tbl values (1); - if FOUND then - insert into found_test_tbl values (2); - end if; - - update found_test_tbl set a = 100 where a = 1; - if FOUND then - insert into found_test_tbl values (3); - end if; - - delete from found_test_tbl where a = 9999; -- matches no rows - if not FOUND then - insert into found_test_tbl values (4); - end if; - - for i in 1 .. 10 loop - -- no need to do anything - end loop; - if FOUND then - insert into found_test_tbl values (5); - end if; - - -- never executes the loop - for i in 2 .. 1 loop - -- no need to do anything - end loop; - if not FOUND then - insert into found_test_tbl values (6); - end if; - return true; - end;' language plpgsql; - -select test_found(); -select * from found_test_tbl; - --- --- Test set-returning functions for PL/pgSQL --- - -create function test_table_func_rec() returns setof found_test_tbl as ' -DECLARE - rec RECORD; -BEGIN - FOR rec IN select * from found_test_tbl LOOP - RETURN NEXT rec; - END LOOP; - RETURN; -END;' language plpgsql; - -select * from test_table_func_rec(); - -create function test_table_func_row() returns setof found_test_tbl as ' -DECLARE - row found_test_tbl%ROWTYPE; -BEGIN - FOR row IN select * from found_test_tbl LOOP - RETURN NEXT row; - END LOOP; - RETURN; -END;' language plpgsql; - -select * from test_table_func_row(); - -create function test_ret_set_scalar(int,int) returns setof int as ' -DECLARE - i int; -BEGIN - FOR i IN $1 .. $2 LOOP - RETURN NEXT i + 1; - END LOOP; - RETURN; -END;' language plpgsql; - -select * from test_ret_set_scalar(1,10); - -create function test_ret_set_rec_dyn(int) returns setof record as ' -DECLARE - retval RECORD; -BEGIN - IF $1 > 10 THEN - SELECT INTO retval 5, 10, 15; - RETURN NEXT retval; - RETURN NEXT retval; - ELSE - SELECT INTO retval 50, 5::numeric, ''xxx''::text; - RETURN NEXT retval; - RETURN NEXT retval; - END IF; - RETURN; -END;' language plpgsql; - -SELECT * FROM test_ret_set_rec_dyn(1500) AS (a int, b int, c int); -SELECT * FROM test_ret_set_rec_dyn(5) AS (a int, b numeric, c text); - -create function test_ret_rec_dyn(int) returns record as ' -DECLARE - retval RECORD; -BEGIN - IF $1 > 10 THEN - SELECT INTO retval 5, 10, 15; - RETURN retval; - ELSE - SELECT INTO retval 50, 5::numeric, ''xxx''::text; - RETURN retval; - END IF; -END;' language plpgsql; - -SELECT * FROM test_ret_rec_dyn(1500) AS (a int, b int, c int); -SELECT * FROM test_ret_rec_dyn(5) AS (a int, b numeric, c text); - --- --- Test some simple polymorphism cases. --- - -create function f1(x anyelement) returns anyelement as $$ -begin - return x + 1; -end$$ language plpgsql; - -select f1(42) as int, f1(4.5) as num; -select f1(point(3,4)); -- fail for lack of + operator - -drop function f1(x anyelement); - -create function f1(x anyelement) returns anyarray as $$ -begin - return array[x + 1, x + 2]; -end$$ language plpgsql; - -select f1(42) as int, f1(4.5) as num; - -drop function f1(x anyelement); - -create function f1(x anyarray) returns anyelement as $$ -begin - return x[1]; -end$$ language plpgsql; - -select f1(array[2,4]) as int, f1(array[4.5, 7.7]) as num; - -select f1(stavalues1) from pg_statistic; -- fail, can't infer element type - -drop function f1(x anyarray); - -create function f1(x anyarray) returns anyarray as $$ -begin - return x; -end$$ language plpgsql; - -select f1(array[2,4]) as int, f1(array[4.5, 7.7]) as num; - -select f1(stavalues1) from pg_statistic; -- fail, can't infer element type - -drop function f1(x anyarray); - --- fail, can't infer type: -create function f1(x anyelement) returns anyrange as $$ -begin - return array[x + 1, x + 2]; -end$$ language plpgsql; - -create function f1(x anyrange) returns anyarray as $$ -begin - return array[lower(x), upper(x)]; -end$$ language plpgsql; - -select f1(int4range(42, 49)) as int, f1(float8range(4.5, 7.8)) as num; - -drop function f1(x anyrange); - -create function f1(x anycompatible, y anycompatible) returns anycompatiblearray as $$ -begin - return array[x, y]; -end$$ language plpgsql; - -select f1(2, 4) as int, f1(2, 4.5) as num; - -drop function f1(x anycompatible, y anycompatible); - -create function f1(x anycompatiblerange, y anycompatible, z anycompatible) returns anycompatiblearray as $$ -begin - return array[lower(x), upper(x), y, z]; -end$$ language plpgsql; - -select f1(int4range(42, 49), 11, 2::smallint) as int, f1(float8range(4.5, 7.8), 7.8, 11::real) as num; - -select f1(int4range(42, 49), 11, 4.5) as fail; -- range type doesn't fit - -drop function f1(x anycompatiblerange, y anycompatible, z anycompatible); - --- fail, can't infer type: -create function f1(x anycompatible) returns anycompatiblerange as $$ -begin - return array[x + 1, x + 2]; -end$$ language plpgsql; - -create function f1(x anycompatiblerange, y anycompatiblearray) returns anycompatiblerange as $$ -begin - return x; -end$$ language plpgsql; - -select f1(int4range(42, 49), array[11]) as int, f1(float8range(4.5, 7.8), array[7]) as num; - -drop function f1(x anycompatiblerange, y anycompatiblearray); - -create function f1(a anyelement, b anyarray, - c anycompatible, d anycompatible, - OUT x anyarray, OUT y anycompatiblearray) -as $$ -begin - x := a || b; - y := array[c, d]; -end$$ language plpgsql; - -select x, pg_typeof(x), y, pg_typeof(y) - from f1(11, array[1, 2], 42, 34.5); -select x, pg_typeof(x), y, pg_typeof(y) - from f1(11, array[1, 2], point(1,2), point(3,4)); -select x, pg_typeof(x), y, pg_typeof(y) - from f1(11, '{1,2}', point(1,2), '(3,4)'); -select x, pg_typeof(x), y, pg_typeof(y) - from f1(11, array[1, 2.2], 42, 34.5); -- fail - -drop function f1(a anyelement, b anyarray, - c anycompatible, d anycompatible); - --- --- Test handling of OUT parameters, including polymorphic cases. --- Note that RETURN is optional with OUT params; we try both ways. --- - --- wrong way to do it: -create function f1(in i int, out j int) returns int as $$ -begin - return i+1; -end$$ language plpgsql; - -create function f1(in i int, out j int) as $$ -begin - j := i+1; - return; -end$$ language plpgsql; - -select f1(42); -select * from f1(42); - -create or replace function f1(inout i int) as $$ -begin - i := i+1; -end$$ language plpgsql; - -select f1(42); -select * from f1(42); - -drop function f1(int); - -create function f1(in i int, out j int) returns setof int as $$ -begin - j := i+1; - return next; - j := i+2; - return next; - return; -end$$ language plpgsql; - -select * from f1(42); - -drop function f1(int); - -create function f1(in i int, out j int, out k text) as $$ -begin - j := i; - j := j+1; - k := 'foo'; -end$$ language plpgsql; - -select f1(42); -select * from f1(42); - -drop function f1(int); - -create function f1(in i int, out j int, out k text) returns setof record as $$ -begin - j := i+1; - k := 'foo'; - return next; - j := j+1; - k := 'foot'; - return next; -end$$ language plpgsql; - -select * from f1(42); - -drop function f1(int); - -create function duplic(in i anyelement, out j anyelement, out k anyarray) as $$ -begin - j := i; - k := array[j,j]; - return; -end$$ language plpgsql; - -select * from duplic(42); -select * from duplic('foo'::text); - -drop function duplic(anyelement); - -create function duplic(in i anycompatiblerange, out j anycompatible, out k anycompatiblearray) as $$ -begin - j := lower(i); - k := array[lower(i),upper(i)]; - return; -end$$ language plpgsql; - -select * from duplic(int4range(42,49)); -select * from duplic(textrange('aaa', 'bbb')); - -drop function duplic(anycompatiblerange); - --- --- test PERFORM --- - -create table perform_test ( - a INT, - b INT -); - -create function perform_simple_func(int) returns boolean as ' -BEGIN - IF $1 < 20 THEN - INSERT INTO perform_test VALUES ($1, $1 + 10); - RETURN TRUE; - ELSE - RETURN FALSE; - END IF; -END;' language plpgsql; - -create function perform_test_func() returns void as ' -BEGIN - IF FOUND then - INSERT INTO perform_test VALUES (100, 100); - END IF; - - PERFORM perform_simple_func(5); - - IF FOUND then - INSERT INTO perform_test VALUES (100, 100); - END IF; - - PERFORM perform_simple_func(50); - - IF FOUND then - INSERT INTO perform_test VALUES (100, 100); - END IF; - - RETURN; -END;' language plpgsql; - -SELECT perform_test_func(); -SELECT * FROM perform_test; - -drop table perform_test; - --- --- Test proper snapshot handling in simple expressions --- - -create temp table users(login text, id serial); - -create function sp_id_user(a_login text) returns int as $$ -declare x int; -begin - select into x id from users where login = a_login; - if found then return x; end if; - return 0; -end$$ language plpgsql stable; - -insert into users values('user1'); - -select sp_id_user('user1'); -select sp_id_user('userx'); - -create function sp_add_user(a_login text) returns int as $$ -declare my_id_user int; -begin - my_id_user = sp_id_user( a_login ); - IF my_id_user > 0 THEN - RETURN -1; -- error code for existing user - END IF; - INSERT INTO users ( login ) VALUES ( a_login ); - my_id_user = sp_id_user( a_login ); - IF my_id_user = 0 THEN - RETURN -2; -- error code for insertion failure - END IF; - RETURN my_id_user; -end$$ language plpgsql; - -select sp_add_user('user1'); -select sp_add_user('user2'); -select sp_add_user('user2'); -select sp_add_user('user3'); -select sp_add_user('user3'); - -drop function sp_add_user(text); -drop function sp_id_user(text); - --- --- tests for refcursors --- -create table rc_test (a int, b int); -copy rc_test from stdin; -5 10 -50 100 -500 1000 -\. - -create function return_unnamed_refcursor() returns refcursor as $$ -declare - rc refcursor; -begin - open rc for select a from rc_test; - return rc; -end -$$ language plpgsql; - -create function use_refcursor(rc refcursor) returns int as $$ -declare - rc refcursor; - x record; -begin - rc := return_unnamed_refcursor(); - fetch next from rc into x; - return x.a; -end -$$ language plpgsql; - -select use_refcursor(return_unnamed_refcursor()); - -create function return_refcursor(rc refcursor) returns refcursor as $$ -begin - open rc for select a from rc_test; - return rc; -end -$$ language plpgsql; - -create function refcursor_test1(refcursor) returns refcursor as $$ -begin - perform return_refcursor($1); - return $1; -end -$$ language plpgsql; - -begin; - -select refcursor_test1('test1'); -fetch next in test1; - -select refcursor_test1('test2'); -fetch all from test2; - -commit; - --- should fail -fetch next from test1; - -create function refcursor_test2(int, int) returns boolean as $$ -declare - c1 cursor (param1 int, param2 int) for select * from rc_test where a > param1 and b > param2; - nonsense record; -begin - open c1($1, $2); - fetch c1 into nonsense; - close c1; - if found then - return true; - else - return false; - end if; -end -$$ language plpgsql; - -select refcursor_test2(20000, 20000) as "Should be false", - refcursor_test2(20, 20) as "Should be true"; - --- should fail -create function constant_refcursor() returns refcursor as $$ -declare - rc constant refcursor; -begin - open rc for select a from rc_test; - return rc; -end -$$ language plpgsql; - -select constant_refcursor(); - --- but it's okay like this -create or replace function constant_refcursor() returns refcursor as $$ -declare - rc constant refcursor := 'my_cursor_name'; -begin - open rc for select a from rc_test; - return rc; -end -$$ language plpgsql; - -select constant_refcursor(); - --- --- tests for cursors with named parameter arguments --- -create function namedparmcursor_test1(int, int) returns boolean as $$ -declare - c1 cursor (param1 int, param12 int) for select * from rc_test where a > param1 and b > param12; - nonsense record; -begin - open c1(param12 := $2, param1 := $1); - fetch c1 into nonsense; - close c1; - if found then - return true; - else - return false; - end if; -end -$$ language plpgsql; - -select namedparmcursor_test1(20000, 20000) as "Should be false", - namedparmcursor_test1(20, 20) as "Should be true"; - --- mixing named and positional argument notations -create function namedparmcursor_test2(int, int) returns boolean as $$ -declare - c1 cursor (param1 int, param2 int) for select * from rc_test where a > param1 and b > param2; - nonsense record; -begin - open c1(param1 := $1, $2); - fetch c1 into nonsense; - close c1; - if found then - return true; - else - return false; - end if; -end -$$ language plpgsql; -select namedparmcursor_test2(20, 20); - --- mixing named and positional: param2 is given twice, once in named notation --- and second time in positional notation. Should throw an error at parse time -create function namedparmcursor_test3() returns void as $$ -declare - c1 cursor (param1 int, param2 int) for select * from rc_test where a > param1 and b > param2; -begin - open c1(param2 := 20, 21); -end -$$ language plpgsql; - --- mixing named and positional: same as previous test, but param1 is duplicated -create function namedparmcursor_test4() returns void as $$ -declare - c1 cursor (param1 int, param2 int) for select * from rc_test where a > param1 and b > param2; -begin - open c1(20, param1 := 21); -end -$$ language plpgsql; - --- duplicate named parameter, should throw an error at parse time -create function namedparmcursor_test5() returns void as $$ -declare - c1 cursor (p1 int, p2 int) for - select * from tenk1 where thousand = p1 and tenthous = p2; -begin - open c1 (p2 := 77, p2 := 42); -end -$$ language plpgsql; - --- not enough parameters, should throw an error at parse time -create function namedparmcursor_test6() returns void as $$ -declare - c1 cursor (p1 int, p2 int) for - select * from tenk1 where thousand = p1 and tenthous = p2; -begin - open c1 (p2 := 77); -end -$$ language plpgsql; - --- division by zero runtime error, the context given in the error message --- should be sensible -create function namedparmcursor_test7() returns void as $$ -declare - c1 cursor (p1 int, p2 int) for - select * from tenk1 where thousand = p1 and tenthous = p2; -begin - open c1 (p2 := 77, p1 := 42/0); -end $$ language plpgsql; -select namedparmcursor_test7(); - --- check that line comments work correctly within the argument list (there --- is some special handling of this case in the code: the newline after the --- comment must be preserved when the argument-evaluating query is --- constructed, otherwise the comment effectively comments out the next --- argument, too) -create function namedparmcursor_test8() returns int4 as $$ -declare - c1 cursor (p1 int, p2 int) for - select count(*) from tenk1 where thousand = p1 and tenthous = p2; - n int4; -begin - open c1 (77 -- test - , 42); - fetch c1 into n; - return n; -end $$ language plpgsql; -select namedparmcursor_test8(); - --- cursor parameter name can match plpgsql variable or unreserved keyword -create function namedparmcursor_test9(p1 int) returns int4 as $$ -declare - c1 cursor (p1 int, p2 int, debug int) for - select count(*) from tenk1 where thousand = p1 and tenthous = p2 - and four = debug; - p2 int4 := 1006; - n int4; -begin - open c1 (p1 := p1, p2 := p2, debug := 2); - fetch c1 into n; - return n; -end $$ language plpgsql; -select namedparmcursor_test9(6); - --- --- tests for "raise" processing --- -create function raise_test1(int) returns int as $$ -begin - raise notice 'This message has too many parameters!', $1; - return $1; -end; -$$ language plpgsql; - -create function raise_test2(int) returns int as $$ -begin - raise notice 'This message has too few parameters: %, %, %', $1, $1; - return $1; -end; -$$ language plpgsql; - -create function raise_test3(int) returns int as $$ -begin - raise notice 'This message has no parameters (despite having %% signs in it)!'; - return $1; -end; -$$ language plpgsql; - -select raise_test3(1); - --- Test re-RAISE inside a nested exception block. This case is allowed --- by Oracle's PL/SQL but was handled differently by PG before 9.1. - -CREATE FUNCTION reraise_test() RETURNS void AS $$ -BEGIN - BEGIN - RAISE syntax_error; - EXCEPTION - WHEN syntax_error THEN - BEGIN - raise notice 'exception % thrown in inner block, reraising', sqlerrm; - RAISE; - EXCEPTION - WHEN OTHERS THEN - raise notice 'RIGHT - exception % caught in inner block', sqlerrm; - END; - END; -EXCEPTION - WHEN OTHERS THEN - raise notice 'WRONG - exception % caught in outer block', sqlerrm; -END; -$$ LANGUAGE plpgsql; - -SELECT reraise_test(); - --- --- reject function definitions that contain malformed SQL queries at --- compile-time, where possible --- -create function bad_sql1() returns int as $$ -declare a int; -begin - a := 5; - Johnny Yuma; - a := 10; - return a; -end$$ language plpgsql; - -create function bad_sql2() returns int as $$ -declare r record; -begin - for r in select I fought the law, the law won LOOP - raise notice 'in loop'; - end loop; - return 5; -end;$$ language plpgsql; - --- a RETURN expression is mandatory, except for void-returning --- functions, where it is not allowed -create function missing_return_expr() returns int as $$ -begin - return ; -end;$$ language plpgsql; - -create function void_return_expr() returns void as $$ -begin - return 5; -end;$$ language plpgsql; - --- VOID functions are allowed to omit RETURN -create function void_return_expr() returns void as $$ -begin - perform 2+2; -end;$$ language plpgsql; - -select void_return_expr(); - --- but ordinary functions are not -create function missing_return_expr() returns int as $$ -begin - perform 2+2; -end;$$ language plpgsql; - -select missing_return_expr(); - -drop function void_return_expr(); -drop function missing_return_expr(); - --- --- EXECUTE ... INTO test --- - -create table eifoo (i integer, y integer); -create type eitype as (i integer, y integer); - -create or replace function execute_into_test(varchar) returns record as $$ -declare - _r record; - _rt eifoo%rowtype; - _v eitype; - i int; - j int; - k int; -begin - execute 'insert into '||$1||' values(10,15)'; - execute 'select (row).* from (select row(10,1)::eifoo) s' into _r; - raise notice '% %', _r.i, _r.y; - execute 'select * from '||$1||' limit 1' into _rt; - raise notice '% %', _rt.i, _rt.y; - execute 'select *, 20 from '||$1||' limit 1' into i, j, k; - raise notice '% % %', i, j, k; - execute 'select 1,2' into _v; - return _v; -end; $$ language plpgsql; - -select execute_into_test('eifoo'); - -drop table eifoo cascade; -drop type eitype cascade; - --- --- SQLSTATE and SQLERRM test --- - -create function excpt_test1() returns void as $$ -begin - raise notice '% %', sqlstate, sqlerrm; -end; $$ language plpgsql; --- should fail: SQLSTATE and SQLERRM are only in defined EXCEPTION --- blocks -select excpt_test1(); - -create function excpt_test2() returns void as $$ -begin - begin - begin - raise notice '% %', sqlstate, sqlerrm; - end; - end; -end; $$ language plpgsql; --- should fail -select excpt_test2(); - -create function excpt_test3() returns void as $$ -begin - begin - raise exception 'user exception'; - exception when others then - raise notice 'caught exception % %', sqlstate, sqlerrm; - begin - raise notice '% %', sqlstate, sqlerrm; - perform 10/0; - exception - when substring_error then - -- this exception handler shouldn't be invoked - raise notice 'unexpected exception: % %', sqlstate, sqlerrm; - when division_by_zero then - raise notice 'caught exception % %', sqlstate, sqlerrm; - end; - raise notice '% %', sqlstate, sqlerrm; - end; -end; $$ language plpgsql; -select excpt_test3(); - -create function excpt_test4() returns text as $$ -begin - begin perform 1/0; - exception when others then return sqlerrm; end; -end; $$ language plpgsql; -select excpt_test4(); - -drop function excpt_test1(); -drop function excpt_test2(); -drop function excpt_test3(); -drop function excpt_test4(); - --- parameters of raise stmt can be expressions -create function raise_exprs() returns void as $$ -declare - a integer[] = '{10,20,30}'; - c varchar = 'xyz'; - i integer; -begin - i := 2; - raise notice '%; %; %; %; %; %', a, a[i], c, (select c || 'abc'), row(10,'aaa',NULL,30), NULL; -end;$$ language plpgsql; - -select raise_exprs(); -drop function raise_exprs(); - --- regression test: verify that multiple uses of same plpgsql datum within --- a SQL command all get mapped to the same $n parameter. The return value --- of the SELECT is not important, we only care that it doesn't fail with --- a complaint about an ungrouped column reference. -create function multi_datum_use(p1 int) returns bool as $$ -declare - x int; - y int; -begin - select into x,y unique1/p1, unique1/$1 from tenk1 group by unique1/p1; - return x = y; -end$$ language plpgsql; - -select multi_datum_use(42); - --- --- Test STRICT limiter in both planned and EXECUTE invocations. --- Note that a data-modifying query is quasi strict (disallow multi rows) --- by default in the planned case, but not in EXECUTE. --- - -create temp table foo (f1 int, f2 int); - -insert into foo values (1,2), (3,4); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should work - insert into foo values(5,6) returning * into x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should fail due to implicit strict - insert into foo values(7,8),(9,10) returning * into x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should work - execute 'insert into foo values(5,6) returning *' into x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- this should work since EXECUTE isn't as picky - execute 'insert into foo values(7,8),(9,10) returning *' into x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -select * from foo; - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should work - select * from foo where f1 = 3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should fail, no rows - select * from foo where f1 = 0 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should fail, too many rows - select * from foo where f1 > 3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should work - execute 'select * from foo where f1 = 3' into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should fail, no rows - execute 'select * from foo where f1 = 0' into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- should fail, too many rows - execute 'select * from foo where f1 > 3' into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -drop function stricttest(); - --- test printing parameters after failure due to STRICT - -set plpgsql.print_strict_params to true; - -create or replace function stricttest() returns void as $$ -declare -x record; -p1 int := 2; -p3 text := 'foo'; -begin - -- no rows - select * from foo where f1 = p1 and f1::text = p3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare -x record; -p1 int := 2; -p3 text := $a$'Valame Dios!' dijo Sancho; 'no le dije yo a vuestra merced que mirase bien lo que hacia?'$a$; -begin - -- no rows - select * from foo where f1 = p1 and f1::text = p3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare -x record; -p1 int := 2; -p3 text := 'foo'; -begin - -- too many rows - select * from foo where f1 > p1 or f1::text = p3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- too many rows, no params - select * from foo where f1 > 3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- no rows - execute 'select * from foo where f1 = $1 or f1::text = $2' using 0, 'foo' into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- too many rows - execute 'select * from foo where f1 > $1' using 1 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ -declare x record; -begin - -- too many rows, no parameters - execute 'select * from foo where f1 > 3' into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -create or replace function stricttest() returns void as $$ --- override the global -#print_strict_params off -declare -x record; -p1 int := 2; -p3 text := 'foo'; -begin - -- too many rows - select * from foo where f1 > p1 or f1::text = p3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - -reset plpgsql.print_strict_params; - -create or replace function stricttest() returns void as $$ --- override the global -#print_strict_params on -declare -x record; -p1 int := 2; -p3 text := 'foo'; -begin - -- too many rows - select * from foo where f1 > p1 or f1::text = p3 into strict x; - raise notice 'x.f1 = %, x.f2 = %', x.f1, x.f2; -end$$ language plpgsql; - -select stricttest(); - --- test warnings and errors -set plpgsql.extra_warnings to 'all'; -set plpgsql.extra_warnings to 'none'; -set plpgsql.extra_errors to 'all'; -set plpgsql.extra_errors to 'none'; - --- test warnings when shadowing a variable - -set plpgsql.extra_warnings to 'shadowed_variables'; - --- simple shadowing of input and output parameters -create or replace function shadowtest(in1 int) - returns table (out1 int) as $$ -declare -in1 int; -out1 int; -begin -end -$$ language plpgsql; -select shadowtest(1); - -set plpgsql.extra_warnings to 'shadowed_variables'; -select shadowtest(1); -create or replace function shadowtest(in1 int) - returns table (out1 int) as $$ -declare -in1 int; -out1 int; -begin -end -$$ language plpgsql; -select shadowtest(1); -drop function shadowtest(int); - --- shadowing in a second DECLARE block -create or replace function shadowtest() - returns void as $$ -declare -f1 int; -begin - declare - f1 int; - begin - end; -end$$ language plpgsql; -drop function shadowtest(); - --- several levels of shadowing -create or replace function shadowtest(in1 int) - returns void as $$ -declare -in1 int; -begin - declare - in1 int; - begin - end; -end$$ language plpgsql; -drop function shadowtest(int); - --- shadowing in cursor definitions -create or replace function shadowtest() - returns void as $$ -declare -f1 int; -c1 cursor (f1 int) for select 1; -begin -end$$ language plpgsql; -drop function shadowtest(); - --- test errors when shadowing a variable - -set plpgsql.extra_errors to 'shadowed_variables'; - -create or replace function shadowtest(f1 int) - returns boolean as $$ -declare f1 int; begin return 1; end $$ language plpgsql; - -select shadowtest(1); - -reset plpgsql.extra_errors; -reset plpgsql.extra_warnings; - -create or replace function shadowtest(f1 int) - returns boolean as $$ -declare f1 int; begin return 1; end $$ language plpgsql; - -select shadowtest(1); - --- runtime extra checks -set plpgsql.extra_warnings to 'too_many_rows'; - -do $$ -declare x int; -begin - select v from generate_series(1,2) g(v) into x; -end; -$$; - -set plpgsql.extra_errors to 'too_many_rows'; - -do $$ -declare x int; -begin - select v from generate_series(1,2) g(v) into x; -end; -$$; - -reset plpgsql.extra_errors; -reset plpgsql.extra_warnings; - -set plpgsql.extra_warnings to 'strict_multi_assignment'; - -do $$ -declare - x int; - y int; -begin - select 1 into x, y; - select 1,2 into x, y; - select 1,2,3 into x, y; -end -$$; - -set plpgsql.extra_errors to 'strict_multi_assignment'; - -do $$ -declare - x int; - y int; -begin - select 1 into x, y; - select 1,2 into x, y; - select 1,2,3 into x, y; -end -$$; - -create table test_01(a int, b int, c int); - -alter table test_01 drop column a; - --- the check is active only when source table is not empty -insert into test_01 values(10,20); - -do $$ -declare - x int; - y int; -begin - select * from test_01 into x, y; -- should be ok - raise notice 'ok'; - select * from test_01 into x; -- should to fail -end; -$$; - -do $$ -declare - t test_01; -begin - select 1, 2 into t; -- should be ok - raise notice 'ok'; - select 1, 2, 3 into t; -- should fail; -end; -$$; - -do $$ -declare - t test_01; -begin - select 1 into t; -- should fail; -end; -$$; - -drop table test_01; - -reset plpgsql.extra_errors; -reset plpgsql.extra_warnings; - --- test scrollable cursor support - -create function sc_test() returns setof integer as $$ -declare - c scroll cursor for select f1 from int4_tbl; - x integer; -begin - open c; - fetch last from c into x; - while found loop - return next x; - fetch prior from c into x; - end loop; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); - -create or replace function sc_test() returns setof integer as $$ -declare - c no scroll cursor for select f1 from int4_tbl; - x integer; -begin - open c; - fetch last from c into x; - while found loop - return next x; - fetch prior from c into x; - end loop; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); -- fails because of NO SCROLL specification - -create or replace function sc_test() returns setof integer as $$ -declare - c refcursor; - x integer; -begin - open c scroll for select f1 from int4_tbl; - fetch last from c into x; - while found loop - return next x; - fetch prior from c into x; - end loop; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); - -create or replace function sc_test() returns setof integer as $$ -declare - c refcursor; - x integer; -begin - open c scroll for execute 'select f1 from int4_tbl'; - fetch last from c into x; - while found loop - return next x; - fetch relative -2 from c into x; - end loop; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); - -create or replace function sc_test() returns setof integer as $$ -declare - c refcursor; - x integer; -begin - open c scroll for execute 'select f1 from int4_tbl'; - fetch last from c into x; - while found loop - return next x; - move backward 2 from c; - fetch relative -1 from c into x; - end loop; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); - -create or replace function sc_test() returns setof integer as $$ -declare - c cursor for select * from generate_series(1, 10); - x integer; -begin - open c; - loop - move relative 2 in c; - if not found then - exit; - end if; - fetch next from c into x; - if found then - return next x; - end if; - end loop; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); - -create or replace function sc_test() returns setof integer as $$ -declare - c cursor for select * from generate_series(1, 10); - x integer; -begin - open c; - move forward all in c; - fetch backward from c into x; - if found then - return next x; - end if; - close c; -end; -$$ language plpgsql; - -select * from sc_test(); - -drop function sc_test(); - --- test qualified variable names - -create function pl_qual_names (param1 int) returns void as $$ -<> -declare - param1 int := 1; -begin - <> - declare - param1 int := 2; - begin - raise notice 'param1 = %', param1; - raise notice 'pl_qual_names.param1 = %', pl_qual_names.param1; - raise notice 'outerblock.param1 = %', outerblock.param1; - raise notice 'innerblock.param1 = %', innerblock.param1; - end; -end; -$$ language plpgsql; - -select pl_qual_names(42); - -drop function pl_qual_names(int); - --- tests for RETURN QUERY -create function ret_query1(out int, out int) returns setof record as $$ -begin - $1 := -1; - $2 := -2; - return next; - return query select x + 1, x * 10 from generate_series(0, 10) s (x); - return next; -end; -$$ language plpgsql; - -select * from ret_query1(); - -create type record_type as (x text, y int, z boolean); - -create or replace function ret_query2(lim int) returns setof record_type as $$ -begin - return query select md5(s.x::text), s.x, s.x > 0 - from generate_series(-8, lim) s (x) where s.x % 2 = 0; -end; -$$ language plpgsql; - -select * from ret_query2(8); - --- test EXECUTE USING -create function exc_using(int, text) returns int as $$ -declare i int; -begin - for i in execute 'select * from generate_series(1,$1)' using $1+1 loop - raise notice '%', i; - end loop; - execute 'select $2 + $2*3 + length($1)' into i using $2,$1; - return i; -end -$$ language plpgsql; - -select exc_using(5, 'foobar'); - -drop function exc_using(int, text); - -create or replace function exc_using(int) returns void as $$ -declare - c refcursor; - i int; -begin - open c for execute 'select * from generate_series(1,$1)' using $1+1; - loop - fetch c into i; - exit when not found; - raise notice '%', i; - end loop; - close c; - return; -end; -$$ language plpgsql; - -select exc_using(5); - -drop function exc_using(int); - --- test FOR-over-cursor - -create or replace function forc01() returns void as $$ -declare - c cursor(r1 integer, r2 integer) - for select * from generate_series(r1,r2) i; - c2 cursor - for select * from generate_series(41,43) i; -begin - for r in c(5,7) loop - raise notice '% from %', r.i, c; - end loop; - -- again, to test if cursor was closed properly - for r in c(9,10) loop - raise notice '% from %', r.i, c; - end loop; - -- and test a parameterless cursor - for r in c2 loop - raise notice '% from %', r.i, c2; - end loop; - -- and try it with a hand-assigned name - raise notice 'after loop, c2 = %', c2; - c2 := 'special_name'; - for r in c2 loop - raise notice '% from %', r.i, c2; - end loop; - raise notice 'after loop, c2 = %', c2; - -- and try it with a generated name - -- (which we can't show in the output because it's variable) - c2 := null; - for r in c2 loop - raise notice '%', r.i; - end loop; - raise notice 'after loop, c2 = %', c2; - return; -end; -$$ language plpgsql; - -select forc01(); - --- try updating the cursor's current row - -create temp table forc_test as - select n as i, n as j from generate_series(1,10) n; - -create or replace function forc01() returns void as $$ -declare - c cursor for select * from forc_test; -begin - for r in c loop - raise notice '%, %', r.i, r.j; - update forc_test set i = i * 100, j = r.j * 2 where current of c; - end loop; -end; -$$ language plpgsql; - -select forc01(); - -select * from forc_test; - --- same, with a cursor whose portal name doesn't match variable name -create or replace function forc01() returns void as $$ -declare - c refcursor := 'fooled_ya'; - r record; -begin - open c for select * from forc_test; - loop - fetch c into r; - exit when not found; - raise notice '%, %', r.i, r.j; - update forc_test set i = i * 100, j = r.j * 2 where current of c; - end loop; -end; -$$ language plpgsql; - -select forc01(); - -select * from forc_test; - -drop function forc01(); - --- fail because cursor has no query bound to it - -create or replace function forc_bad() returns void as $$ -declare - c refcursor; -begin - for r in c loop - raise notice '%', r.i; - end loop; -end; -$$ language plpgsql; - --- test RETURN QUERY EXECUTE - -create or replace function return_dquery() -returns setof int as $$ -begin - return query execute 'select * from (values(10),(20)) f'; - return query execute 'select * from (values($1),($2)) f' using 40,50; -end; -$$ language plpgsql; - -select * from return_dquery(); - -drop function return_dquery(); - --- test RETURN QUERY with dropped columns - -create table tabwithcols(a int, b int, c int, d int); -insert into tabwithcols values(10,20,30,40),(50,60,70,80); - -create or replace function returnqueryf() -returns setof tabwithcols as $$ -begin - return query select * from tabwithcols; - return query execute 'select * from tabwithcols'; -end; -$$ language plpgsql; - -select * from returnqueryf(); - -alter table tabwithcols drop column b; - -select * from returnqueryf(); - -alter table tabwithcols drop column d; - -select * from returnqueryf(); - -alter table tabwithcols add column d int; - -select * from returnqueryf(); - -drop function returnqueryf(); -drop table tabwithcols; - --- --- Tests for composite-type results --- - -create type compostype as (x int, y varchar); - --- test: use of variable of composite type in return statement -create or replace function compos() returns compostype as $$ -declare - v compostype; -begin - v := (1, 'hello'); - return v; -end; -$$ language plpgsql; - -select compos(); - --- test: use of variable of record type in return statement -create or replace function compos() returns compostype as $$ -declare - v record; -begin - v := (1, 'hello'::varchar); - return v; -end; -$$ language plpgsql; - -select compos(); - --- test: use of row expr in return statement -create or replace function compos() returns compostype as $$ -begin - return (1, 'hello'::varchar); -end; -$$ language plpgsql; - -select compos(); - --- this does not work currently (no implicit casting) -create or replace function compos() returns compostype as $$ -begin - return (1, 'hello'); -end; -$$ language plpgsql; - -select compos(); - --- ... but this does -create or replace function compos() returns compostype as $$ -begin - return (1, 'hello')::compostype; -end; -$$ language plpgsql; - -select compos(); - -drop function compos(); - --- test: return a row expr as record. -create or replace function composrec() returns record as $$ -declare - v record; -begin - v := (1, 'hello'); - return v; -end; -$$ language plpgsql; - -select composrec(); - --- test: return row expr in return statement. -create or replace function composrec() returns record as $$ -begin - return (1, 'hello'); -end; -$$ language plpgsql; - -select composrec(); - -drop function composrec(); - --- test: row expr in RETURN NEXT statement. -create or replace function compos() returns setof compostype as $$ -begin - for i in 1..3 - loop - return next (1, 'hello'::varchar); - end loop; - return next null::compostype; - return next (2, 'goodbye')::compostype; -end; -$$ language plpgsql; - -select * from compos(); - -drop function compos(); - --- test: use invalid expr in return statement. -create or replace function compos() returns compostype as $$ -begin - return 1 + 1; -end; -$$ language plpgsql; - -select compos(); - --- RETURN variable is a different code path ... -create or replace function compos() returns compostype as $$ -declare x int := 42; -begin - return x; -end; -$$ language plpgsql; - -select * from compos(); - -drop function compos(); - --- test: invalid use of composite variable in scalar-returning function -create or replace function compos() returns int as $$ -declare - v compostype; -begin - v := (1, 'hello'); - return v; -end; -$$ language plpgsql; - -select compos(); - --- test: invalid use of composite expression in scalar-returning function -create or replace function compos() returns int as $$ -begin - return (1, 'hello')::compostype; -end; -$$ language plpgsql; - -select compos(); - -drop function compos(); -drop type compostype; - --- --- Tests for 8.4's new RAISE features --- - -create or replace function raise_test() returns void as $$ -begin - raise notice '% % %', 1, 2, 3 - using errcode = '55001', detail = 'some detail info', hint = 'some hint'; - raise '% % %', 1, 2, 3 - using errcode = 'division_by_zero', detail = 'some detail info'; -end; -$$ language plpgsql; - -select raise_test(); - --- Since we can't actually see the thrown SQLSTATE in default psql output, --- test it like this; this also tests re-RAISE - -create or replace function raise_test() returns void as $$ -begin - raise 'check me' - using errcode = 'division_by_zero', detail = 'some detail info'; - exception - when others then - raise notice 'SQLSTATE: % SQLERRM: %', sqlstate, sqlerrm; - raise; -end; -$$ language plpgsql; - -select raise_test(); - -create or replace function raise_test() returns void as $$ -begin - raise 'check me' - using errcode = '1234F', detail = 'some detail info'; - exception - when others then - raise notice 'SQLSTATE: % SQLERRM: %', sqlstate, sqlerrm; - raise; -end; -$$ language plpgsql; - -select raise_test(); - --- SQLSTATE specification in WHEN -create or replace function raise_test() returns void as $$ -begin - raise 'check me' - using errcode = '1234F', detail = 'some detail info'; - exception - when sqlstate '1234F' then - raise notice 'SQLSTATE: % SQLERRM: %', sqlstate, sqlerrm; - raise; -end; -$$ language plpgsql; - -select raise_test(); - -create or replace function raise_test() returns void as $$ -begin - raise division_by_zero using detail = 'some detail info'; - exception - when others then - raise notice 'SQLSTATE: % SQLERRM: %', sqlstate, sqlerrm; - raise; -end; -$$ language plpgsql; - -select raise_test(); - -create or replace function raise_test() returns void as $$ -begin - raise division_by_zero; -end; -$$ language plpgsql; - -select raise_test(); - -create or replace function raise_test() returns void as $$ -begin - raise sqlstate '1234F'; -end; -$$ language plpgsql; - -select raise_test(); - -create or replace function raise_test() returns void as $$ -begin - raise division_by_zero using message = 'custom' || ' message'; -end; -$$ language plpgsql; - -select raise_test(); - -create or replace function raise_test() returns void as $$ -begin - raise using message = 'custom' || ' message', errcode = '22012'; -end; -$$ language plpgsql; - -select raise_test(); - --- conflict on message -create or replace function raise_test() returns void as $$ -begin - raise notice 'some message' using message = 'custom' || ' message', errcode = '22012'; -end; -$$ language plpgsql; - -select raise_test(); - --- conflict on errcode -create or replace function raise_test() returns void as $$ -begin - raise division_by_zero using message = 'custom' || ' message', errcode = '22012'; -end; -$$ language plpgsql; - -select raise_test(); - --- nothing to re-RAISE -create or replace function raise_test() returns void as $$ -begin - raise; -end; -$$ language plpgsql; - -select raise_test(); - --- test access to exception data -create function zero_divide() returns int as $$ -declare v int := 0; -begin - return 10 / v; -end; -$$ language plpgsql; - -create or replace function raise_test() returns void as $$ -begin - raise exception 'custom exception' - using detail = 'some detail of custom exception', - hint = 'some hint related to custom exception'; -end; -$$ language plpgsql; - -create function stacked_diagnostics_test() returns void as $$ -declare _sqlstate text; - _message text; - _context text; -begin - perform zero_divide(); -exception when others then - get stacked diagnostics - _sqlstate = returned_sqlstate, - _message = message_text, - _context = pg_exception_context; - raise notice 'sqlstate: %, message: %, context: [%]', - _sqlstate, _message, replace(_context, E'\n', ' <- '); -end; -$$ language plpgsql; - -select stacked_diagnostics_test(); - -create or replace function stacked_diagnostics_test() returns void as $$ -declare _detail text; - _hint text; - _message text; -begin - perform raise_test(); -exception when others then - get stacked diagnostics - _message = message_text, - _detail = pg_exception_detail, - _hint = pg_exception_hint; - raise notice 'message: %, detail: %, hint: %', _message, _detail, _hint; -end; -$$ language plpgsql; - -select stacked_diagnostics_test(); - --- fail, cannot use stacked diagnostics statement outside handler -create or replace function stacked_diagnostics_test() returns void as $$ -declare _detail text; - _hint text; - _message text; -begin - get stacked diagnostics - _message = message_text, - _detail = pg_exception_detail, - _hint = pg_exception_hint; - raise notice 'message: %, detail: %, hint: %', _message, _detail, _hint; -end; -$$ language plpgsql; - -select stacked_diagnostics_test(); - -drop function zero_divide(); -drop function stacked_diagnostics_test(); - --- check cases where implicit SQLSTATE variable could be confused with --- SQLSTATE as a keyword, cf bug #5524 -create or replace function raise_test() returns void as $$ -begin - perform 1/0; -exception - when sqlstate '22012' then - raise notice using message = sqlstate; - raise sqlstate '22012' using message = 'substitute message'; -end; -$$ language plpgsql; - -select raise_test(); - -drop function raise_test(); - --- test passing column_name, constraint_name, datatype_name, table_name --- and schema_name error fields - -create or replace function stacked_diagnostics_test() returns void as $$ -declare _column_name text; - _constraint_name text; - _datatype_name text; - _table_name text; - _schema_name text; -begin - raise exception using - column = '>>some column name<<', - constraint = '>>some constraint name<<', - datatype = '>>some datatype name<<', - table = '>>some table name<<', - schema = '>>some schema name<<'; -exception when others then - get stacked diagnostics - _column_name = column_name, - _constraint_name = constraint_name, - _datatype_name = pg_datatype_name, - _table_name = table_name, - _schema_name = schema_name; - raise notice 'column %, constraint %, type %, table %, schema %', - _column_name, _constraint_name, _datatype_name, _table_name, _schema_name; -end; -$$ language plpgsql; - -select stacked_diagnostics_test(); - -drop function stacked_diagnostics_test(); - --- test variadic functions - -create or replace function vari(variadic int[]) -returns void as $$ -begin - for i in array_lower($1,1)..array_upper($1,1) loop - raise notice '%', $1[i]; - end loop; end; -$$ language plpgsql; - -select vari(1,2,3,4,5); -select vari(3,4,5); -select vari(variadic array[5,6,7]); - -drop function vari(int[]); - --- coercion test -create or replace function pleast(variadic numeric[]) -returns numeric as $$ -declare aux numeric = $1[array_lower($1,1)]; -begin - for i in array_lower($1,1)+1..array_upper($1,1) loop - if $1[i] < aux then aux := $1[i]; end if; - end loop; - return aux; -end; -$$ language plpgsql immutable strict; - -select pleast(10,1,2,3,-16); -select pleast(10.2,2.2,-1.1); -select pleast(10.2,10, -20); -select pleast(10,20, -1.0); - --- in case of conflict, non-variadic version is preferred -create or replace function pleast(numeric) -returns numeric as $$ -begin - raise notice 'non-variadic function called'; - return $1; -end; -$$ language plpgsql immutable strict; - -select pleast(10); - -drop function pleast(numeric[]); -drop function pleast(numeric); - --- test table functions - -create function tftest(int) returns table(a int, b int) as $$ -begin - return query select $1, $1+i from generate_series(1,5) g(i); -end; -$$ language plpgsql immutable strict; - -select * from tftest(10); - -create or replace function tftest(a1 int) returns table(a int, b int) as $$ -begin - a := a1; b := a1 + 1; - return next; - a := a1 * 10; b := a1 * 10 + 1; - return next; -end; -$$ language plpgsql immutable strict; - -select * from tftest(10); - -drop function tftest(int); - -create function rttest() -returns setof int as $$ -declare rc int; -begin - return query values(10),(20); - get diagnostics rc = row_count; - raise notice '% %', found, rc; - return query select * from (values(10),(20)) f(a) where false; - get diagnostics rc = row_count; - raise notice '% %', found, rc; - return query execute 'values(10),(20)'; - get diagnostics rc = row_count; - raise notice '% %', found, rc; - return query execute 'select * from (values(10),(20)) f(a) where false'; - get diagnostics rc = row_count; - raise notice '% %', found, rc; -end; -$$ language plpgsql; - -select * from rttest(); - --- check some error cases, too - -create or replace function rttest() -returns setof int as $$ -begin - return query select 10 into no_such_table; -end; -$$ language plpgsql; - -select * from rttest(); - -create or replace function rttest() -returns setof int as $$ -begin - return query execute 'select 10 into no_such_table'; -end; -$$ language plpgsql; - -select * from rttest(); - -select * from no_such_table; - -drop function rttest(); - --- Test for proper cleanup at subtransaction exit. This example --- exposed a bug in PG 8.2. - -CREATE FUNCTION leaker_1(fail BOOL) RETURNS INTEGER AS $$ -DECLARE - v_var INTEGER; -BEGIN - BEGIN - v_var := (leaker_2(fail)).error_code; - EXCEPTION - WHEN others THEN RETURN 0; - END; - RETURN 1; -END; -$$ LANGUAGE plpgsql; - -CREATE FUNCTION leaker_2(fail BOOL, OUT error_code INTEGER, OUT new_id INTEGER) - RETURNS RECORD AS $$ -BEGIN - IF fail THEN - RAISE EXCEPTION 'fail ...'; - END IF; - error_code := 1; - new_id := 1; - RETURN; -END; -$$ LANGUAGE plpgsql; - -SELECT * FROM leaker_1(false); -SELECT * FROM leaker_1(true); - -DROP FUNCTION leaker_1(bool); -DROP FUNCTION leaker_2(bool); - --- Test for appropriate cleanup of non-simple expression evaluations --- (bug in all versions prior to August 2010) - -CREATE FUNCTION nonsimple_expr_test() RETURNS text[] AS $$ -DECLARE - arr text[]; - lr text; - i integer; -BEGIN - arr := array[array['foo','bar'], array['baz', 'quux']]; - lr := 'fool'; - i := 1; - -- use sub-SELECTs to make expressions non-simple - arr[(SELECT i)][(SELECT i+1)] := (SELECT lr); - RETURN arr; -END; -$$ LANGUAGE plpgsql; - -SELECT nonsimple_expr_test(); - -DROP FUNCTION nonsimple_expr_test(); - -CREATE FUNCTION nonsimple_expr_test() RETURNS integer AS $$ -declare - i integer NOT NULL := 0; -begin - begin - i := (SELECT NULL::integer); -- should throw error - exception - WHEN OTHERS THEN - i := (SELECT 1::integer); - end; - return i; -end; -$$ LANGUAGE plpgsql; - -SELECT nonsimple_expr_test(); - -DROP FUNCTION nonsimple_expr_test(); - --- --- Test cases involving recursion and error recovery in simple expressions --- (bugs in all versions before October 2010). The problems are most --- easily exposed by mutual recursion between plpgsql and sql functions. --- - -create function recurse(float8) returns float8 as -$$ -begin - if ($1 > 0) then - return sql_recurse($1 - 1); - else - return $1; - end if; -end; -$$ language plpgsql; - --- "limit" is to prevent this from being inlined -create function sql_recurse(float8) returns float8 as -$$ select recurse($1) limit 1; $$ language sql; - -select recurse(10); - -create function error1(text) returns text language sql as -$$ SELECT relname::text FROM pg_class c WHERE c.oid = $1::regclass $$; - -create function error2(p_name_table text) returns text language plpgsql as $$ -begin - return error1(p_name_table); -end$$; - -BEGIN; -create table public.stuffs (stuff text); -SAVEPOINT a; -select error2('nonexistent.stuffs'); -ROLLBACK TO a; -select error2('public.stuffs'); -rollback; - -drop function error2(p_name_table text); -drop function error1(text); - --- Test for proper handling of cast-expression caching - -create function sql_to_date(integer) returns date as $$ -select $1::text::date -$$ language sql immutable strict; - -create cast (integer as date) with function sql_to_date(integer) as assignment; - -create function cast_invoker(integer) returns date as $$ -begin - return $1; -end$$ language plpgsql; - -select cast_invoker(20150717); -select cast_invoker(20150718); -- second call crashed in pre-release 9.5 - -begin; -select cast_invoker(20150717); -select cast_invoker(20150718); -savepoint s1; -select cast_invoker(20150718); -select cast_invoker(-1); -- fails -rollback to savepoint s1; -select cast_invoker(20150719); -select cast_invoker(20150720); -commit; - -drop function cast_invoker(integer); -drop function sql_to_date(integer) cascade; - --- Test handling of cast cache inside DO blocks --- (to check the original crash case, this must be a cast not previously --- used in this session) - -begin; -do $$ declare x text[]; begin x := '{1.23, 4.56}'::numeric[]; end $$; -do $$ declare x text[]; begin x := '{1.23, 4.56}'::numeric[]; end $$; -end; - --- Test for consistent reporting of error context - -create function fail() returns int language plpgsql as $$ -begin - return 1/0; -end -$$; - -select fail(); -select fail(); - -drop function fail(); - --- Test handling of string literals. - -set standard_conforming_strings = off; - -create or replace function strtest() returns text as $$ -begin - raise notice 'foo\\bar\041baz'; - return 'foo\\bar\041baz'; -end -$$ language plpgsql; - -select strtest(); - -create or replace function strtest() returns text as $$ -begin - raise notice E'foo\\bar\041baz'; - return E'foo\\bar\041baz'; -end -$$ language plpgsql; - -select strtest(); - -set standard_conforming_strings = on; - -create or replace function strtest() returns text as $$ -begin - raise notice 'foo\\bar\041baz\'; - return 'foo\\bar\041baz\'; -end -$$ language plpgsql; - -select strtest(); - -create or replace function strtest() returns text as $$ -begin - raise notice E'foo\\bar\041baz'; - return E'foo\\bar\041baz'; -end -$$ language plpgsql; - -select strtest(); - -drop function strtest(); - --- Test anonymous code blocks. - -DO $$ -DECLARE r record; -BEGIN - FOR r IN SELECT rtrim(roomno) AS roomno, comment FROM Room ORDER BY roomno - LOOP - RAISE NOTICE '%, %', r.roomno, r.comment; - END LOOP; -END$$; - --- these are to check syntax error reporting -DO LANGUAGE plpgsql $$begin return 1; end$$; - -DO $$ -DECLARE r record; -BEGIN - FOR r IN SELECT rtrim(roomno) AS roomno, foo FROM Room ORDER BY roomno - LOOP - RAISE NOTICE '%, %', r.roomno, r.comment; - END LOOP; -END$$; - --- Check handling of errors thrown from/into anonymous code blocks. -do $outer$ -begin - for i in 1..10 loop - begin - execute $ex$ - do $$ - declare x int = 0; - begin - x := 1 / x; - end; - $$; - $ex$; - exception when division_by_zero then - raise notice 'caught division by zero'; - end; - end loop; -end; -$outer$; - --- Check variable scoping -- a var is not available in its own or prior --- default expressions, but it is available in later ones. - -do $$ -declare x int := x + 1; -- error -begin - raise notice 'x = %', x; -end; -$$; - -do $$ -declare y int := x + 1; -- error - x int := 42; -begin - raise notice 'x = %, y = %', x, y; -end; -$$; - -do $$ -declare x int := 42; - y int := x + 1; -begin - raise notice 'x = %, y = %', x, y; -end; -$$; - -do $$ -declare x int := 42; -begin - declare y int := x + 1; - x int := x + 2; - z int := x * 10; - begin - raise notice 'x = %, y = %, z = %', x, y, z; - end; -end; -$$; - --- Check handling of conflicts between plpgsql vars and table columns. - -set plpgsql.variable_conflict = error; - -create function conflict_test() returns setof int8_tbl as $$ -declare r record; - q1 bigint := 42; -begin - for r in select q1,q2 from int8_tbl loop - return next r; - end loop; -end; -$$ language plpgsql; - -select * from conflict_test(); - -create or replace function conflict_test() returns setof int8_tbl as $$ -#variable_conflict use_variable -declare r record; - q1 bigint := 42; -begin - for r in select q1,q2 from int8_tbl loop - return next r; - end loop; -end; -$$ language plpgsql; - -select * from conflict_test(); - -create or replace function conflict_test() returns setof int8_tbl as $$ -#variable_conflict use_column -declare r record; - q1 bigint := 42; -begin - for r in select q1,q2 from int8_tbl loop - return next r; - end loop; -end; -$$ language plpgsql; - -select * from conflict_test(); - -drop function conflict_test(); - --- Check that an unreserved keyword can be used as a variable name - -create function unreserved_test() returns int as $$ -declare - forward int := 21; -begin - forward := forward * 2; - return forward; -end -$$ language plpgsql; - -select unreserved_test(); - -create or replace function unreserved_test() returns int as $$ -declare - return int := 42; -begin - return := return + 1; - return return; -end -$$ language plpgsql; - -select unreserved_test(); - -create or replace function unreserved_test() returns int as $$ -declare - comment int := 21; -begin - comment := comment * 2; - comment on function unreserved_test() is 'this is a test'; - return comment; -end -$$ language plpgsql; - -select unreserved_test(); - -select obj_description('unreserved_test()'::regprocedure, 'pg_proc'); - -drop function unreserved_test(); - --- --- Test FOREACH over arrays --- - -create function foreach_test(anyarray) -returns void as $$ -declare x int; -begin - foreach x in array $1 - loop - raise notice '%', x; - end loop; - end; -$$ language plpgsql; - -select foreach_test(ARRAY[1,2,3,4]); -select foreach_test(ARRAY[[1,2],[3,4]]); - -create or replace function foreach_test(anyarray) -returns void as $$ -declare x int; -begin - foreach x slice 1 in array $1 - loop - raise notice '%', x; - end loop; - end; -$$ language plpgsql; - --- should fail -select foreach_test(ARRAY[1,2,3,4]); -select foreach_test(ARRAY[[1,2],[3,4]]); - -create or replace function foreach_test(anyarray) -returns void as $$ -declare x int[]; -begin - foreach x slice 1 in array $1 - loop - raise notice '%', x; - end loop; - end; -$$ language plpgsql; - -select foreach_test(ARRAY[1,2,3,4]); -select foreach_test(ARRAY[[1,2],[3,4]]); - --- higher level of slicing -create or replace function foreach_test(anyarray) -returns void as $$ -declare x int[]; -begin - foreach x slice 2 in array $1 - loop - raise notice '%', x; - end loop; - end; -$$ language plpgsql; - --- should fail -select foreach_test(ARRAY[1,2,3,4]); --- ok -select foreach_test(ARRAY[[1,2],[3,4]]); -select foreach_test(ARRAY[[[1,2]],[[3,4]]]); - -create type xy_tuple AS (x int, y int); - --- iteration over array of records -create or replace function foreach_test(anyarray) -returns void as $$ -declare r record; -begin - foreach r in array $1 - loop - raise notice '%', r; - end loop; - end; -$$ language plpgsql; - -select foreach_test(ARRAY[(10,20),(40,69),(35,78)]::xy_tuple[]); -select foreach_test(ARRAY[[(10,20),(40,69)],[(35,78),(88,76)]]::xy_tuple[]); - -create or replace function foreach_test(anyarray) -returns void as $$ -declare x int; y int; -begin - foreach x, y in array $1 - loop - raise notice 'x = %, y = %', x, y; - end loop; - end; -$$ language plpgsql; - -select foreach_test(ARRAY[(10,20),(40,69),(35,78)]::xy_tuple[]); -select foreach_test(ARRAY[[(10,20),(40,69)],[(35,78),(88,76)]]::xy_tuple[]); - --- slicing over array of composite types -create or replace function foreach_test(anyarray) -returns void as $$ -declare x xy_tuple[]; -begin - foreach x slice 1 in array $1 - loop - raise notice '%', x; - end loop; - end; -$$ language plpgsql; - -select foreach_test(ARRAY[(10,20),(40,69),(35,78)]::xy_tuple[]); -select foreach_test(ARRAY[[(10,20),(40,69)],[(35,78),(88,76)]]::xy_tuple[]); - -drop function foreach_test(anyarray); -drop type xy_tuple; - --- --- Assorted tests for array subscript assignment --- - -create temp table rtype (id int, ar text[]); - -create function arrayassign1() returns text[] language plpgsql as $$ -declare - r record; -begin - r := row(12, '{foo,bar,baz}')::rtype; - r.ar[2] := 'replace'; - return r.ar; -end$$; - -select arrayassign1(); -select arrayassign1(); -- try again to exercise internal caching - -create domain orderedarray as int[2] - constraint sorted check (value[1] < value[2]); - -select '{1,2}'::orderedarray; -select '{2,1}'::orderedarray; -- fail - -create function testoa(x1 int, x2 int, x3 int) returns orderedarray -language plpgsql as $$ -declare res orderedarray; -begin - res := array[x1, x2]; - res[2] := x3; - return res; -end$$; - -select testoa(1,2,3); -select testoa(1,2,3); -- try again to exercise internal caching -select testoa(2,1,3); -- fail at initial assign -select testoa(1,2,1); -- fail at update - -drop function arrayassign1(); -drop function testoa(x1 int, x2 int, x3 int); - - --- --- Test handling of expanded arrays --- - -create function returns_rw_array(int) returns int[] -language plpgsql as $$ - declare r int[]; - begin r := array[$1, $1]; return r; end; -$$ stable; - -create function consumes_rw_array(int[]) returns int -language plpgsql as $$ - begin return $1[1]; end; -$$ stable; - -select consumes_rw_array(returns_rw_array(42)); - --- bug #14174 -explain (verbose, costs off) -select i, a from - (select returns_rw_array(1) as a offset 0) ss, - lateral consumes_rw_array(a) i; - -select i, a from - (select returns_rw_array(1) as a offset 0) ss, - lateral consumes_rw_array(a) i; - -explain (verbose, costs off) -select consumes_rw_array(a), a from returns_rw_array(1) a; - -select consumes_rw_array(a), a from returns_rw_array(1) a; - -explain (verbose, costs off) -select consumes_rw_array(a), a from - (values (returns_rw_array(1)), (returns_rw_array(2))) v(a); - -select consumes_rw_array(a), a from - (values (returns_rw_array(1)), (returns_rw_array(2))) v(a); - -do $$ -declare a int[] := array[1,2]; -begin - a := a || 3; - raise notice 'a = %', a; -end$$; - - --- --- Test access to call stack --- - -create function inner_func(int) -returns int as $$ -declare _context text; -begin - get diagnostics _context = pg_context; - raise notice '***%***', _context; - -- lets do it again, just for fun.. - get diagnostics _context = pg_context; - raise notice '***%***', _context; - raise notice 'lets make sure we didnt break anything'; - return 2 * $1; -end; -$$ language plpgsql; - -create or replace function outer_func(int) -returns int as $$ -declare - myresult int; -begin - raise notice 'calling down into inner_func()'; - myresult := inner_func($1); - raise notice 'inner_func() done'; - return myresult; -end; -$$ language plpgsql; - -create or replace function outer_outer_func(int) -returns int as $$ -declare - myresult int; -begin - raise notice 'calling down into outer_func()'; - myresult := outer_func($1); - raise notice 'outer_func() done'; - return myresult; -end; -$$ language plpgsql; - -select outer_outer_func(10); --- repeated call should to work -select outer_outer_func(20); - -drop function outer_outer_func(int); -drop function outer_func(int); -drop function inner_func(int); - --- access to call stack from exception -create function inner_func(int) -returns int as $$ -declare - _context text; - sx int := 5; -begin - begin - perform sx / 0; - exception - when division_by_zero then - get diagnostics _context = pg_context; - raise notice '***%***', _context; - end; - - -- lets do it again, just for fun.. - get diagnostics _context = pg_context; - raise notice '***%***', _context; - raise notice 'lets make sure we didnt break anything'; - return 2 * $1; -end; -$$ language plpgsql; - -create or replace function outer_func(int) -returns int as $$ -declare - myresult int; -begin - raise notice 'calling down into inner_func()'; - myresult := inner_func($1); - raise notice 'inner_func() done'; - return myresult; -end; -$$ language plpgsql; - -create or replace function outer_outer_func(int) -returns int as $$ -declare - myresult int; -begin - raise notice 'calling down into outer_func()'; - myresult := outer_func($1); - raise notice 'outer_func() done'; - return myresult; -end; -$$ language plpgsql; - -select outer_outer_func(10); --- repeated call should to work -select outer_outer_func(20); - -drop function outer_outer_func(int); -drop function outer_func(int); -drop function inner_func(int); - --- --- Test ASSERT --- - -do $$ -begin - assert 1=1; -- should succeed -end; -$$; - -do $$ -begin - assert 1=0; -- should fail -end; -$$; - -do $$ -begin - assert NULL; -- should fail -end; -$$; - --- check controlling GUC -set plpgsql.check_asserts = off; -do $$ -begin - assert 1=0; -- won't be tested -end; -$$; -reset plpgsql.check_asserts; - --- test custom message -do $$ -declare var text := 'some value'; -begin - assert 1=0, format('assertion failed, var = "%s"', var); -end; -$$; - --- ensure assertions are not trapped by 'others' -do $$ -begin - assert 1=0, 'unhandled assertion'; -exception when others then - null; -- do nothing -end; -$$; - --- Test use of plpgsql in a domain check constraint (cf. bug #14414) - -create function plpgsql_domain_check(val int) returns boolean as $$ -begin return val > 0; end -$$ language plpgsql immutable; - -create domain plpgsql_domain as integer check(plpgsql_domain_check(value)); - -do $$ -declare v_test plpgsql_domain; -begin - v_test := 1; -end; -$$; - -do $$ -declare v_test plpgsql_domain := 1; -begin - v_test := 0; -- fail -end; -$$; - --- Test handling of expanded array passed to a domain constraint (bug #14472) - -create function plpgsql_arr_domain_check(val int[]) returns boolean as $$ -begin return val[1] > 0; end -$$ language plpgsql immutable; - -create domain plpgsql_arr_domain as int[] check(plpgsql_arr_domain_check(value)); - -do $$ -declare v_test plpgsql_arr_domain; -begin - v_test := array[1]; - v_test := v_test || 2; -end; -$$; - -do $$ -declare v_test plpgsql_arr_domain := array[1]; -begin - v_test := 0 || v_test; -- fail -end; -$$; - --- --- test usage of transition tables in AFTER triggers --- - -CREATE TABLE transition_table_base (id int PRIMARY KEY, val text); - -CREATE FUNCTION transition_table_base_ins_func() - RETURNS trigger - LANGUAGE plpgsql -AS $$ -DECLARE - t text; - l text; -BEGIN - t = ''; - FOR l IN EXECUTE - $q$ - EXPLAIN (TIMING off, COSTS off, VERBOSE on) - SELECT * FROM newtable - $q$ LOOP - t = t || l || E'\n'; - END LOOP; - - RAISE INFO '%', t; - RETURN new; -END; -$$; - -CREATE TRIGGER transition_table_base_ins_trig - AFTER INSERT ON transition_table_base - REFERENCING OLD TABLE AS oldtable NEW TABLE AS newtable - FOR EACH STATEMENT - EXECUTE PROCEDURE transition_table_base_ins_func(); - -CREATE TRIGGER transition_table_base_ins_trig - AFTER INSERT ON transition_table_base - REFERENCING NEW TABLE AS newtable - FOR EACH STATEMENT - EXECUTE PROCEDURE transition_table_base_ins_func(); - -INSERT INTO transition_table_base VALUES (1, 'One'), (2, 'Two'); -INSERT INTO transition_table_base VALUES (3, 'Three'), (4, 'Four'); - -CREATE OR REPLACE FUNCTION transition_table_base_upd_func() - RETURNS trigger - LANGUAGE plpgsql -AS $$ -DECLARE - t text; - l text; -BEGIN - t = ''; - FOR l IN EXECUTE - $q$ - EXPLAIN (TIMING off, COSTS off, VERBOSE on) - SELECT * FROM oldtable ot FULL JOIN newtable nt USING (id) - $q$ LOOP - t = t || l || E'\n'; - END LOOP; - - RAISE INFO '%', t; - RETURN new; -END; -$$; - -CREATE TRIGGER transition_table_base_upd_trig - AFTER UPDATE ON transition_table_base - REFERENCING OLD TABLE AS oldtable NEW TABLE AS newtable - FOR EACH STATEMENT - EXECUTE PROCEDURE transition_table_base_upd_func(); - -UPDATE transition_table_base - SET val = '*' || val || '*' - WHERE id BETWEEN 2 AND 3; - -CREATE TABLE transition_table_level1 -( - level1_no serial NOT NULL , - level1_node_name varchar(255), - PRIMARY KEY (level1_no) -) WITHOUT OIDS; - -CREATE TABLE transition_table_level2 -( - level2_no serial NOT NULL , - parent_no int NOT NULL, - level1_node_name varchar(255), - PRIMARY KEY (level2_no) -) WITHOUT OIDS; - -CREATE TABLE transition_table_status -( - level int NOT NULL, - node_no int NOT NULL, - status int, - PRIMARY KEY (level, node_no) -) WITHOUT OIDS; - -CREATE FUNCTION transition_table_level1_ri_parent_del_func() - RETURNS TRIGGER - LANGUAGE plpgsql -AS $$ - DECLARE n bigint; - BEGIN - PERFORM FROM p JOIN transition_table_level2 c ON c.parent_no = p.level1_no; - IF FOUND THEN - RAISE EXCEPTION 'RI error'; - END IF; - RETURN NULL; - END; -$$; - -CREATE TRIGGER transition_table_level1_ri_parent_del_trigger - AFTER DELETE ON transition_table_level1 - REFERENCING OLD TABLE AS p - FOR EACH STATEMENT EXECUTE PROCEDURE - transition_table_level1_ri_parent_del_func(); - -CREATE FUNCTION transition_table_level1_ri_parent_upd_func() - RETURNS TRIGGER - LANGUAGE plpgsql -AS $$ - DECLARE - x int; - BEGIN - WITH p AS (SELECT level1_no, sum(delta) cnt - FROM (SELECT level1_no, 1 AS delta FROM i - UNION ALL - SELECT level1_no, -1 AS delta FROM d) w - GROUP BY level1_no - HAVING sum(delta) < 0) - SELECT level1_no - FROM p JOIN transition_table_level2 c ON c.parent_no = p.level1_no - INTO x; - IF FOUND THEN - RAISE EXCEPTION 'RI error'; - END IF; - RETURN NULL; - END; -$$; - -CREATE TRIGGER transition_table_level1_ri_parent_upd_trigger - AFTER UPDATE ON transition_table_level1 - REFERENCING OLD TABLE AS d NEW TABLE AS i - FOR EACH STATEMENT EXECUTE PROCEDURE - transition_table_level1_ri_parent_upd_func(); - -CREATE FUNCTION transition_table_level2_ri_child_insupd_func() - RETURNS TRIGGER - LANGUAGE plpgsql -AS $$ - BEGIN - PERFORM FROM i - LEFT JOIN transition_table_level1 p - ON p.level1_no IS NOT NULL AND p.level1_no = i.parent_no - WHERE p.level1_no IS NULL; - IF FOUND THEN - RAISE EXCEPTION 'RI error'; - END IF; - RETURN NULL; - END; -$$; - -CREATE TRIGGER transition_table_level2_ri_child_ins_trigger - AFTER INSERT ON transition_table_level2 - REFERENCING NEW TABLE AS i - FOR EACH STATEMENT EXECUTE PROCEDURE - transition_table_level2_ri_child_insupd_func(); - -CREATE TRIGGER transition_table_level2_ri_child_upd_trigger - AFTER UPDATE ON transition_table_level2 - REFERENCING NEW TABLE AS i - FOR EACH STATEMENT EXECUTE PROCEDURE - transition_table_level2_ri_child_insupd_func(); - --- create initial test data -INSERT INTO transition_table_level1 (level1_no) - SELECT generate_series(1,200); -ANALYZE transition_table_level1; - -INSERT INTO transition_table_level2 (level2_no, parent_no) - SELECT level2_no, level2_no / 50 + 1 AS parent_no - FROM generate_series(1,9999) level2_no; -ANALYZE transition_table_level2; - -INSERT INTO transition_table_status (level, node_no, status) - SELECT 1, level1_no, 0 FROM transition_table_level1; - -INSERT INTO transition_table_status (level, node_no, status) - SELECT 2, level2_no, 0 FROM transition_table_level2; -ANALYZE transition_table_status; - -INSERT INTO transition_table_level1(level1_no) - SELECT generate_series(201,1000); -ANALYZE transition_table_level1; - --- behave reasonably if someone tries to modify a transition table -CREATE FUNCTION transition_table_level2_bad_usage_func() - RETURNS TRIGGER - LANGUAGE plpgsql -AS $$ - BEGIN - INSERT INTO dx VALUES (1000000, 1000000, 'x'); - RETURN NULL; - END; -$$; - -CREATE TRIGGER transition_table_level2_bad_usage_trigger - AFTER DELETE ON transition_table_level2 - REFERENCING OLD TABLE AS dx - FOR EACH STATEMENT EXECUTE PROCEDURE - transition_table_level2_bad_usage_func(); - -DELETE FROM transition_table_level2 - WHERE level2_no BETWEEN 301 AND 305; - -DROP TRIGGER transition_table_level2_bad_usage_trigger - ON transition_table_level2; - --- attempt modifications which would break RI (should all fail) -DELETE FROM transition_table_level1 - WHERE level1_no = 25; - -UPDATE transition_table_level1 SET level1_no = -1 - WHERE level1_no = 30; - -INSERT INTO transition_table_level2 (level2_no, parent_no) - VALUES (10000, 10000); - -UPDATE transition_table_level2 SET parent_no = 2000 - WHERE level2_no = 40; - - --- attempt modifications which would not break RI (should all succeed) -DELETE FROM transition_table_level1 - WHERE level1_no BETWEEN 201 AND 1000; - -DELETE FROM transition_table_level1 - WHERE level1_no BETWEEN 100000000 AND 100000010; - -SELECT count(*) FROM transition_table_level1; - -DELETE FROM transition_table_level2 - WHERE level2_no BETWEEN 211 AND 220; - -SELECT count(*) FROM transition_table_level2; - -CREATE TABLE alter_table_under_transition_tables -( - id int PRIMARY KEY, - name text -); - -CREATE FUNCTION alter_table_under_transition_tables_upd_func() - RETURNS TRIGGER - LANGUAGE plpgsql -AS $$ -BEGIN - RAISE WARNING 'old table = %, new table = %', - (SELECT string_agg(id || '=' || name, ',') FROM d), - (SELECT string_agg(id || '=' || name, ',') FROM i); - RAISE NOTICE 'one = %', (SELECT 1 FROM alter_table_under_transition_tables LIMIT 1); - RETURN NULL; -END; -$$; - --- should fail, TRUNCATE is not compatible with transition tables -CREATE TRIGGER alter_table_under_transition_tables_upd_trigger - AFTER TRUNCATE OR UPDATE ON alter_table_under_transition_tables - REFERENCING OLD TABLE AS d NEW TABLE AS i - FOR EACH STATEMENT EXECUTE PROCEDURE - alter_table_under_transition_tables_upd_func(); - --- should work -CREATE TRIGGER alter_table_under_transition_tables_upd_trigger - AFTER UPDATE ON alter_table_under_transition_tables - REFERENCING OLD TABLE AS d NEW TABLE AS i - FOR EACH STATEMENT EXECUTE PROCEDURE - alter_table_under_transition_tables_upd_func(); - -INSERT INTO alter_table_under_transition_tables - VALUES (1, '1'), (2, '2'), (3, '3'); -UPDATE alter_table_under_transition_tables - SET name = name || name; - --- now change 'name' to an integer to see what happens... -ALTER TABLE alter_table_under_transition_tables - ALTER COLUMN name TYPE int USING name::integer; -UPDATE alter_table_under_transition_tables - SET name = (name::text || name::text)::integer; - --- now drop column 'name' -ALTER TABLE alter_table_under_transition_tables - DROP column name; -UPDATE alter_table_under_transition_tables - SET id = id; - --- --- Test multiple reference to a transition table --- - -CREATE TABLE multi_test (i int); -INSERT INTO multi_test VALUES (1); - -CREATE OR REPLACE FUNCTION multi_test_trig() RETURNS trigger -LANGUAGE plpgsql AS $$ -BEGIN - RAISE NOTICE 'count = %', (SELECT COUNT(*) FROM new_test); - RAISE NOTICE 'count union = %', - (SELECT COUNT(*) - FROM (SELECT * FROM new_test UNION ALL SELECT * FROM new_test) ss); - RETURN NULL; -END$$; - -CREATE TRIGGER my_trigger AFTER UPDATE ON multi_test - REFERENCING NEW TABLE AS new_test OLD TABLE as old_test - FOR EACH STATEMENT EXECUTE PROCEDURE multi_test_trig(); - -UPDATE multi_test SET i = i; - -DROP TABLE multi_test; -DROP FUNCTION multi_test_trig(); - --- --- Check type parsing and record fetching from partitioned tables --- - -CREATE TABLE partitioned_table (a int, b text) PARTITION BY LIST (a); -CREATE TABLE pt_part1 PARTITION OF partitioned_table FOR VALUES IN (1); -CREATE TABLE pt_part2 PARTITION OF partitioned_table FOR VALUES IN (2); - -INSERT INTO partitioned_table VALUES (1, 'Row 1'); -INSERT INTO partitioned_table VALUES (2, 'Row 2'); - -CREATE OR REPLACE FUNCTION get_from_partitioned_table(partitioned_table.a%type) -RETURNS partitioned_table AS $$ -DECLARE - a_val partitioned_table.a%TYPE; - result partitioned_table%ROWTYPE; -BEGIN - a_val := $1; - SELECT * INTO result FROM partitioned_table WHERE a = a_val; - RETURN result; -END; $$ LANGUAGE plpgsql; - -SELECT * FROM get_from_partitioned_table(1) AS t; - -CREATE OR REPLACE FUNCTION list_partitioned_table() -RETURNS SETOF partitioned_table.a%TYPE AS $$ -DECLARE - row partitioned_table%ROWTYPE; - a_val partitioned_table.a%TYPE; -BEGIN - FOR row IN SELECT * FROM partitioned_table ORDER BY a LOOP - a_val := row.a; - RETURN NEXT a_val; - END LOOP; - RETURN; -END; $$ LANGUAGE plpgsql; - -SELECT * FROM list_partitioned_table() AS t; - --- --- Check argument name is used instead of $n in error message --- -CREATE FUNCTION fx(x WSlot) RETURNS void AS $$ -BEGIN - GET DIAGNOSTICS x = ROW_COUNT; - RETURN; -END; $$ LANGUAGE plpgsql; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpolymorphism.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpolymorphism.sql deleted file mode 100644 index fa57db6559..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpolymorphism.sql +++ /dev/null @@ -1,1137 +0,0 @@ --- --- Tests for polymorphic SQL functions and aggregates based on them. --- Tests for other features related to function-calling have snuck in, too. --- - -create function polyf(x anyelement) returns anyelement as $$ - select x + 1 -$$ language sql; - -select polyf(42) as int, polyf(4.5) as num; -select polyf(point(3,4)); -- fail for lack of + operator - -drop function polyf(x anyelement); - -create function polyf(x anyelement) returns anyarray as $$ - select array[x + 1, x + 2] -$$ language sql; - -select polyf(42) as int, polyf(4.5) as num; - -drop function polyf(x anyelement); - -create function polyf(x anyarray) returns anyelement as $$ - select x[1] -$$ language sql; - -select polyf(array[2,4]) as int, polyf(array[4.5, 7.7]) as num; - -select polyf(stavalues1) from pg_statistic; -- fail, can't infer element type - -drop function polyf(x anyarray); - -create function polyf(x anyarray) returns anyarray as $$ - select x -$$ language sql; - -select polyf(array[2,4]) as int, polyf(array[4.5, 7.7]) as num; - -select polyf(stavalues1) from pg_statistic; -- fail, can't infer element type - -drop function polyf(x anyarray); - --- fail, can't infer type: -create function polyf(x anyelement) returns anyrange as $$ - select array[x + 1, x + 2] -$$ language sql; - -create function polyf(x anyrange) returns anyarray as $$ - select array[lower(x), upper(x)] -$$ language sql; - -select polyf(int4range(42, 49)) as int, polyf(float8range(4.5, 7.8)) as num; - -drop function polyf(x anyrange); - -create function polyf(x anycompatible, y anycompatible) returns anycompatiblearray as $$ - select array[x, y] -$$ language sql; - -select polyf(2, 4) as int, polyf(2, 4.5) as num; - -drop function polyf(x anycompatible, y anycompatible); - -create function polyf(x anycompatiblerange, y anycompatible, z anycompatible) returns anycompatiblearray as $$ - select array[lower(x), upper(x), y, z] -$$ language sql; - -select polyf(int4range(42, 49), 11, 2::smallint) as int, polyf(float8range(4.5, 7.8), 7.8, 11::real) as num; - -select polyf(int4range(42, 49), 11, 4.5) as fail; -- range type doesn't fit - -drop function polyf(x anycompatiblerange, y anycompatible, z anycompatible); - -create function polyf(x anycompatiblemultirange, y anycompatible, z anycompatible) returns anycompatiblearray as $$ - select array[lower(x), upper(x), y, z] -$$ language sql; - -select polyf(multirange(int4range(42, 49)), 11, 2::smallint) as int, polyf(multirange(float8range(4.5, 7.8)), 7.8, 11::real) as num; - -select polyf(multirange(int4range(42, 49)), 11, 4.5) as fail; -- range type doesn't fit - -drop function polyf(x anycompatiblemultirange, y anycompatible, z anycompatible); - --- fail, can't infer type: -create function polyf(x anycompatible) returns anycompatiblerange as $$ - select array[x + 1, x + 2] -$$ language sql; - -create function polyf(x anycompatiblerange, y anycompatiblearray) returns anycompatiblerange as $$ - select x -$$ language sql; - -select polyf(int4range(42, 49), array[11]) as int, polyf(float8range(4.5, 7.8), array[7]) as num; - -drop function polyf(x anycompatiblerange, y anycompatiblearray); - --- fail, can't infer type: -create function polyf(x anycompatible) returns anycompatiblemultirange as $$ - select array[x + 1, x + 2] -$$ language sql; - -create function polyf(x anycompatiblemultirange, y anycompatiblearray) returns anycompatiblemultirange as $$ - select x -$$ language sql; - -select polyf(multirange(int4range(42, 49)), array[11]) as int, polyf(multirange(float8range(4.5, 7.8)), array[7]) as num; - -drop function polyf(x anycompatiblemultirange, y anycompatiblearray); - -create function polyf(a anyelement, b anyarray, - c anycompatible, d anycompatible, - OUT x anyarray, OUT y anycompatiblearray) -as $$ - select a || b, array[c, d] -$$ language sql; - -select x, pg_typeof(x), y, pg_typeof(y) - from polyf(11, array[1, 2], 42, 34.5); -select x, pg_typeof(x), y, pg_typeof(y) - from polyf(11, array[1, 2], point(1,2), point(3,4)); -select x, pg_typeof(x), y, pg_typeof(y) - from polyf(11, '{1,2}', point(1,2), '(3,4)'); -select x, pg_typeof(x), y, pg_typeof(y) - from polyf(11, array[1, 2.2], 42, 34.5); -- fail - -drop function polyf(a anyelement, b anyarray, - c anycompatible, d anycompatible); - -create function polyf(anyrange) returns anymultirange -as 'select multirange($1);' language sql; - -select polyf(int4range(1,10)); -select polyf(null); - -drop function polyf(anyrange); - -create function polyf(anymultirange) returns anyelement -as 'select lower($1);' language sql; - -select polyf(int4multirange(int4range(1,10), int4range(20,30))); -select polyf(null); - -drop function polyf(anymultirange); - -create function polyf(anycompatiblerange) returns anycompatiblemultirange -as 'select multirange($1);' language sql; - -select polyf(int4range(1,10)); -select polyf(null); - -drop function polyf(anycompatiblerange); - -create function polyf(anymultirange) returns anyrange -as 'select range_merge($1);' language sql; - -select polyf(int4multirange(int4range(1,10), int4range(20,30))); -select polyf(null); - -drop function polyf(anymultirange); - -create function polyf(anycompatiblemultirange) returns anycompatiblerange -as 'select range_merge($1);' language sql; - -select polyf(int4multirange(int4range(1,10), int4range(20,30))); -select polyf(null); - -drop function polyf(anycompatiblemultirange); - -create function polyf(anycompatiblemultirange) returns anycompatible -as 'select lower($1);' language sql; - -select polyf(int4multirange(int4range(1,10), int4range(20,30))); -select polyf(null); - -drop function polyf(anycompatiblemultirange); - - --- --- Polymorphic aggregate tests --- --- Legend: ------------ --- A = type is ANY --- P = type is polymorphic --- N = type is non-polymorphic --- B = aggregate base type --- S = aggregate state type --- R = aggregate return type --- 1 = arg1 of a function --- 2 = arg2 of a function --- ag = aggregate --- tf = trans (state) function --- ff = final function --- rt = return type of a function --- -> = implies --- => = allowed --- !> = not allowed --- E = exists --- NE = not-exists --- --- Possible states: --- ---------------- --- B = (A || P || N) --- when (B = A) -> (tf2 = NE) --- S = (P || N) --- ff = (E || NE) --- tf1 = (P || N) --- tf2 = (NE || P || N) --- R = (P || N) - --- create functions for use as tf and ff with the needed combinations of --- argument polymorphism, but within the constraints of valid aggregate --- functions, i.e. tf arg1 and tf return type must match - --- polymorphic single arg transfn -CREATE FUNCTION stfp(anyarray) RETURNS anyarray AS -'select $1' LANGUAGE SQL; --- non-polymorphic single arg transfn -CREATE FUNCTION stfnp(int[]) RETURNS int[] AS -'select $1' LANGUAGE SQL; - --- dual polymorphic transfn -CREATE FUNCTION tfp(anyarray,anyelement) RETURNS anyarray AS -'select $1 || $2' LANGUAGE SQL; --- dual non-polymorphic transfn -CREATE FUNCTION tfnp(int[],int) RETURNS int[] AS -'select $1 || $2' LANGUAGE SQL; - --- arg1 only polymorphic transfn -CREATE FUNCTION tf1p(anyarray,int) RETURNS anyarray AS -'select $1' LANGUAGE SQL; --- arg2 only polymorphic transfn -CREATE FUNCTION tf2p(int[],anyelement) RETURNS int[] AS -'select $1' LANGUAGE SQL; - --- multi-arg polymorphic -CREATE FUNCTION sum3(anyelement,anyelement,anyelement) returns anyelement AS -'select $1+$2+$3' language sql strict; - --- finalfn polymorphic -CREATE FUNCTION ffp(anyarray) RETURNS anyarray AS -'select $1' LANGUAGE SQL; --- finalfn non-polymorphic -CREATE FUNCTION ffnp(int[]) returns int[] as -'select $1' LANGUAGE SQL; - --- Try to cover all the possible states: --- --- Note: in Cases 1 & 2, we are trying to return P. Therefore, if the transfn --- is stfnp, tfnp, or tf2p, we must use ffp as finalfn, because stfnp, tfnp, --- and tf2p do not return P. Conversely, in Cases 3 & 4, we are trying to --- return N. Therefore, if the transfn is stfp, tfp, or tf1p, we must use ffnp --- as finalfn, because stfp, tfp, and tf1p do not return N. --- --- Case1 (R = P) && (B = A) --- ------------------------ --- S tf1 --- ------- --- N N --- should CREATE -CREATE AGGREGATE myaggp01a(*) (SFUNC = stfnp, STYPE = int4[], - FINALFUNC = ffp, INITCOND = '{}'); - --- P N --- should ERROR: stfnp(anyarray) not matched by stfnp(int[]) -CREATE AGGREGATE myaggp02a(*) (SFUNC = stfnp, STYPE = anyarray, - FINALFUNC = ffp, INITCOND = '{}'); - --- N P --- should CREATE -CREATE AGGREGATE myaggp03a(*) (SFUNC = stfp, STYPE = int4[], - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp03b(*) (SFUNC = stfp, STYPE = int4[], - INITCOND = '{}'); - --- P P --- should ERROR: we have no way to resolve S -CREATE AGGREGATE myaggp04a(*) (SFUNC = stfp, STYPE = anyarray, - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp04b(*) (SFUNC = stfp, STYPE = anyarray, - INITCOND = '{}'); - - --- Case2 (R = P) && ((B = P) || (B = N)) --- ------------------------------------- --- S tf1 B tf2 --- ----------------------- --- N N N N --- should CREATE -CREATE AGGREGATE myaggp05a(BASETYPE = int, SFUNC = tfnp, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); - --- N N N P --- should CREATE -CREATE AGGREGATE myaggp06a(BASETYPE = int, SFUNC = tf2p, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); - --- N N P N --- should ERROR: tfnp(int[], anyelement) not matched by tfnp(int[], int) -CREATE AGGREGATE myaggp07a(BASETYPE = anyelement, SFUNC = tfnp, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); - --- N N P P --- should CREATE -CREATE AGGREGATE myaggp08a(BASETYPE = anyelement, SFUNC = tf2p, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); - --- N P N N --- should CREATE -CREATE AGGREGATE myaggp09a(BASETYPE = int, SFUNC = tf1p, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp09b(BASETYPE = int, SFUNC = tf1p, STYPE = int[], - INITCOND = '{}'); - --- N P N P --- should CREATE -CREATE AGGREGATE myaggp10a(BASETYPE = int, SFUNC = tfp, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp10b(BASETYPE = int, SFUNC = tfp, STYPE = int[], - INITCOND = '{}'); - --- N P P N --- should ERROR: tf1p(int[],anyelement) not matched by tf1p(anyarray,int) -CREATE AGGREGATE myaggp11a(BASETYPE = anyelement, SFUNC = tf1p, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp11b(BASETYPE = anyelement, SFUNC = tf1p, STYPE = int[], - INITCOND = '{}'); - --- N P P P --- should ERROR: tfp(int[],anyelement) not matched by tfp(anyarray,anyelement) -CREATE AGGREGATE myaggp12a(BASETYPE = anyelement, SFUNC = tfp, STYPE = int[], - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp12b(BASETYPE = anyelement, SFUNC = tfp, STYPE = int[], - INITCOND = '{}'); - --- P N N N --- should ERROR: tfnp(anyarray, int) not matched by tfnp(int[],int) -CREATE AGGREGATE myaggp13a(BASETYPE = int, SFUNC = tfnp, STYPE = anyarray, - FINALFUNC = ffp, INITCOND = '{}'); - --- P N N P --- should ERROR: tf2p(anyarray, int) not matched by tf2p(int[],anyelement) -CREATE AGGREGATE myaggp14a(BASETYPE = int, SFUNC = tf2p, STYPE = anyarray, - FINALFUNC = ffp, INITCOND = '{}'); - --- P N P N --- should ERROR: tfnp(anyarray, anyelement) not matched by tfnp(int[],int) -CREATE AGGREGATE myaggp15a(BASETYPE = anyelement, SFUNC = tfnp, - STYPE = anyarray, FINALFUNC = ffp, INITCOND = '{}'); - --- P N P P --- should ERROR: tf2p(anyarray, anyelement) not matched by tf2p(int[],anyelement) -CREATE AGGREGATE myaggp16a(BASETYPE = anyelement, SFUNC = tf2p, - STYPE = anyarray, FINALFUNC = ffp, INITCOND = '{}'); - --- P P N N --- should ERROR: we have no way to resolve S -CREATE AGGREGATE myaggp17a(BASETYPE = int, SFUNC = tf1p, STYPE = anyarray, - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp17b(BASETYPE = int, SFUNC = tf1p, STYPE = anyarray, - INITCOND = '{}'); - --- P P N P --- should ERROR: tfp(anyarray, int) not matched by tfp(anyarray, anyelement) -CREATE AGGREGATE myaggp18a(BASETYPE = int, SFUNC = tfp, STYPE = anyarray, - FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp18b(BASETYPE = int, SFUNC = tfp, STYPE = anyarray, - INITCOND = '{}'); - --- P P P N --- should ERROR: tf1p(anyarray, anyelement) not matched by tf1p(anyarray, int) -CREATE AGGREGATE myaggp19a(BASETYPE = anyelement, SFUNC = tf1p, - STYPE = anyarray, FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp19b(BASETYPE = anyelement, SFUNC = tf1p, - STYPE = anyarray, INITCOND = '{}'); - --- P P P P --- should CREATE -CREATE AGGREGATE myaggp20a(BASETYPE = anyelement, SFUNC = tfp, - STYPE = anyarray, FINALFUNC = ffp, INITCOND = '{}'); -CREATE AGGREGATE myaggp20b(BASETYPE = anyelement, SFUNC = tfp, - STYPE = anyarray, INITCOND = '{}'); - --- Case3 (R = N) && (B = A) --- ------------------------ --- S tf1 --- ------- --- N N --- should CREATE -CREATE AGGREGATE myaggn01a(*) (SFUNC = stfnp, STYPE = int4[], - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn01b(*) (SFUNC = stfnp, STYPE = int4[], - INITCOND = '{}'); - --- P N --- should ERROR: stfnp(anyarray) not matched by stfnp(int[]) -CREATE AGGREGATE myaggn02a(*) (SFUNC = stfnp, STYPE = anyarray, - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn02b(*) (SFUNC = stfnp, STYPE = anyarray, - INITCOND = '{}'); - --- N P --- should CREATE -CREATE AGGREGATE myaggn03a(*) (SFUNC = stfp, STYPE = int4[], - FINALFUNC = ffnp, INITCOND = '{}'); - --- P P --- should ERROR: ffnp(anyarray) not matched by ffnp(int[]) -CREATE AGGREGATE myaggn04a(*) (SFUNC = stfp, STYPE = anyarray, - FINALFUNC = ffnp, INITCOND = '{}'); - - --- Case4 (R = N) && ((B = P) || (B = N)) --- ------------------------------------- --- S tf1 B tf2 --- ----------------------- --- N N N N --- should CREATE -CREATE AGGREGATE myaggn05a(BASETYPE = int, SFUNC = tfnp, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn05b(BASETYPE = int, SFUNC = tfnp, STYPE = int[], - INITCOND = '{}'); - --- N N N P --- should CREATE -CREATE AGGREGATE myaggn06a(BASETYPE = int, SFUNC = tf2p, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn06b(BASETYPE = int, SFUNC = tf2p, STYPE = int[], - INITCOND = '{}'); - --- N N P N --- should ERROR: tfnp(int[], anyelement) not matched by tfnp(int[], int) -CREATE AGGREGATE myaggn07a(BASETYPE = anyelement, SFUNC = tfnp, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn07b(BASETYPE = anyelement, SFUNC = tfnp, STYPE = int[], - INITCOND = '{}'); - --- N N P P --- should CREATE -CREATE AGGREGATE myaggn08a(BASETYPE = anyelement, SFUNC = tf2p, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn08b(BASETYPE = anyelement, SFUNC = tf2p, STYPE = int[], - INITCOND = '{}'); - --- N P N N --- should CREATE -CREATE AGGREGATE myaggn09a(BASETYPE = int, SFUNC = tf1p, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); - --- N P N P --- should CREATE -CREATE AGGREGATE myaggn10a(BASETYPE = int, SFUNC = tfp, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); - --- N P P N --- should ERROR: tf1p(int[],anyelement) not matched by tf1p(anyarray,int) -CREATE AGGREGATE myaggn11a(BASETYPE = anyelement, SFUNC = tf1p, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); - --- N P P P --- should ERROR: tfp(int[],anyelement) not matched by tfp(anyarray,anyelement) -CREATE AGGREGATE myaggn12a(BASETYPE = anyelement, SFUNC = tfp, STYPE = int[], - FINALFUNC = ffnp, INITCOND = '{}'); - --- P N N N --- should ERROR: tfnp(anyarray, int) not matched by tfnp(int[],int) -CREATE AGGREGATE myaggn13a(BASETYPE = int, SFUNC = tfnp, STYPE = anyarray, - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn13b(BASETYPE = int, SFUNC = tfnp, STYPE = anyarray, - INITCOND = '{}'); - --- P N N P --- should ERROR: tf2p(anyarray, int) not matched by tf2p(int[],anyelement) -CREATE AGGREGATE myaggn14a(BASETYPE = int, SFUNC = tf2p, STYPE = anyarray, - FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn14b(BASETYPE = int, SFUNC = tf2p, STYPE = anyarray, - INITCOND = '{}'); - --- P N P N --- should ERROR: tfnp(anyarray, anyelement) not matched by tfnp(int[],int) -CREATE AGGREGATE myaggn15a(BASETYPE = anyelement, SFUNC = tfnp, - STYPE = anyarray, FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn15b(BASETYPE = anyelement, SFUNC = tfnp, - STYPE = anyarray, INITCOND = '{}'); - --- P N P P --- should ERROR: tf2p(anyarray, anyelement) not matched by tf2p(int[],anyelement) -CREATE AGGREGATE myaggn16a(BASETYPE = anyelement, SFUNC = tf2p, - STYPE = anyarray, FINALFUNC = ffnp, INITCOND = '{}'); -CREATE AGGREGATE myaggn16b(BASETYPE = anyelement, SFUNC = tf2p, - STYPE = anyarray, INITCOND = '{}'); - --- P P N N --- should ERROR: ffnp(anyarray) not matched by ffnp(int[]) -CREATE AGGREGATE myaggn17a(BASETYPE = int, SFUNC = tf1p, STYPE = anyarray, - FINALFUNC = ffnp, INITCOND = '{}'); - --- P P N P --- should ERROR: tfp(anyarray, int) not matched by tfp(anyarray, anyelement) -CREATE AGGREGATE myaggn18a(BASETYPE = int, SFUNC = tfp, STYPE = anyarray, - FINALFUNC = ffnp, INITCOND = '{}'); - --- P P P N --- should ERROR: tf1p(anyarray, anyelement) not matched by tf1p(anyarray, int) -CREATE AGGREGATE myaggn19a(BASETYPE = anyelement, SFUNC = tf1p, - STYPE = anyarray, FINALFUNC = ffnp, INITCOND = '{}'); - --- P P P P --- should ERROR: ffnp(anyarray) not matched by ffnp(int[]) -CREATE AGGREGATE myaggn20a(BASETYPE = anyelement, SFUNC = tfp, - STYPE = anyarray, FINALFUNC = ffnp, INITCOND = '{}'); - --- multi-arg polymorphic -CREATE AGGREGATE mysum2(anyelement,anyelement) (SFUNC = sum3, - STYPE = anyelement, INITCOND = '0'); - --- create test data for polymorphic aggregates -create temp table t(f1 int, f2 int[], f3 text); -insert into t values(1,array[1],'a'); -insert into t values(1,array[11],'b'); -insert into t values(1,array[111],'c'); -insert into t values(2,array[2],'a'); -insert into t values(2,array[22],'b'); -insert into t values(2,array[222],'c'); -insert into t values(3,array[3],'a'); -insert into t values(3,array[3],'b'); - --- test the successfully created polymorphic aggregates -select f3, myaggp01a(*) from t group by f3 order by f3; -select f3, myaggp03a(*) from t group by f3 order by f3; -select f3, myaggp03b(*) from t group by f3 order by f3; -select f3, myaggp05a(f1) from t group by f3 order by f3; -select f3, myaggp06a(f1) from t group by f3 order by f3; -select f3, myaggp08a(f1) from t group by f3 order by f3; -select f3, myaggp09a(f1) from t group by f3 order by f3; -select f3, myaggp09b(f1) from t group by f3 order by f3; -select f3, myaggp10a(f1) from t group by f3 order by f3; -select f3, myaggp10b(f1) from t group by f3 order by f3; -select f3, myaggp20a(f1) from t group by f3 order by f3; -select f3, myaggp20b(f1) from t group by f3 order by f3; -select f3, myaggn01a(*) from t group by f3 order by f3; -select f3, myaggn01b(*) from t group by f3 order by f3; -select f3, myaggn03a(*) from t group by f3 order by f3; -select f3, myaggn05a(f1) from t group by f3 order by f3; -select f3, myaggn05b(f1) from t group by f3 order by f3; -select f3, myaggn06a(f1) from t group by f3 order by f3; -select f3, myaggn06b(f1) from t group by f3 order by f3; -select f3, myaggn08a(f1) from t group by f3 order by f3; -select f3, myaggn08b(f1) from t group by f3 order by f3; -select f3, myaggn09a(f1) from t group by f3 order by f3; -select f3, myaggn10a(f1) from t group by f3 order by f3; -select mysum2(f1, f1 + 1) from t; - --- test inlining of polymorphic SQL functions -create function bleat(int) returns int as $$ -begin - raise notice 'bleat %', $1; - return $1; -end$$ language plpgsql; - -create function sql_if(bool, anyelement, anyelement) returns anyelement as $$ -select case when $1 then $2 else $3 end $$ language sql; - --- Note this would fail with integer overflow, never mind wrong bleat() output, --- if the CASE expression were not successfully inlined -select f1, sql_if(f1 > 0, bleat(f1), bleat(f1 + 1)) from int4_tbl; - -select q2, sql_if(q2 > 0, q2, q2 + 1) from int8_tbl; - --- another sort of polymorphic aggregate - -CREATE AGGREGATE array_larger_accum (anyarray) -( - sfunc = array_larger, - stype = anyarray, - initcond = '{}' -); - -SELECT array_larger_accum(i) -FROM (VALUES (ARRAY[1,2]), (ARRAY[3,4])) as t(i); - -SELECT array_larger_accum(i) -FROM (VALUES (ARRAY[row(1,2),row(3,4)]), (ARRAY[row(5,6),row(7,8)])) as t(i); - --- another kind of polymorphic aggregate - -create function add_group(grp anyarray, ad anyelement, size integer) - returns anyarray - as $$ -begin - if grp is null then - return array[ad]; - end if; - if array_upper(grp, 1) < size then - return grp || ad; - end if; - return grp; -end; -$$ - language plpgsql immutable; - -create aggregate build_group(anyelement, integer) ( - SFUNC = add_group, - STYPE = anyarray -); - -select build_group(q1,3) from int8_tbl; - --- this should fail because stype isn't compatible with arg -create aggregate build_group(int8, integer) ( - SFUNC = add_group, - STYPE = int2[] -); - --- but we can make a non-poly agg from a poly sfunc if types are OK -create aggregate build_group(int8, integer) ( - SFUNC = add_group, - STYPE = int8[] -); - --- check proper resolution of data types for polymorphic transfn/finalfn - -create function first_el_transfn(anyarray, anyelement) returns anyarray as -'select $1 || $2' language sql immutable; - -create function first_el(anyarray) returns anyelement as -'select $1[1]' language sql strict immutable; - -create aggregate first_el_agg_f8(float8) ( - SFUNC = array_append, - STYPE = float8[], - FINALFUNC = first_el -); - -create aggregate first_el_agg_any(anyelement) ( - SFUNC = first_el_transfn, - STYPE = anyarray, - FINALFUNC = first_el -); - -select first_el_agg_f8(x::float8) from generate_series(1,10) x; -select first_el_agg_any(x) from generate_series(1,10) x; -select first_el_agg_f8(x::float8) over(order by x) from generate_series(1,10) x; -select first_el_agg_any(x) over(order by x) from generate_series(1,10) x; - --- check that we can apply functions taking ANYARRAY to pg_stats -select distinct array_ndims(histogram_bounds) from pg_stats -where histogram_bounds is not null; - --- such functions must protect themselves if varying element type isn't OK --- (WHERE clause here is to avoid possibly getting a collation error instead) -select max(histogram_bounds) from pg_stats where tablename = 'pg_am'; - --- another corner case is the input functions for polymorphic pseudotypes -select array_in('{1,2,3}','int4'::regtype,-1); -- this has historically worked -select * from array_in('{1,2,3}','int4'::regtype,-1); -- this not -select anyrange_in('[10,20)','int4range'::regtype,-1); - --- test variadic polymorphic functions - -create function myleast(variadic anyarray) returns anyelement as $$ - select min($1[i]) from generate_subscripts($1,1) g(i) -$$ language sql immutable strict; - -select myleast(10, 1, 20, 33); -select myleast(1.1, 0.22, 0.55); -select myleast('z'::text); -select myleast(); -- fail - --- test with variadic call parameter -select myleast(variadic array[1,2,3,4,-1]); -select myleast(variadic array[1.1, -5.5]); - ---test with empty variadic call parameter -select myleast(variadic array[]::int[]); - --- an example with some ordinary arguments too -create function concat(text, variadic anyarray) returns text as $$ - select array_to_string($2, $1); -$$ language sql immutable strict; - -select concat('%', 1, 2, 3, 4, 5); -select concat('|', 'a'::text, 'b', 'c'); -select concat('|', variadic array[1,2,33]); -select concat('|', variadic array[]::int[]); - -drop function concat(text, anyarray); - --- mix variadic with anyelement -create function formarray(anyelement, variadic anyarray) returns anyarray as $$ - select array_prepend($1, $2); -$$ language sql immutable strict; - -select formarray(1,2,3,4,5); -select formarray(1.1, variadic array[1.2,55.5]); -select formarray(1.1, array[1.2,55.5]); -- fail without variadic -select formarray(1, 'x'::text); -- fail, type mismatch -select formarray(1, variadic array['x'::text]); -- fail, type mismatch - -drop function formarray(anyelement, variadic anyarray); - --- test pg_typeof() function -select pg_typeof(null); -- unknown -select pg_typeof(0); -- integer -select pg_typeof(0.0); -- numeric -select pg_typeof(1+1 = 2); -- boolean -select pg_typeof('x'); -- unknown -select pg_typeof('' || ''); -- text -select pg_typeof(pg_typeof(0)); -- regtype -select pg_typeof(array[1.2,55.5]); -- numeric[] -select pg_typeof(myleast(10, 1, 20, 33)); -- polymorphic input - --- test functions with default parameters - --- test basic functionality -create function dfunc(a int = 1, int = 2) returns int as $$ - select $1 + $2; -$$ language sql; - -select dfunc(); -select dfunc(10); -select dfunc(10, 20); -select dfunc(10, 20, 30); -- fail - -drop function dfunc(); -- fail -drop function dfunc(int); -- fail -drop function dfunc(int, int); -- ok - --- fail: defaults must be at end of argument list -create function dfunc(a int = 1, b int) returns int as $$ - select $1 + $2; -$$ language sql; - --- however, this should work: -create function dfunc(a int = 1, out sum int, b int = 2) as $$ - select $1 + $2; -$$ language sql; - -select dfunc(); - --- verify it lists properly -\df dfunc - -drop function dfunc(int, int); - --- check implicit coercion -create function dfunc(a int DEFAULT 1.0, int DEFAULT '-1') returns int as $$ - select $1 + $2; -$$ language sql; -select dfunc(); - -create function dfunc(a text DEFAULT 'Hello', b text DEFAULT 'World') returns text as $$ - select $1 || ', ' || $2; -$$ language sql; - -select dfunc(); -- fail: which dfunc should be called? int or text -select dfunc('Hi'); -- ok -select dfunc('Hi', 'City'); -- ok -select dfunc(0); -- ok -select dfunc(10, 20); -- ok - -drop function dfunc(int, int); -drop function dfunc(text, text); - -create function dfunc(int = 1, int = 2) returns int as $$ - select 2; -$$ language sql; - -create function dfunc(int = 1, int = 2, int = 3, int = 4) returns int as $$ - select 4; -$$ language sql; - --- Now, dfunc(nargs = 2) and dfunc(nargs = 4) are ambiguous when called --- with 0 to 2 arguments. - -select dfunc(); -- fail -select dfunc(1); -- fail -select dfunc(1, 2); -- fail -select dfunc(1, 2, 3); -- ok -select dfunc(1, 2, 3, 4); -- ok - -drop function dfunc(int, int); -drop function dfunc(int, int, int, int); - --- default values are not allowed for output parameters -create function dfunc(out int = 20) returns int as $$ - select 1; -$$ language sql; - --- polymorphic parameter test -create function dfunc(anyelement = 'World'::text) returns text as $$ - select 'Hello, ' || $1::text; -$$ language sql; - -select dfunc(); -select dfunc(0); -select dfunc(to_date('20081215','YYYYMMDD')); -select dfunc('City'::text); - -drop function dfunc(anyelement); - --- check defaults for variadics - -create function dfunc(a variadic int[]) returns int as -$$ select array_upper($1, 1) $$ language sql; - -select dfunc(); -- fail -select dfunc(10); -select dfunc(10,20); - -create or replace function dfunc(a variadic int[] default array[]::int[]) returns int as -$$ select array_upper($1, 1) $$ language sql; - -select dfunc(); -- now ok -select dfunc(10); -select dfunc(10,20); - --- can't remove the default once it exists -create or replace function dfunc(a variadic int[]) returns int as -$$ select array_upper($1, 1) $$ language sql; - -\df dfunc - -drop function dfunc(a variadic int[]); - --- Ambiguity should be reported only if there's not a better match available - -create function dfunc(int = 1, int = 2, int = 3) returns int as $$ - select 3; -$$ language sql; - -create function dfunc(int = 1, int = 2) returns int as $$ - select 2; -$$ language sql; - -create function dfunc(text) returns text as $$ - select $1; -$$ language sql; - --- dfunc(narg=2) and dfunc(narg=3) are ambiguous -select dfunc(1); -- fail - --- but this works since the ambiguous functions aren't preferred anyway -select dfunc('Hi'); - -drop function dfunc(int, int, int); -drop function dfunc(int, int); -drop function dfunc(text); - --- --- Tests for named- and mixed-notation function calling --- - -create function dfunc(a int, b int, c int = 0, d int = 0) - returns table (a int, b int, c int, d int) as $$ - select $1, $2, $3, $4; -$$ language sql; - -select (dfunc(10,20,30)).*; -select (dfunc(a := 10, b := 20, c := 30)).*; -select * from dfunc(a := 10, b := 20); -select * from dfunc(b := 10, a := 20); -select * from dfunc(0); -- fail -select * from dfunc(1,2); -select * from dfunc(1,2,c := 3); -select * from dfunc(1,2,d := 3); - -select * from dfunc(x := 20, b := 10, x := 30); -- fail, duplicate name -select * from dfunc(10, b := 20, 30); -- fail, named args must be last -select * from dfunc(x := 10, b := 20, c := 30); -- fail, unknown param -select * from dfunc(10, 10, a := 20); -- fail, a overlaps positional parameter -select * from dfunc(1,c := 2,d := 3); -- fail, no value for b - -drop function dfunc(int, int, int, int); - --- test with different parameter types -create function dfunc(a varchar, b numeric, c date = current_date) - returns table (a varchar, b numeric, c date) as $$ - select $1, $2, $3; -$$ language sql; - -select (dfunc('Hello World', 20, '2009-07-25'::date)).*; -select * from dfunc('Hello World', 20, '2009-07-25'::date); -select * from dfunc(c := '2009-07-25'::date, a := 'Hello World', b := 20); -select * from dfunc('Hello World', b := 20, c := '2009-07-25'::date); -select * from dfunc('Hello World', c := '2009-07-25'::date, b := 20); -select * from dfunc('Hello World', c := 20, b := '2009-07-25'::date); -- fail - -drop function dfunc(varchar, numeric, date); - --- test out parameters with named params -create function dfunc(a varchar = 'def a', out _a varchar, c numeric = NULL, out _c numeric) -returns record as $$ - select $1, $2; -$$ language sql; - -select (dfunc()).*; -select * from dfunc(); -select * from dfunc('Hello', 100); -select * from dfunc(a := 'Hello', c := 100); -select * from dfunc(c := 100, a := 'Hello'); -select * from dfunc('Hello'); -select * from dfunc('Hello', c := 100); -select * from dfunc(c := 100); - --- fail, can no longer change an input parameter's name -create or replace function dfunc(a varchar = 'def a', out _a varchar, x numeric = NULL, out _c numeric) -returns record as $$ - select $1, $2; -$$ language sql; - -create or replace function dfunc(a varchar = 'def a', out _a varchar, numeric = NULL, out _c numeric) -returns record as $$ - select $1, $2; -$$ language sql; - -drop function dfunc(varchar, numeric); - ---fail, named parameters are not unique -create function testpolym(a int, a int) returns int as $$ select 1;$$ language sql; -create function testpolym(int, out a int, out a int) returns int as $$ select 1;$$ language sql; -create function testpolym(out a int, inout a int) returns int as $$ select 1;$$ language sql; -create function testpolym(a int, inout a int) returns int as $$ select 1;$$ language sql; - --- valid -create function testpolym(a int, out a int) returns int as $$ select $1;$$ language sql; -select testpolym(37); -drop function testpolym(int); -create function testpolym(a int) returns table(a int) as $$ select $1;$$ language sql; -select * from testpolym(37); -drop function testpolym(int); - --- test polymorphic params and defaults -create function dfunc(a anyelement, b anyelement = null, flag bool = true) -returns anyelement as $$ - select case when $3 then $1 else $2 end; -$$ language sql; - -select dfunc(1,2); -select dfunc('a'::text, 'b'); -- positional notation with default - -select dfunc(a := 1, b := 2); -select dfunc(a := 'a'::text, b := 'b'); -select dfunc(a := 'a'::text, b := 'b', flag := false); -- named notation - -select dfunc(b := 'b'::text, a := 'a'); -- named notation with default -select dfunc(a := 'a'::text, flag := true); -- named notation with default -select dfunc(a := 'a'::text, flag := false); -- named notation with default -select dfunc(b := 'b'::text, a := 'a', flag := true); -- named notation - -select dfunc('a'::text, 'b', false); -- full positional notation -select dfunc('a'::text, 'b', flag := false); -- mixed notation -select dfunc('a'::text, 'b', true); -- full positional notation -select dfunc('a'::text, 'b', flag := true); -- mixed notation - --- ansi/sql syntax -select dfunc(a => 1, b => 2); -select dfunc(a => 'a'::text, b => 'b'); -select dfunc(a => 'a'::text, b => 'b', flag => false); -- named notation - -select dfunc(b => 'b'::text, a => 'a'); -- named notation with default -select dfunc(a => 'a'::text, flag => true); -- named notation with default -select dfunc(a => 'a'::text, flag => false); -- named notation with default -select dfunc(b => 'b'::text, a => 'a', flag => true); -- named notation - -select dfunc('a'::text, 'b', false); -- full positional notation -select dfunc('a'::text, 'b', flag => false); -- mixed notation -select dfunc('a'::text, 'b', true); -- full positional notation -select dfunc('a'::text, 'b', flag => true); -- mixed notation - --- this tests lexer edge cases around => -select dfunc(a =>-1); -select dfunc(a =>+1); -select dfunc(a =>/**/1); -select dfunc(a =>--comment to be removed by psql - 1); --- need DO to protect the -- from psql -do $$ - declare r integer; - begin - select dfunc(a=>-- comment - 1) into r; - raise info 'r = %', r; - end; -$$; - --- check reverse-listing of named-arg calls -CREATE VIEW dfview AS - SELECT q1, q2, - dfunc(q1,q2, flag := q1>q2) as c3, - dfunc(q1, flag := q1= 1000 AND oid < 3000 ORDER BY oid; - -RESET client_min_messages; - --- test proper begins here - -CREATE USER regress_priv_user1; -CREATE USER regress_priv_user2; -CREATE USER regress_priv_user3; -CREATE USER regress_priv_user4; -CREATE USER regress_priv_user5; -CREATE USER regress_priv_user5; -- duplicate -CREATE USER regress_priv_user6; -CREATE USER regress_priv_user7; -CREATE USER regress_priv_user8; -CREATE USER regress_priv_user9; -CREATE USER regress_priv_user10; -CREATE ROLE regress_priv_role; - -GRANT pg_read_all_data TO regress_priv_user6; -GRANT pg_write_all_data TO regress_priv_user7; -GRANT pg_read_all_settings TO regress_priv_user8 WITH ADMIN OPTION; - -SET SESSION AUTHORIZATION regress_priv_user8; -GRANT pg_read_all_settings TO regress_priv_user9 WITH ADMIN OPTION; - -SET SESSION AUTHORIZATION regress_priv_user9; -GRANT pg_read_all_settings TO regress_priv_user10; - -SET SESSION AUTHORIZATION regress_priv_user8; -REVOKE pg_read_all_settings FROM regress_priv_user10; -REVOKE ADMIN OPTION FOR pg_read_all_settings FROM regress_priv_user9; -REVOKE pg_read_all_settings FROM regress_priv_user9; - -RESET SESSION AUTHORIZATION; -REVOKE ADMIN OPTION FOR pg_read_all_settings FROM regress_priv_user8; - -SET SESSION AUTHORIZATION regress_priv_user8; -SET ROLE pg_read_all_settings; -RESET ROLE; - -RESET SESSION AUTHORIZATION; -REVOKE pg_read_all_settings FROM regress_priv_user8; - -DROP USER regress_priv_user10; -DROP USER regress_priv_user9; -DROP USER regress_priv_user8; - -CREATE GROUP regress_priv_group1; -CREATE GROUP regress_priv_group2 WITH USER regress_priv_user1, regress_priv_user2; - -ALTER GROUP regress_priv_group1 ADD USER regress_priv_user4; - -ALTER GROUP regress_priv_group2 ADD USER regress_priv_user2; -- duplicate -ALTER GROUP regress_priv_group2 DROP USER regress_priv_user2; -GRANT regress_priv_group2 TO regress_priv_user4 WITH ADMIN OPTION; - --- prepare non-leakproof function for later -CREATE FUNCTION leak(integer,integer) RETURNS boolean - AS 'int4lt' - LANGUAGE internal IMMUTABLE STRICT; -- but deliberately not LEAKPROOF -ALTER FUNCTION leak(integer,integer) OWNER TO regress_priv_user1; - --- test owner privileges - -GRANT regress_priv_role TO regress_priv_user1 WITH ADMIN OPTION GRANTED BY CURRENT_ROLE; -REVOKE ADMIN OPTION FOR regress_priv_role FROM regress_priv_user1 GRANTED BY foo; -- error -REVOKE ADMIN OPTION FOR regress_priv_role FROM regress_priv_user1 GRANTED BY regress_priv_user2; -- error -REVOKE ADMIN OPTION FOR regress_priv_role FROM regress_priv_user1 GRANTED BY CURRENT_USER; -REVOKE regress_priv_role FROM regress_priv_user1 GRANTED BY CURRENT_ROLE; -DROP ROLE regress_priv_role; - -SET SESSION AUTHORIZATION regress_priv_user1; -SELECT session_user, current_user; - -CREATE TABLE atest1 ( a int, b text ); -SELECT * FROM atest1; -INSERT INTO atest1 VALUES (1, 'one'); -DELETE FROM atest1; -UPDATE atest1 SET a = 1 WHERE b = 'blech'; -TRUNCATE atest1; -BEGIN; -LOCK atest1 IN ACCESS EXCLUSIVE MODE; -COMMIT; - -REVOKE ALL ON atest1 FROM PUBLIC; -SELECT * FROM atest1; - -GRANT ALL ON atest1 TO regress_priv_user2; -GRANT SELECT ON atest1 TO regress_priv_user3, regress_priv_user4; -SELECT * FROM atest1; - -CREATE TABLE atest2 (col1 varchar(10), col2 boolean); -GRANT SELECT ON atest2 TO regress_priv_user2; -GRANT UPDATE ON atest2 TO regress_priv_user3; -GRANT INSERT ON atest2 TO regress_priv_user4 GRANTED BY CURRENT_USER; -GRANT TRUNCATE ON atest2 TO regress_priv_user5 GRANTED BY CURRENT_ROLE; - -GRANT TRUNCATE ON atest2 TO regress_priv_user4 GRANTED BY regress_priv_user5; -- error - - -SET SESSION AUTHORIZATION regress_priv_user2; -SELECT session_user, current_user; - --- try various combinations of queries on atest1 and atest2 - -SELECT * FROM atest1; -- ok -SELECT * FROM atest2; -- ok -INSERT INTO atest1 VALUES (2, 'two'); -- ok -INSERT INTO atest2 VALUES ('foo', true); -- fail -INSERT INTO atest1 SELECT 1, b FROM atest1; -- ok -UPDATE atest1 SET a = 1 WHERE a = 2; -- ok -UPDATE atest2 SET col2 = NOT col2; -- fail -SELECT * FROM atest1 FOR UPDATE; -- ok -SELECT * FROM atest2 FOR UPDATE; -- fail -DELETE FROM atest2; -- fail -TRUNCATE atest2; -- fail -BEGIN; -LOCK atest2 IN ACCESS EXCLUSIVE MODE; -- fail -COMMIT; -COPY atest2 FROM stdin; -- fail -GRANT ALL ON atest1 TO PUBLIC; -- fail - --- checks in subquery, both ok -SELECT * FROM atest1 WHERE ( b IN ( SELECT col1 FROM atest2 ) ); -SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) ); - -SET SESSION AUTHORIZATION regress_priv_user6; -SELECT * FROM atest1; -- ok -SELECT * FROM atest2; -- ok -INSERT INTO atest2 VALUES ('foo', true); -- fail - -SET SESSION AUTHORIZATION regress_priv_user7; -SELECT * FROM atest1; -- fail -SELECT * FROM atest2; -- fail -INSERT INTO atest2 VALUES ('foo', true); -- ok -UPDATE atest2 SET col2 = true; -- ok -DELETE FROM atest2; -- ok - --- Make sure we are not able to modify system catalogs -UPDATE pg_catalog.pg_class SET relname = '123'; -- fail -DELETE FROM pg_catalog.pg_class; -- fail -UPDATE pg_toast.pg_toast_1213 SET chunk_id = 1; -- fail - -SET SESSION AUTHORIZATION regress_priv_user3; -SELECT session_user, current_user; - -SELECT * FROM atest1; -- ok -SELECT * FROM atest2; -- fail -INSERT INTO atest1 VALUES (2, 'two'); -- fail -INSERT INTO atest2 VALUES ('foo', true); -- fail -INSERT INTO atest1 SELECT 1, b FROM atest1; -- fail -UPDATE atest1 SET a = 1 WHERE a = 2; -- fail -UPDATE atest2 SET col2 = NULL; -- ok -UPDATE atest2 SET col2 = NOT col2; -- fails; requires SELECT on atest2 -UPDATE atest2 SET col2 = true FROM atest1 WHERE atest1.a = 5; -- ok -SELECT * FROM atest1 FOR UPDATE; -- fail -SELECT * FROM atest2 FOR UPDATE; -- fail -DELETE FROM atest2; -- fail -TRUNCATE atest2; -- fail -BEGIN; -LOCK atest2 IN ACCESS EXCLUSIVE MODE; -- ok -COMMIT; -COPY atest2 FROM stdin; -- fail - --- checks in subquery, both fail -SELECT * FROM atest1 WHERE ( b IN ( SELECT col1 FROM atest2 ) ); -SELECT * FROM atest2 WHERE ( col1 IN ( SELECT b FROM atest1 ) ); - -SET SESSION AUTHORIZATION regress_priv_user4; -COPY atest2 FROM stdin; -- ok -bar true -\. -SELECT * FROM atest1; -- ok - - --- test leaky-function protections in selfuncs - --- regress_priv_user1 will own a table and provide views for it. -SET SESSION AUTHORIZATION regress_priv_user1; - -CREATE TABLE atest12 as - SELECT x AS a, 10001 - x AS b FROM generate_series(1,10000) x; -CREATE INDEX ON atest12 (a); -CREATE INDEX ON atest12 (abs(a)); --- results below depend on having quite accurate stats for atest12, so... -ALTER TABLE atest12 SET (autovacuum_enabled = off); -SET default_statistics_target = 10000; -VACUUM ANALYZE atest12; -RESET default_statistics_target; - -CREATE OPERATOR <<< (procedure = leak, leftarg = integer, rightarg = integer, - restrict = scalarltsel); - --- views with leaky operator -CREATE VIEW atest12v AS - SELECT * FROM atest12 WHERE b <<< 5; -CREATE VIEW atest12sbv WITH (security_barrier=true) AS - SELECT * FROM atest12 WHERE b <<< 5; -GRANT SELECT ON atest12v TO PUBLIC; -GRANT SELECT ON atest12sbv TO PUBLIC; - --- This plan should use nestloop, knowing that few rows will be selected. -EXPLAIN (COSTS OFF) SELECT * FROM atest12v x, atest12v y WHERE x.a = y.b; - --- And this one. -EXPLAIN (COSTS OFF) SELECT * FROM atest12 x, atest12 y - WHERE x.a = y.b and abs(y.a) <<< 5; - --- This should also be a nestloop, but the security barrier forces the inner --- scan to be materialized -EXPLAIN (COSTS OFF) SELECT * FROM atest12sbv x, atest12sbv y WHERE x.a = y.b; - --- Check if regress_priv_user2 can break security. -SET SESSION AUTHORIZATION regress_priv_user2; - -CREATE FUNCTION leak2(integer,integer) RETURNS boolean - AS $$begin raise notice 'leak % %', $1, $2; return $1 > $2; end$$ - LANGUAGE plpgsql immutable; -CREATE OPERATOR >>> (procedure = leak2, leftarg = integer, rightarg = integer, - restrict = scalargtsel); - --- This should not show any "leak" notices before failing. -EXPLAIN (COSTS OFF) SELECT * FROM atest12 WHERE a >>> 0; - --- These plans should continue to use a nestloop, since they execute with the --- privileges of the view owner. -EXPLAIN (COSTS OFF) SELECT * FROM atest12v x, atest12v y WHERE x.a = y.b; -EXPLAIN (COSTS OFF) SELECT * FROM atest12sbv x, atest12sbv y WHERE x.a = y.b; - --- A non-security barrier view does not guard against information leakage. -EXPLAIN (COSTS OFF) SELECT * FROM atest12v x, atest12v y - WHERE x.a = y.b and abs(y.a) <<< 5; - --- But a security barrier view isolates the leaky operator. -EXPLAIN (COSTS OFF) SELECT * FROM atest12sbv x, atest12sbv y - WHERE x.a = y.b and abs(y.a) <<< 5; - --- Now regress_priv_user1 grants sufficient access to regress_priv_user2. -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT SELECT (a, b) ON atest12 TO PUBLIC; -SET SESSION AUTHORIZATION regress_priv_user2; - --- regress_priv_user2 should continue to get a good row estimate. -EXPLAIN (COSTS OFF) SELECT * FROM atest12v x, atest12v y WHERE x.a = y.b; - --- But not for this, due to lack of table-wide permissions needed --- to make use of the expression index's statistics. -EXPLAIN (COSTS OFF) SELECT * FROM atest12 x, atest12 y - WHERE x.a = y.b and abs(y.a) <<< 5; - --- clean up (regress_priv_user1's objects are all dropped later) -DROP FUNCTION leak2(integer, integer) CASCADE; - - --- groups - -SET SESSION AUTHORIZATION regress_priv_user3; -CREATE TABLE atest3 (one int, two int, three int); -GRANT DELETE ON atest3 TO GROUP regress_priv_group2; - -SET SESSION AUTHORIZATION regress_priv_user1; - -SELECT * FROM atest3; -- fail -DELETE FROM atest3; -- ok - -BEGIN; -RESET SESSION AUTHORIZATION; -ALTER ROLE regress_priv_user1 NOINHERIT; -SET SESSION AUTHORIZATION regress_priv_user1; -DELETE FROM atest3; -ROLLBACK; - --- views - -SET SESSION AUTHORIZATION regress_priv_user3; - -CREATE VIEW atestv1 AS SELECT * FROM atest1; -- ok -/* The next *should* fail, but it's not implemented that way yet. */ -CREATE VIEW atestv2 AS SELECT * FROM atest2; -CREATE VIEW atestv3 AS SELECT * FROM atest3; -- ok -/* Empty view is a corner case that failed in 9.2. */ -CREATE VIEW atestv0 AS SELECT 0 as x WHERE false; -- ok - -SELECT * FROM atestv1; -- ok -SELECT * FROM atestv2; -- fail -GRANT SELECT ON atestv1, atestv3 TO regress_priv_user4; -GRANT SELECT ON atestv2 TO regress_priv_user2; - -SET SESSION AUTHORIZATION regress_priv_user4; - -SELECT * FROM atestv1; -- ok -SELECT * FROM atestv2; -- fail -SELECT * FROM atestv3; -- ok -SELECT * FROM atestv0; -- fail - --- Appendrels excluded by constraints failed to check permissions in 8.4-9.2. -select * from - ((select a.q1 as x from int8_tbl a offset 0) - union all - (select b.q2 as x from int8_tbl b offset 0)) ss -where false; - -set constraint_exclusion = on; -select * from - ((select a.q1 as x, random() from int8_tbl a where q1 > 0) - union all - (select b.q2 as x, random() from int8_tbl b where q2 > 0)) ss -where x < 0; -reset constraint_exclusion; - -CREATE VIEW atestv4 AS SELECT * FROM atestv3; -- nested view -SELECT * FROM atestv4; -- ok -GRANT SELECT ON atestv4 TO regress_priv_user2; - -SET SESSION AUTHORIZATION regress_priv_user2; - --- Two complex cases: - -SELECT * FROM atestv3; -- fail -SELECT * FROM atestv4; -- ok (even though regress_priv_user2 cannot access underlying atestv3) - -SELECT * FROM atest2; -- ok -SELECT * FROM atestv2; -- fail (even though regress_priv_user2 can access underlying atest2) - --- Test column level permissions - -SET SESSION AUTHORIZATION regress_priv_user1; -CREATE TABLE atest5 (one int, two int unique, three int, four int unique); -CREATE TABLE atest6 (one int, two int, blue int); -GRANT SELECT (one), INSERT (two), UPDATE (three) ON atest5 TO regress_priv_user4; -GRANT ALL (one) ON atest5 TO regress_priv_user3; - -INSERT INTO atest5 VALUES (1,2,3); - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT * FROM atest5; -- fail -SELECT one FROM atest5; -- ok -COPY atest5 (one) TO stdout; -- ok -SELECT two FROM atest5; -- fail -COPY atest5 (two) TO stdout; -- fail -SELECT atest5 FROM atest5; -- fail -COPY atest5 (one,two) TO stdout; -- fail -SELECT 1 FROM atest5; -- ok -SELECT 1 FROM atest5 a JOIN atest5 b USING (one); -- ok -SELECT 1 FROM atest5 a JOIN atest5 b USING (two); -- fail -SELECT 1 FROM atest5 a NATURAL JOIN atest5 b; -- fail -SELECT * FROM (atest5 a JOIN atest5 b USING (one)) j; -- fail -SELECT j.* FROM (atest5 a JOIN atest5 b USING (one)) j; -- fail -SELECT (j.*) IS NULL FROM (atest5 a JOIN atest5 b USING (one)) j; -- fail -SELECT one FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)) j; -- ok -SELECT j.one FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)) j; -- ok -SELECT two FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)) j; -- fail -SELECT j.two FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)) j; -- fail -SELECT y FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)) j; -- fail -SELECT j.y FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)) j; -- fail -SELECT * FROM (atest5 a JOIN atest5 b USING (one)); -- fail -SELECT a.* FROM (atest5 a JOIN atest5 b USING (one)); -- fail -SELECT (a.*) IS NULL FROM (atest5 a JOIN atest5 b USING (one)); -- fail -SELECT two FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT a.two FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT y FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT b.y FROM (atest5 a JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT y FROM (atest5 a LEFT JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT b.y FROM (atest5 a LEFT JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT y FROM (atest5 a FULL JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT b.y FROM (atest5 a FULL JOIN atest5 b(one,x,y,z) USING (one)); -- fail -SELECT 1 FROM atest5 WHERE two = 2; -- fail -SELECT * FROM atest1, atest5; -- fail -SELECT atest1.* FROM atest1, atest5; -- ok -SELECT atest1.*,atest5.one FROM atest1, atest5; -- ok -SELECT atest1.*,atest5.one FROM atest1 JOIN atest5 ON (atest1.a = atest5.two); -- fail -SELECT atest1.*,atest5.one FROM atest1 JOIN atest5 ON (atest1.a = atest5.one); -- ok -SELECT one, two FROM atest5; -- fail - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT SELECT (one,two) ON atest6 TO regress_priv_user4; - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT one, two FROM atest5 NATURAL JOIN atest6; -- fail still - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT SELECT (two) ON atest5 TO regress_priv_user4; - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT one, two FROM atest5 NATURAL JOIN atest6; -- ok now - --- test column-level privileges for INSERT and UPDATE -INSERT INTO atest5 (two) VALUES (3); -- ok -COPY atest5 FROM stdin; -- fail -COPY atest5 (two) FROM stdin; -- ok -1 -\. -INSERT INTO atest5 (three) VALUES (4); -- fail -INSERT INTO atest5 VALUES (5,5,5); -- fail -UPDATE atest5 SET three = 10; -- ok -UPDATE atest5 SET one = 8; -- fail -UPDATE atest5 SET three = 5, one = 2; -- fail --- Check that column level privs are enforced in RETURNING --- Ok. -INSERT INTO atest5(two) VALUES (6) ON CONFLICT (two) DO UPDATE set three = 10; --- Error. No SELECT on column three. -INSERT INTO atest5(two) VALUES (6) ON CONFLICT (two) DO UPDATE set three = 10 RETURNING atest5.three; --- Ok. May SELECT on column "one": -INSERT INTO atest5(two) VALUES (6) ON CONFLICT (two) DO UPDATE set three = 10 RETURNING atest5.one; --- Check that column level privileges are enforced for EXCLUDED --- Ok. we may select one -INSERT INTO atest5(two) VALUES (6) ON CONFLICT (two) DO UPDATE set three = EXCLUDED.one; --- Error. No select rights on three -INSERT INTO atest5(two) VALUES (6) ON CONFLICT (two) DO UPDATE set three = EXCLUDED.three; -INSERT INTO atest5(two) VALUES (6) ON CONFLICT (two) DO UPDATE set one = 8; -- fails (due to UPDATE) -INSERT INTO atest5(three) VALUES (4) ON CONFLICT (two) DO UPDATE set three = 10; -- fails (due to INSERT) - --- Check that the columns in the inference require select privileges -INSERT INTO atest5(four) VALUES (4); -- fail - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT INSERT (four) ON atest5 TO regress_priv_user4; -SET SESSION AUTHORIZATION regress_priv_user4; - -INSERT INTO atest5(four) VALUES (4) ON CONFLICT (four) DO UPDATE set three = 3; -- fails (due to SELECT) -INSERT INTO atest5(four) VALUES (4) ON CONFLICT ON CONSTRAINT atest5_four_key DO UPDATE set three = 3; -- fails (due to SELECT) -INSERT INTO atest5(four) VALUES (4); -- ok - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT SELECT (four) ON atest5 TO regress_priv_user4; -SET SESSION AUTHORIZATION regress_priv_user4; - -INSERT INTO atest5(four) VALUES (4) ON CONFLICT (four) DO UPDATE set three = 3; -- ok -INSERT INTO atest5(four) VALUES (4) ON CONFLICT ON CONSTRAINT atest5_four_key DO UPDATE set three = 3; -- ok - -SET SESSION AUTHORIZATION regress_priv_user1; -REVOKE ALL (one) ON atest5 FROM regress_priv_user4; -GRANT SELECT (one,two,blue) ON atest6 TO regress_priv_user4; - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT one FROM atest5; -- fail -UPDATE atest5 SET one = 1; -- fail -SELECT atest6 FROM atest6; -- ok -COPY atest6 TO stdout; -- ok - --- test column privileges with MERGE -SET SESSION AUTHORIZATION regress_priv_user1; -CREATE TABLE mtarget (a int, b text); -CREATE TABLE msource (a int, b text); -INSERT INTO mtarget VALUES (1, 'init1'), (2, 'init2'); -INSERT INTO msource VALUES (1, 'source1'), (2, 'source2'), (3, 'source3'); - -GRANT SELECT (a) ON msource TO regress_priv_user4; -GRANT SELECT (a) ON mtarget TO regress_priv_user4; -GRANT INSERT (a,b) ON mtarget TO regress_priv_user4; -GRANT UPDATE (b) ON mtarget TO regress_priv_user4; - -SET SESSION AUTHORIZATION regress_priv_user4; - --- --- test source privileges --- - --- fail (no SELECT priv on s.b) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = s.b -WHEN NOT MATCHED THEN - INSERT VALUES (a, NULL); - --- fail (s.b used in the INSERTed values) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = 'x' -WHEN NOT MATCHED THEN - INSERT VALUES (a, b); - --- fail (s.b used in the WHEN quals) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED AND s.b = 'x' THEN - UPDATE SET b = 'x' -WHEN NOT MATCHED THEN - INSERT VALUES (a, NULL); - --- this should be ok since only s.a is accessed -BEGIN; -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = 'ok' -WHEN NOT MATCHED THEN - INSERT VALUES (a, NULL); -ROLLBACK; - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT SELECT (b) ON msource TO regress_priv_user4; -SET SESSION AUTHORIZATION regress_priv_user4; - --- should now be ok -BEGIN; -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = s.b -WHEN NOT MATCHED THEN - INSERT VALUES (a, b); -ROLLBACK; - --- --- test target privileges --- - --- fail (no SELECT priv on t.b) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = t.b -WHEN NOT MATCHED THEN - INSERT VALUES (a, NULL); - --- fail (no UPDATE on t.a) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = s.b, a = t.a + 1 -WHEN NOT MATCHED THEN - INSERT VALUES (a, b); - --- fail (no SELECT on t.b) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED AND t.b IS NOT NULL THEN - UPDATE SET b = s.b -WHEN NOT MATCHED THEN - INSERT VALUES (a, b); - --- ok -BEGIN; -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED THEN - UPDATE SET b = s.b; -ROLLBACK; - --- fail (no DELETE) -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED AND t.b IS NOT NULL THEN - DELETE; - --- grant delete privileges -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT DELETE ON mtarget TO regress_priv_user4; --- should be ok now -BEGIN; -MERGE INTO mtarget t USING msource s ON t.a = s.a -WHEN MATCHED AND t.b IS NOT NULL THEN - DELETE; -ROLLBACK; - --- check error reporting with column privs -SET SESSION AUTHORIZATION regress_priv_user1; -CREATE TABLE t1 (c1 int, c2 int, c3 int check (c3 < 5), primary key (c1, c2)); -GRANT SELECT (c1) ON t1 TO regress_priv_user2; -GRANT INSERT (c1, c2, c3) ON t1 TO regress_priv_user2; -GRANT UPDATE (c1, c2, c3) ON t1 TO regress_priv_user2; - --- seed data -INSERT INTO t1 VALUES (1, 1, 1); -INSERT INTO t1 VALUES (1, 2, 1); -INSERT INTO t1 VALUES (2, 1, 2); -INSERT INTO t1 VALUES (2, 2, 2); -INSERT INTO t1 VALUES (3, 1, 3); - -SET SESSION AUTHORIZATION regress_priv_user2; -INSERT INTO t1 (c1, c2) VALUES (1, 1); -- fail, but row not shown -UPDATE t1 SET c2 = 1; -- fail, but row not shown -INSERT INTO t1 (c1, c2) VALUES (null, null); -- fail, but see columns being inserted -INSERT INTO t1 (c3) VALUES (null); -- fail, but see columns being inserted or have SELECT -INSERT INTO t1 (c1) VALUES (5); -- fail, but see columns being inserted or have SELECT -UPDATE t1 SET c3 = 10; -- fail, but see columns with SELECT rights, or being modified - -SET SESSION AUTHORIZATION regress_priv_user1; -DROP TABLE t1; - --- check error reporting with column privs on a partitioned table -CREATE TABLE errtst(a text, b text NOT NULL, c text, secret1 text, secret2 text) PARTITION BY LIST (a); -CREATE TABLE errtst_part_1(secret2 text, c text, a text, b text NOT NULL, secret1 text); -CREATE TABLE errtst_part_2(secret1 text, secret2 text, a text, c text, b text NOT NULL); - -ALTER TABLE errtst ATTACH PARTITION errtst_part_1 FOR VALUES IN ('aaa'); -ALTER TABLE errtst ATTACH PARTITION errtst_part_2 FOR VALUES IN ('aaaa'); - -GRANT SELECT (a, b, c) ON TABLE errtst TO regress_priv_user2; -GRANT UPDATE (a, b, c) ON TABLE errtst TO regress_priv_user2; -GRANT INSERT (a, b, c) ON TABLE errtst TO regress_priv_user2; - -INSERT INTO errtst_part_1 (a, b, c, secret1, secret2) -VALUES ('aaa', 'bbb', 'ccc', 'the body', 'is in the attic'); - -SET SESSION AUTHORIZATION regress_priv_user2; - --- Perform a few updates that violate the NOT NULL constraint. Make sure --- the error messages don't leak the secret fields. - --- simple insert. -INSERT INTO errtst (a, b) VALUES ('aaa', NULL); --- simple update. -UPDATE errtst SET b = NULL; --- partitioning key is updated, doesn't move the row. -UPDATE errtst SET a = 'aaa', b = NULL; --- row is moved to another partition. -UPDATE errtst SET a = 'aaaa', b = NULL; - --- row is moved to another partition. This differs from the previous case in --- that the new partition is excluded by constraint exclusion, so its --- ResultRelInfo is not created at ExecInitModifyTable, but needs to be --- constructed on the fly when the updated tuple is routed to it. -UPDATE errtst SET a = 'aaaa', b = NULL WHERE a = 'aaa'; - -SET SESSION AUTHORIZATION regress_priv_user1; -DROP TABLE errtst; - --- test column-level privileges when involved with DELETE -SET SESSION AUTHORIZATION regress_priv_user1; -ALTER TABLE atest6 ADD COLUMN three integer; -GRANT DELETE ON atest5 TO regress_priv_user3; -GRANT SELECT (two) ON atest5 TO regress_priv_user3; -REVOKE ALL (one) ON atest5 FROM regress_priv_user3; -GRANT SELECT (one) ON atest5 TO regress_priv_user4; - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT atest6 FROM atest6; -- fail -SELECT one FROM atest5 NATURAL JOIN atest6; -- fail - -SET SESSION AUTHORIZATION regress_priv_user1; -ALTER TABLE atest6 DROP COLUMN three; - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT atest6 FROM atest6; -- ok -SELECT one FROM atest5 NATURAL JOIN atest6; -- ok - -SET SESSION AUTHORIZATION regress_priv_user1; -ALTER TABLE atest6 DROP COLUMN two; -REVOKE SELECT (one,blue) ON atest6 FROM regress_priv_user4; - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT * FROM atest6; -- fail -SELECT 1 FROM atest6; -- fail - -SET SESSION AUTHORIZATION regress_priv_user3; -DELETE FROM atest5 WHERE one = 1; -- fail -DELETE FROM atest5 WHERE two = 2; -- ok - --- check inheritance cases -SET SESSION AUTHORIZATION regress_priv_user1; -CREATE TABLE atestp1 (f1 int, f2 int); -CREATE TABLE atestp2 (fx int, fy int); -CREATE TABLE atestc (fz int) INHERITS (atestp1, atestp2); -GRANT SELECT(fx,fy,tableoid) ON atestp2 TO regress_priv_user2; -GRANT SELECT(fx) ON atestc TO regress_priv_user2; - -SET SESSION AUTHORIZATION regress_priv_user2; -SELECT fx FROM atestp2; -- ok -SELECT fy FROM atestp2; -- ok -SELECT atestp2 FROM atestp2; -- ok -SELECT tableoid FROM atestp2; -- ok -SELECT fy FROM atestc; -- fail - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT SELECT(fy,tableoid) ON atestc TO regress_priv_user2; - -SET SESSION AUTHORIZATION regress_priv_user2; -SELECT fx FROM atestp2; -- still ok -SELECT fy FROM atestp2; -- ok -SELECT atestp2 FROM atestp2; -- ok -SELECT tableoid FROM atestp2; -- ok - --- child's permissions do not apply when operating on parent -SET SESSION AUTHORIZATION regress_priv_user1; -REVOKE ALL ON atestc FROM regress_priv_user2; -GRANT ALL ON atestp1 TO regress_priv_user2; -SET SESSION AUTHORIZATION regress_priv_user2; -SELECT f2 FROM atestp1; -- ok -SELECT f2 FROM atestc; -- fail -DELETE FROM atestp1; -- ok -DELETE FROM atestc; -- fail -UPDATE atestp1 SET f1 = 1; -- ok -UPDATE atestc SET f1 = 1; -- fail -TRUNCATE atestp1; -- ok -TRUNCATE atestc; -- fail -BEGIN; -LOCK atestp1; -END; -BEGIN; -LOCK atestc; -END; - --- privileges on functions, languages - --- switch to superuser -\c - - -REVOKE ALL PRIVILEGES ON LANGUAGE sql FROM PUBLIC; -GRANT USAGE ON LANGUAGE sql TO regress_priv_user1; -- ok -GRANT USAGE ON LANGUAGE c TO PUBLIC; -- fail - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT USAGE ON LANGUAGE sql TO regress_priv_user2; -- fail -CREATE FUNCTION priv_testfunc1(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -CREATE FUNCTION priv_testfunc2(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql; -CREATE AGGREGATE priv_testagg1(int) (sfunc = int4pl, stype = int4); -CREATE PROCEDURE priv_testproc1(int) AS 'select $1;' LANGUAGE sql; - -REVOKE ALL ON FUNCTION priv_testfunc1(int), priv_testfunc2(int), priv_testagg1(int) FROM PUBLIC; -GRANT EXECUTE ON FUNCTION priv_testfunc1(int), priv_testfunc2(int), priv_testagg1(int) TO regress_priv_user2; -REVOKE ALL ON FUNCTION priv_testproc1(int) FROM PUBLIC; -- fail, not a function -REVOKE ALL ON PROCEDURE priv_testproc1(int) FROM PUBLIC; -GRANT EXECUTE ON PROCEDURE priv_testproc1(int) TO regress_priv_user2; -GRANT USAGE ON FUNCTION priv_testfunc1(int) TO regress_priv_user3; -- semantic error -GRANT USAGE ON FUNCTION priv_testagg1(int) TO regress_priv_user3; -- semantic error -GRANT USAGE ON PROCEDURE priv_testproc1(int) TO regress_priv_user3; -- semantic error -GRANT ALL PRIVILEGES ON FUNCTION priv_testfunc1(int) TO regress_priv_user4; -GRANT ALL PRIVILEGES ON FUNCTION priv_testfunc_nosuch(int) TO regress_priv_user4; -GRANT ALL PRIVILEGES ON FUNCTION priv_testagg1(int) TO regress_priv_user4; -GRANT ALL PRIVILEGES ON PROCEDURE priv_testproc1(int) TO regress_priv_user4; - -CREATE FUNCTION priv_testfunc4(boolean) RETURNS text - AS 'select col1 from atest2 where col2 = $1;' - LANGUAGE sql SECURITY DEFINER; -GRANT EXECUTE ON FUNCTION priv_testfunc4(boolean) TO regress_priv_user3; - -SET SESSION AUTHORIZATION regress_priv_user2; -SELECT priv_testfunc1(5), priv_testfunc2(5); -- ok -CREATE FUNCTION priv_testfunc3(int) RETURNS int AS 'select 2 * $1;' LANGUAGE sql; -- fail -SELECT priv_testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok -CALL priv_testproc1(6); -- ok - -SET SESSION AUTHORIZATION regress_priv_user3; -SELECT priv_testfunc1(5); -- fail -SELECT priv_testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- fail -CALL priv_testproc1(6); -- fail -SELECT col1 FROM atest2 WHERE col2 = true; -- fail -SELECT priv_testfunc4(true); -- ok - -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT priv_testfunc1(5); -- ok -SELECT priv_testagg1(x) FROM (VALUES (1), (2), (3)) _(x); -- ok -CALL priv_testproc1(6); -- ok - -DROP FUNCTION priv_testfunc1(int); -- fail -DROP AGGREGATE priv_testagg1(int); -- fail -DROP PROCEDURE priv_testproc1(int); -- fail - -\c - - -DROP FUNCTION priv_testfunc1(int); -- ok --- restore to sanity -GRANT ALL PRIVILEGES ON LANGUAGE sql TO PUBLIC; - --- verify privilege checks on array-element coercions -BEGIN; -SELECT '{1}'::int4[]::int8[]; -REVOKE ALL ON FUNCTION int8(integer) FROM PUBLIC; -SELECT '{1}'::int4[]::int8[]; --superuser, succeed -SET SESSION AUTHORIZATION regress_priv_user4; -SELECT '{1}'::int4[]::int8[]; --other user, fail -ROLLBACK; - --- privileges on types - --- switch to superuser -\c - - -CREATE TYPE priv_testtype1 AS (a int, b text); -REVOKE USAGE ON TYPE priv_testtype1 FROM PUBLIC; -GRANT USAGE ON TYPE priv_testtype1 TO regress_priv_user2; -GRANT USAGE ON TYPE _priv_testtype1 TO regress_priv_user2; -- fail -GRANT USAGE ON DOMAIN priv_testtype1 TO regress_priv_user2; -- fail - -CREATE DOMAIN priv_testdomain1 AS int; -REVOKE USAGE on DOMAIN priv_testdomain1 FROM PUBLIC; -GRANT USAGE ON DOMAIN priv_testdomain1 TO regress_priv_user2; -GRANT USAGE ON TYPE priv_testdomain1 TO regress_priv_user2; -- ok - -SET SESSION AUTHORIZATION regress_priv_user1; - --- commands that should fail - -CREATE AGGREGATE priv_testagg1a(priv_testdomain1) (sfunc = int4_sum, stype = bigint); - -CREATE DOMAIN priv_testdomain2a AS priv_testdomain1; - -CREATE DOMAIN priv_testdomain3a AS int; -CREATE FUNCTION castfunc(int) RETURNS priv_testdomain3a AS $$ SELECT $1::priv_testdomain3a $$ LANGUAGE SQL; -CREATE CAST (priv_testdomain1 AS priv_testdomain3a) WITH FUNCTION castfunc(int); -DROP FUNCTION castfunc(int) CASCADE; -DROP DOMAIN priv_testdomain3a; - -CREATE FUNCTION priv_testfunc5a(a priv_testdomain1) RETURNS int LANGUAGE SQL AS $$ SELECT $1 $$; -CREATE FUNCTION priv_testfunc6a(b int) RETURNS priv_testdomain1 LANGUAGE SQL AS $$ SELECT $1::priv_testdomain1 $$; - -CREATE OPERATOR !+! (PROCEDURE = int4pl, LEFTARG = priv_testdomain1, RIGHTARG = priv_testdomain1); - -CREATE TABLE test5a (a int, b priv_testdomain1); -CREATE TABLE test6a OF priv_testtype1; -CREATE TABLE test10a (a int[], b priv_testtype1[]); - -CREATE TABLE test9a (a int, b int); -ALTER TABLE test9a ADD COLUMN c priv_testdomain1; -ALTER TABLE test9a ALTER COLUMN b TYPE priv_testdomain1; - -CREATE TYPE test7a AS (a int, b priv_testdomain1); - -CREATE TYPE test8a AS (a int, b int); -ALTER TYPE test8a ADD ATTRIBUTE c priv_testdomain1; -ALTER TYPE test8a ALTER ATTRIBUTE b TYPE priv_testdomain1; - -CREATE TABLE test11a AS (SELECT 1::priv_testdomain1 AS a); - -REVOKE ALL ON TYPE priv_testtype1 FROM PUBLIC; - -SET SESSION AUTHORIZATION regress_priv_user2; - --- commands that should succeed - -CREATE AGGREGATE priv_testagg1b(priv_testdomain1) (sfunc = int4_sum, stype = bigint); - -CREATE DOMAIN priv_testdomain2b AS priv_testdomain1; - -CREATE DOMAIN priv_testdomain3b AS int; -CREATE FUNCTION castfunc(int) RETURNS priv_testdomain3b AS $$ SELECT $1::priv_testdomain3b $$ LANGUAGE SQL; -CREATE CAST (priv_testdomain1 AS priv_testdomain3b) WITH FUNCTION castfunc(int); - -CREATE FUNCTION priv_testfunc5b(a priv_testdomain1) RETURNS int LANGUAGE SQL AS $$ SELECT $1 $$; -CREATE FUNCTION priv_testfunc6b(b int) RETURNS priv_testdomain1 LANGUAGE SQL AS $$ SELECT $1::priv_testdomain1 $$; - -CREATE OPERATOR !! (PROCEDURE = priv_testfunc5b, RIGHTARG = priv_testdomain1); - -CREATE TABLE test5b (a int, b priv_testdomain1); -CREATE TABLE test6b OF priv_testtype1; -CREATE TABLE test10b (a int[], b priv_testtype1[]); - -CREATE TABLE test9b (a int, b int); -ALTER TABLE test9b ADD COLUMN c priv_testdomain1; -ALTER TABLE test9b ALTER COLUMN b TYPE priv_testdomain1; - -CREATE TYPE test7b AS (a int, b priv_testdomain1); - -CREATE TYPE test8b AS (a int, b int); -ALTER TYPE test8b ADD ATTRIBUTE c priv_testdomain1; -ALTER TYPE test8b ALTER ATTRIBUTE b TYPE priv_testdomain1; - -CREATE TABLE test11b AS (SELECT 1::priv_testdomain1 AS a); - -REVOKE ALL ON TYPE priv_testtype1 FROM PUBLIC; - -\c - -DROP AGGREGATE priv_testagg1b(priv_testdomain1); -DROP DOMAIN priv_testdomain2b; -DROP OPERATOR !! (NONE, priv_testdomain1); -DROP FUNCTION priv_testfunc5b(a priv_testdomain1); -DROP FUNCTION priv_testfunc6b(b int); -DROP TABLE test5b; -DROP TABLE test6b; -DROP TABLE test9b; -DROP TABLE test10b; -DROP TYPE test7b; -DROP TYPE test8b; -DROP CAST (priv_testdomain1 AS priv_testdomain3b); -DROP FUNCTION castfunc(int) CASCADE; -DROP DOMAIN priv_testdomain3b; -DROP TABLE test11b; - -DROP TYPE priv_testtype1; -- ok -DROP DOMAIN priv_testdomain1; -- ok - - --- truncate -SET SESSION AUTHORIZATION regress_priv_user5; -TRUNCATE atest2; -- ok -TRUNCATE atest3; -- fail - --- has_table_privilege function - --- bad-input checks -select has_table_privilege(NULL,'pg_authid','select'); -select has_table_privilege('pg_shad','select'); -select has_table_privilege('nosuchuser','pg_authid','select'); -select has_table_privilege('pg_authid','sel'); -select has_table_privilege(-999999,'pg_authid','update'); -select has_table_privilege(1,'select'); - --- superuser -\c - - -select has_table_privilege(current_user,'pg_authid','select'); -select has_table_privilege(current_user,'pg_authid','insert'); - -select has_table_privilege(t2.oid,'pg_authid','update') -from (select oid from pg_roles where rolname = current_user) as t2; -select has_table_privilege(t2.oid,'pg_authid','delete') -from (select oid from pg_roles where rolname = current_user) as t2; - --- 'rule' privilege no longer exists, but for backwards compatibility --- has_table_privilege still recognizes the keyword and says FALSE -select has_table_privilege(current_user,t1.oid,'rule') -from (select oid from pg_class where relname = 'pg_authid') as t1; -select has_table_privilege(current_user,t1.oid,'references') -from (select oid from pg_class where relname = 'pg_authid') as t1; - -select has_table_privilege(t2.oid,t1.oid,'select') -from (select oid from pg_class where relname = 'pg_authid') as t1, - (select oid from pg_roles where rolname = current_user) as t2; -select has_table_privilege(t2.oid,t1.oid,'insert') -from (select oid from pg_class where relname = 'pg_authid') as t1, - (select oid from pg_roles where rolname = current_user) as t2; - -select has_table_privilege('pg_authid','update'); -select has_table_privilege('pg_authid','delete'); -select has_table_privilege('pg_authid','truncate'); - -select has_table_privilege(t1.oid,'select') -from (select oid from pg_class where relname = 'pg_authid') as t1; -select has_table_privilege(t1.oid,'trigger') -from (select oid from pg_class where relname = 'pg_authid') as t1; - --- non-superuser -SET SESSION AUTHORIZATION regress_priv_user3; - -select has_table_privilege(current_user,'pg_class','select'); -select has_table_privilege(current_user,'pg_class','insert'); - -select has_table_privilege(t2.oid,'pg_class','update') -from (select oid from pg_roles where rolname = current_user) as t2; -select has_table_privilege(t2.oid,'pg_class','delete') -from (select oid from pg_roles where rolname = current_user) as t2; - -select has_table_privilege(current_user,t1.oid,'references') -from (select oid from pg_class where relname = 'pg_class') as t1; - -select has_table_privilege(t2.oid,t1.oid,'select') -from (select oid from pg_class where relname = 'pg_class') as t1, - (select oid from pg_roles where rolname = current_user) as t2; -select has_table_privilege(t2.oid,t1.oid,'insert') -from (select oid from pg_class where relname = 'pg_class') as t1, - (select oid from pg_roles where rolname = current_user) as t2; - -select has_table_privilege('pg_class','update'); -select has_table_privilege('pg_class','delete'); -select has_table_privilege('pg_class','truncate'); - -select has_table_privilege(t1.oid,'select') -from (select oid from pg_class where relname = 'pg_class') as t1; -select has_table_privilege(t1.oid,'trigger') -from (select oid from pg_class where relname = 'pg_class') as t1; - -select has_table_privilege(current_user,'atest1','select'); -select has_table_privilege(current_user,'atest1','insert'); - -select has_table_privilege(t2.oid,'atest1','update') -from (select oid from pg_roles where rolname = current_user) as t2; -select has_table_privilege(t2.oid,'atest1','delete') -from (select oid from pg_roles where rolname = current_user) as t2; - -select has_table_privilege(current_user,t1.oid,'references') -from (select oid from pg_class where relname = 'atest1') as t1; - -select has_table_privilege(t2.oid,t1.oid,'select') -from (select oid from pg_class where relname = 'atest1') as t1, - (select oid from pg_roles where rolname = current_user) as t2; -select has_table_privilege(t2.oid,t1.oid,'insert') -from (select oid from pg_class where relname = 'atest1') as t1, - (select oid from pg_roles where rolname = current_user) as t2; - -select has_table_privilege('atest1','update'); -select has_table_privilege('atest1','delete'); -select has_table_privilege('atest1','truncate'); - -select has_table_privilege(t1.oid,'select') -from (select oid from pg_class where relname = 'atest1') as t1; -select has_table_privilege(t1.oid,'trigger') -from (select oid from pg_class where relname = 'atest1') as t1; - --- has_column_privilege function - --- bad-input checks (as non-super-user) -select has_column_privilege('pg_authid',NULL,'select'); -select has_column_privilege('pg_authid','nosuchcol','select'); -select has_column_privilege(9999,'nosuchcol','select'); -select has_column_privilege(9999,99::int2,'select'); -select has_column_privilege('pg_authid',99::int2,'select'); -select has_column_privilege(9999,99::int2,'select'); - -create temp table mytable(f1 int, f2 int, f3 int); -alter table mytable drop column f2; -select has_column_privilege('mytable','f2','select'); -select has_column_privilege('mytable','........pg.dropped.2........','select'); -select has_column_privilege('mytable',2::int2,'select'); -select has_column_privilege('mytable',99::int2,'select'); -revoke select on table mytable from regress_priv_user3; -select has_column_privilege('mytable',2::int2,'select'); -select has_column_privilege('mytable',99::int2,'select'); -drop table mytable; - --- Grant options - -SET SESSION AUTHORIZATION regress_priv_user1; - -CREATE TABLE atest4 (a int); - -GRANT SELECT ON atest4 TO regress_priv_user2 WITH GRANT OPTION; -GRANT UPDATE ON atest4 TO regress_priv_user2; -GRANT SELECT ON atest4 TO GROUP regress_priv_group1 WITH GRANT OPTION; - -SET SESSION AUTHORIZATION regress_priv_user2; - -GRANT SELECT ON atest4 TO regress_priv_user3; -GRANT UPDATE ON atest4 TO regress_priv_user3; -- fail - -SET SESSION AUTHORIZATION regress_priv_user1; - -REVOKE SELECT ON atest4 FROM regress_priv_user3; -- does nothing -SELECT has_table_privilege('regress_priv_user3', 'atest4', 'SELECT'); -- true -REVOKE SELECT ON atest4 FROM regress_priv_user2; -- fail -REVOKE GRANT OPTION FOR SELECT ON atest4 FROM regress_priv_user2 CASCADE; -- ok -SELECT has_table_privilege('regress_priv_user2', 'atest4', 'SELECT'); -- true -SELECT has_table_privilege('regress_priv_user3', 'atest4', 'SELECT'); -- false - -SELECT has_table_privilege('regress_priv_user1', 'atest4', 'SELECT WITH GRANT OPTION'); -- true - - --- security-restricted operations -\c - -CREATE ROLE regress_sro_user; - --- Check that index expressions and predicates are run as the table's owner - --- A dummy index function checking current_user -CREATE FUNCTION sro_ifun(int) RETURNS int AS $$ -BEGIN - -- Below we set the table's owner to regress_sro_user - ASSERT current_user = 'regress_sro_user', - format('sro_ifun(%s) called by %s', $1, current_user); - RETURN $1; -END; -$$ LANGUAGE plpgsql IMMUTABLE; --- Create a table owned by regress_sro_user -CREATE TABLE sro_tab (a int); -ALTER TABLE sro_tab OWNER TO regress_sro_user; -INSERT INTO sro_tab VALUES (1), (2), (3); --- Create an expression index with a predicate -CREATE INDEX sro_idx ON sro_tab ((sro_ifun(a) + sro_ifun(0))) - WHERE sro_ifun(a + 10) > sro_ifun(10); -DROP INDEX sro_idx; --- Do the same concurrently -CREATE INDEX CONCURRENTLY sro_idx ON sro_tab ((sro_ifun(a) + sro_ifun(0))) - WHERE sro_ifun(a + 10) > sro_ifun(10); --- REINDEX -REINDEX TABLE sro_tab; -REINDEX INDEX sro_idx; -REINDEX TABLE CONCURRENTLY sro_tab; -DROP INDEX sro_idx; --- CLUSTER -CREATE INDEX sro_cluster_idx ON sro_tab ((sro_ifun(a) + sro_ifun(0))); -CLUSTER sro_tab USING sro_cluster_idx; -DROP INDEX sro_cluster_idx; --- BRIN index -CREATE INDEX sro_brin ON sro_tab USING brin ((sro_ifun(a) + sro_ifun(0))); -SELECT brin_desummarize_range('sro_brin', 0); -SELECT brin_summarize_range('sro_brin', 0); -DROP TABLE sro_tab; --- Check with a partitioned table -CREATE TABLE sro_ptab (a int) PARTITION BY RANGE (a); -ALTER TABLE sro_ptab OWNER TO regress_sro_user; -CREATE TABLE sro_part PARTITION OF sro_ptab FOR VALUES FROM (1) TO (10); -ALTER TABLE sro_part OWNER TO regress_sro_user; -INSERT INTO sro_ptab VALUES (1), (2), (3); -CREATE INDEX sro_pidx ON sro_ptab ((sro_ifun(a) + sro_ifun(0))) - WHERE sro_ifun(a + 10) > sro_ifun(10); -REINDEX TABLE sro_ptab; -REINDEX INDEX CONCURRENTLY sro_pidx; - -SET SESSION AUTHORIZATION regress_sro_user; -CREATE FUNCTION unwanted_grant() RETURNS void LANGUAGE sql AS - 'GRANT regress_priv_group2 TO regress_sro_user'; -CREATE FUNCTION mv_action() RETURNS bool LANGUAGE sql AS - 'DECLARE c CURSOR WITH HOLD FOR SELECT unwanted_grant(); SELECT true'; --- REFRESH of this MV will queue a GRANT at end of transaction -CREATE MATERIALIZED VIEW sro_mv AS SELECT mv_action() WITH NO DATA; -REFRESH MATERIALIZED VIEW sro_mv; -\c - -REFRESH MATERIALIZED VIEW sro_mv; - -SET SESSION AUTHORIZATION regress_sro_user; --- INSERT to this table will queue a GRANT at end of transaction -CREATE TABLE sro_trojan_table (); -CREATE FUNCTION sro_trojan() RETURNS trigger LANGUAGE plpgsql AS - 'BEGIN PERFORM unwanted_grant(); RETURN NULL; END'; -CREATE CONSTRAINT TRIGGER t AFTER INSERT ON sro_trojan_table - INITIALLY DEFERRED FOR EACH ROW EXECUTE PROCEDURE sro_trojan(); --- Now, REFRESH will issue such an INSERT, queueing the GRANT -CREATE OR REPLACE FUNCTION mv_action() RETURNS bool LANGUAGE sql AS - 'INSERT INTO sro_trojan_table DEFAULT VALUES; SELECT true'; -REFRESH MATERIALIZED VIEW sro_mv; -\c - -REFRESH MATERIALIZED VIEW sro_mv; -BEGIN; SET CONSTRAINTS ALL IMMEDIATE; REFRESH MATERIALIZED VIEW sro_mv; COMMIT; - --- REFRESH MATERIALIZED VIEW CONCURRENTLY use of eval_const_expressions() -SET SESSION AUTHORIZATION regress_sro_user; -CREATE FUNCTION unwanted_grant_nofail(int) RETURNS int - IMMUTABLE LANGUAGE plpgsql AS $$ -BEGIN - PERFORM unwanted_grant(); - RAISE WARNING 'owned'; - RETURN 1; -EXCEPTION WHEN OTHERS THEN - RETURN 2; -END$$; -CREATE MATERIALIZED VIEW sro_index_mv AS SELECT 1 AS c; -CREATE UNIQUE INDEX ON sro_index_mv (c) WHERE unwanted_grant_nofail(1) > 0; -\c - -REFRESH MATERIALIZED VIEW CONCURRENTLY sro_index_mv; -REFRESH MATERIALIZED VIEW sro_index_mv; - -DROP OWNED BY regress_sro_user; -DROP ROLE regress_sro_user; - - --- Admin options - -SET SESSION AUTHORIZATION regress_priv_user4; -CREATE FUNCTION dogrant_ok() RETURNS void LANGUAGE sql SECURITY DEFINER AS - 'GRANT regress_priv_group2 TO regress_priv_user5'; -GRANT regress_priv_group2 TO regress_priv_user5; -- ok: had ADMIN OPTION -SET ROLE regress_priv_group2; -GRANT regress_priv_group2 TO regress_priv_user5; -- fails: SET ROLE suspended privilege - -SET SESSION AUTHORIZATION regress_priv_user1; -GRANT regress_priv_group2 TO regress_priv_user5; -- fails: no ADMIN OPTION -SELECT dogrant_ok(); -- ok: SECURITY DEFINER conveys ADMIN -SET ROLE regress_priv_group2; -GRANT regress_priv_group2 TO regress_priv_user5; -- fails: SET ROLE did not help - -SET SESSION AUTHORIZATION regress_priv_group2; -GRANT regress_priv_group2 TO regress_priv_user5; -- fails: no self-admin - -SET SESSION AUTHORIZATION regress_priv_user4; -DROP FUNCTION dogrant_ok(); -REVOKE regress_priv_group2 FROM regress_priv_user5; - - --- has_sequence_privilege tests -\c - - -CREATE SEQUENCE x_seq; - -GRANT USAGE on x_seq to regress_priv_user2; - -SELECT has_sequence_privilege('regress_priv_user1', 'atest1', 'SELECT'); -SELECT has_sequence_privilege('regress_priv_user1', 'x_seq', 'INSERT'); -SELECT has_sequence_privilege('regress_priv_user1', 'x_seq', 'SELECT'); - -SET SESSION AUTHORIZATION regress_priv_user2; - -SELECT has_sequence_privilege('x_seq', 'USAGE'); - --- largeobject privilege tests -\c - -SET SESSION AUTHORIZATION regress_priv_user1; - -SELECT lo_create(1001); -SELECT lo_create(1002); -SELECT lo_create(1003); -SELECT lo_create(1004); -SELECT lo_create(1005); - -GRANT ALL ON LARGE OBJECT 1001 TO PUBLIC; -GRANT SELECT ON LARGE OBJECT 1003 TO regress_priv_user2; -GRANT SELECT,UPDATE ON LARGE OBJECT 1004 TO regress_priv_user2; -GRANT ALL ON LARGE OBJECT 1005 TO regress_priv_user2; -GRANT SELECT ON LARGE OBJECT 1005 TO regress_priv_user2 WITH GRANT OPTION; - -GRANT SELECT, INSERT ON LARGE OBJECT 1001 TO PUBLIC; -- to be failed -GRANT SELECT, UPDATE ON LARGE OBJECT 1001 TO nosuchuser; -- to be failed -GRANT SELECT, UPDATE ON LARGE OBJECT 999 TO PUBLIC; -- to be failed - -\c - -SET SESSION AUTHORIZATION regress_priv_user2; - -SELECT lo_create(2001); -SELECT lo_create(2002); - -SELECT loread(lo_open(1001, x'20000'::int), 32); -- allowed, for now -SELECT lowrite(lo_open(1001, x'40000'::int), 'abcd'); -- fail, wrong mode - -SELECT loread(lo_open(1001, x'40000'::int), 32); -SELECT loread(lo_open(1002, x'40000'::int), 32); -- to be denied -SELECT loread(lo_open(1003, x'40000'::int), 32); -SELECT loread(lo_open(1004, x'40000'::int), 32); - -SELECT lowrite(lo_open(1001, x'20000'::int), 'abcd'); -SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd'); -- to be denied -SELECT lowrite(lo_open(1003, x'20000'::int), 'abcd'); -- to be denied -SELECT lowrite(lo_open(1004, x'20000'::int), 'abcd'); - -GRANT SELECT ON LARGE OBJECT 1005 TO regress_priv_user3; -GRANT UPDATE ON LARGE OBJECT 1006 TO regress_priv_user3; -- to be denied -REVOKE ALL ON LARGE OBJECT 2001, 2002 FROM PUBLIC; -GRANT ALL ON LARGE OBJECT 2001 TO regress_priv_user3; - -SELECT lo_unlink(1001); -- to be denied -SELECT lo_unlink(2002); - -\c - --- confirm ACL setting -SELECT oid, pg_get_userbyid(lomowner) ownername, lomacl FROM pg_largeobject_metadata WHERE oid >= 1000 AND oid < 3000 ORDER BY oid; - -SET SESSION AUTHORIZATION regress_priv_user3; - -SELECT loread(lo_open(1001, x'40000'::int), 32); -SELECT loread(lo_open(1003, x'40000'::int), 32); -- to be denied -SELECT loread(lo_open(1005, x'40000'::int), 32); - -SELECT lo_truncate(lo_open(1005, x'20000'::int), 10); -- to be denied -SELECT lo_truncate(lo_open(2001, x'20000'::int), 10); - --- compatibility mode in largeobject permission -\c - -SET lo_compat_privileges = false; -- default setting -SET SESSION AUTHORIZATION regress_priv_user4; - -SELECT loread(lo_open(1002, x'40000'::int), 32); -- to be denied -SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd'); -- to be denied -SELECT lo_truncate(lo_open(1002, x'20000'::int), 10); -- to be denied -SELECT lo_put(1002, 1, 'abcd'); -- to be denied -SELECT lo_unlink(1002); -- to be denied -SELECT lo_export(1001, '/dev/null'); -- to be denied -SELECT lo_import('/dev/null'); -- to be denied -SELECT lo_import('/dev/null', 2003); -- to be denied - -\c - -SET lo_compat_privileges = true; -- compatibility mode -SET SESSION AUTHORIZATION regress_priv_user4; - -SELECT loread(lo_open(1002, x'40000'::int), 32); -SELECT lowrite(lo_open(1002, x'20000'::int), 'abcd'); -SELECT lo_truncate(lo_open(1002, x'20000'::int), 10); -SELECT lo_unlink(1002); -SELECT lo_export(1001, '/dev/null'); -- to be denied - --- don't allow unpriv users to access pg_largeobject contents -\c - -SELECT * FROM pg_largeobject LIMIT 0; - -SET SESSION AUTHORIZATION regress_priv_user1; -SELECT * FROM pg_largeobject LIMIT 0; -- to be denied - --- test pg_database_owner -RESET SESSION AUTHORIZATION; -GRANT pg_database_owner TO regress_priv_user1; -GRANT regress_priv_user1 TO pg_database_owner; -CREATE TABLE datdba_only (); -ALTER TABLE datdba_only OWNER TO pg_database_owner; -REVOKE DELETE ON datdba_only FROM pg_database_owner; -SELECT - pg_has_role('regress_priv_user1', 'pg_database_owner', 'USAGE') as priv, - pg_has_role('regress_priv_user1', 'pg_database_owner', 'MEMBER') as mem, - pg_has_role('regress_priv_user1', 'pg_database_owner', - 'MEMBER WITH ADMIN OPTION') as admin; - -BEGIN; -DO $$BEGIN EXECUTE format( - 'ALTER DATABASE %I OWNER TO regress_priv_group2', current_catalog); END$$; -SELECT - pg_has_role('regress_priv_user1', 'pg_database_owner', 'USAGE') as priv, - pg_has_role('regress_priv_user1', 'pg_database_owner', 'MEMBER') as mem, - pg_has_role('regress_priv_user1', 'pg_database_owner', - 'MEMBER WITH ADMIN OPTION') as admin; -SET SESSION AUTHORIZATION regress_priv_user1; -TABLE information_schema.enabled_roles ORDER BY role_name COLLATE "C"; -TABLE information_schema.applicable_roles ORDER BY role_name COLLATE "C"; -INSERT INTO datdba_only DEFAULT VALUES; -SAVEPOINT q; DELETE FROM datdba_only; ROLLBACK TO q; -SET SESSION AUTHORIZATION regress_priv_user2; -TABLE information_schema.enabled_roles; -INSERT INTO datdba_only DEFAULT VALUES; -ROLLBACK; - --- test default ACLs -\c - - -CREATE SCHEMA testns; -GRANT ALL ON SCHEMA testns TO regress_priv_user1; - -CREATE TABLE testns.acltest1 (x int); -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'SELECT'); -- no -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'INSERT'); -- no - --- placeholder for test with duplicated schema and role names -ALTER DEFAULT PRIVILEGES IN SCHEMA testns,testns GRANT SELECT ON TABLES TO public,public; - -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'SELECT'); -- no -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'INSERT'); -- no - -DROP TABLE testns.acltest1; -CREATE TABLE testns.acltest1 (x int); - -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'SELECT'); -- yes -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'INSERT'); -- no - -ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT INSERT ON TABLES TO regress_priv_user1; - -DROP TABLE testns.acltest1; -CREATE TABLE testns.acltest1 (x int); - -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'SELECT'); -- yes -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'INSERT'); -- yes - -ALTER DEFAULT PRIVILEGES IN SCHEMA testns REVOKE INSERT ON TABLES FROM regress_priv_user1; - -DROP TABLE testns.acltest1; -CREATE TABLE testns.acltest1 (x int); - -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'SELECT'); -- yes -SELECT has_table_privilege('regress_priv_user1', 'testns.acltest1', 'INSERT'); -- no - -ALTER DEFAULT PRIVILEGES FOR ROLE regress_priv_user1 REVOKE EXECUTE ON FUNCTIONS FROM public; - -ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT USAGE ON SCHEMAS TO regress_priv_user2; -- error - --- --- Testing blanket default grants is very hazardous since it might change --- the privileges attached to objects created by concurrent regression tests. --- To avoid that, be sure to revoke the privileges again before committing. --- -BEGIN; - -ALTER DEFAULT PRIVILEGES GRANT USAGE ON SCHEMAS TO regress_priv_user2; - -CREATE SCHEMA testns2; - -SELECT has_schema_privilege('regress_priv_user2', 'testns2', 'USAGE'); -- yes -SELECT has_schema_privilege('regress_priv_user6', 'testns2', 'USAGE'); -- yes -SELECT has_schema_privilege('regress_priv_user2', 'testns2', 'CREATE'); -- no - -ALTER DEFAULT PRIVILEGES REVOKE USAGE ON SCHEMAS FROM regress_priv_user2; - -CREATE SCHEMA testns3; - -SELECT has_schema_privilege('regress_priv_user2', 'testns3', 'USAGE'); -- no -SELECT has_schema_privilege('regress_priv_user2', 'testns3', 'CREATE'); -- no - -ALTER DEFAULT PRIVILEGES GRANT ALL ON SCHEMAS TO regress_priv_user2; - -CREATE SCHEMA testns4; - -SELECT has_schema_privilege('regress_priv_user2', 'testns4', 'USAGE'); -- yes -SELECT has_schema_privilege('regress_priv_user2', 'testns4', 'CREATE'); -- yes - -ALTER DEFAULT PRIVILEGES REVOKE ALL ON SCHEMAS FROM regress_priv_user2; - -COMMIT; - --- Test for DROP OWNED BY with shared dependencies. This is done in a --- separate, rollbacked, transaction to avoid any trouble with other --- regression sessions. -BEGIN; -ALTER DEFAULT PRIVILEGES GRANT ALL ON FUNCTIONS TO regress_priv_user2; -ALTER DEFAULT PRIVILEGES GRANT ALL ON SCHEMAS TO regress_priv_user2; -ALTER DEFAULT PRIVILEGES GRANT ALL ON SEQUENCES TO regress_priv_user2; -ALTER DEFAULT PRIVILEGES GRANT ALL ON TABLES TO regress_priv_user2; -ALTER DEFAULT PRIVILEGES GRANT ALL ON TYPES TO regress_priv_user2; -SELECT count(*) FROM pg_shdepend - WHERE deptype = 'a' AND - refobjid = 'regress_priv_user2'::regrole AND - classid = 'pg_default_acl'::regclass; -DROP OWNED BY regress_priv_user2, regress_priv_user2; -SELECT count(*) FROM pg_shdepend - WHERE deptype = 'a' AND - refobjid = 'regress_priv_user2'::regrole AND - classid = 'pg_default_acl'::regclass; -ROLLBACK; - -CREATE SCHEMA testns5; - -SELECT has_schema_privilege('regress_priv_user2', 'testns5', 'USAGE'); -- no -SELECT has_schema_privilege('regress_priv_user2', 'testns5', 'CREATE'); -- no - -SET ROLE regress_priv_user1; - -CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql; -CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4); -CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql; - -SELECT has_function_privilege('regress_priv_user2', 'testns.foo()', 'EXECUTE'); -- no -SELECT has_function_privilege('regress_priv_user2', 'testns.agg1(int)', 'EXECUTE'); -- no -SELECT has_function_privilege('regress_priv_user2', 'testns.bar()', 'EXECUTE'); -- no - -ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT EXECUTE ON ROUTINES to public; - -DROP FUNCTION testns.foo(); -CREATE FUNCTION testns.foo() RETURNS int AS 'select 1' LANGUAGE sql; -DROP AGGREGATE testns.agg1(int); -CREATE AGGREGATE testns.agg1(int) (sfunc = int4pl, stype = int4); -DROP PROCEDURE testns.bar(); -CREATE PROCEDURE testns.bar() AS 'select 1' LANGUAGE sql; - -SELECT has_function_privilege('regress_priv_user2', 'testns.foo()', 'EXECUTE'); -- yes -SELECT has_function_privilege('regress_priv_user2', 'testns.agg1(int)', 'EXECUTE'); -- yes -SELECT has_function_privilege('regress_priv_user2', 'testns.bar()', 'EXECUTE'); -- yes (counts as function here) - -DROP FUNCTION testns.foo(); -DROP AGGREGATE testns.agg1(int); -DROP PROCEDURE testns.bar(); - -ALTER DEFAULT PRIVILEGES FOR ROLE regress_priv_user1 REVOKE USAGE ON TYPES FROM public; - -CREATE DOMAIN testns.priv_testdomain1 AS int; - -SELECT has_type_privilege('regress_priv_user2', 'testns.priv_testdomain1', 'USAGE'); -- no - -ALTER DEFAULT PRIVILEGES IN SCHEMA testns GRANT USAGE ON TYPES to public; - -DROP DOMAIN testns.priv_testdomain1; -CREATE DOMAIN testns.priv_testdomain1 AS int; - -SELECT has_type_privilege('regress_priv_user2', 'testns.priv_testdomain1', 'USAGE'); -- yes - -DROP DOMAIN testns.priv_testdomain1; - -RESET ROLE; - -SELECT count(*) - FROM pg_default_acl d LEFT JOIN pg_namespace n ON defaclnamespace = n.oid - WHERE nspname = 'testns'; - -DROP SCHEMA testns CASCADE; -DROP SCHEMA testns2 CASCADE; -DROP SCHEMA testns3 CASCADE; -DROP SCHEMA testns4 CASCADE; -DROP SCHEMA testns5 CASCADE; - -SELECT d.* -- check that entries went away - FROM pg_default_acl d LEFT JOIN pg_namespace n ON defaclnamespace = n.oid - WHERE nspname IS NULL AND defaclnamespace != 0; - - --- Grant on all objects of given type in a schema -\c - - -CREATE SCHEMA testns; -CREATE TABLE testns.t1 (f1 int); -CREATE TABLE testns.t2 (f1 int); - -SELECT has_table_privilege('regress_priv_user1', 'testns.t1', 'SELECT'); -- false - -GRANT ALL ON ALL TABLES IN SCHEMA testns TO regress_priv_user1; - -SELECT has_table_privilege('regress_priv_user1', 'testns.t1', 'SELECT'); -- true -SELECT has_table_privilege('regress_priv_user1', 'testns.t2', 'SELECT'); -- true - -REVOKE ALL ON ALL TABLES IN SCHEMA testns FROM regress_priv_user1; - -SELECT has_table_privilege('regress_priv_user1', 'testns.t1', 'SELECT'); -- false -SELECT has_table_privilege('regress_priv_user1', 'testns.t2', 'SELECT'); -- false - -CREATE FUNCTION testns.priv_testfunc(int) RETURNS int AS 'select 3 * $1;' LANGUAGE sql; -CREATE AGGREGATE testns.priv_testagg(int) (sfunc = int4pl, stype = int4); -CREATE PROCEDURE testns.priv_testproc(int) AS 'select 3' LANGUAGE sql; - -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testfunc(int)', 'EXECUTE'); -- true by default -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testagg(int)', 'EXECUTE'); -- true by default -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testproc(int)', 'EXECUTE'); -- true by default - -REVOKE ALL ON ALL FUNCTIONS IN SCHEMA testns FROM PUBLIC; - -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testfunc(int)', 'EXECUTE'); -- false -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testagg(int)', 'EXECUTE'); -- false -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testproc(int)', 'EXECUTE'); -- still true, not a function - -REVOKE ALL ON ALL PROCEDURES IN SCHEMA testns FROM PUBLIC; - -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testproc(int)', 'EXECUTE'); -- now false - -GRANT ALL ON ALL ROUTINES IN SCHEMA testns TO PUBLIC; - -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testfunc(int)', 'EXECUTE'); -- true -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testagg(int)', 'EXECUTE'); -- true -SELECT has_function_privilege('regress_priv_user1', 'testns.priv_testproc(int)', 'EXECUTE'); -- true - -DROP SCHEMA testns CASCADE; - - --- Change owner of the schema & and rename of new schema owner -\c - - -CREATE ROLE regress_schemauser1 superuser login; -CREATE ROLE regress_schemauser2 superuser login; - -SET SESSION ROLE regress_schemauser1; -CREATE SCHEMA testns; - -SELECT nspname, rolname FROM pg_namespace, pg_roles WHERE pg_namespace.nspname = 'testns' AND pg_namespace.nspowner = pg_roles.oid; - -ALTER SCHEMA testns OWNER TO regress_schemauser2; -ALTER ROLE regress_schemauser2 RENAME TO regress_schemauser_renamed; -SELECT nspname, rolname FROM pg_namespace, pg_roles WHERE pg_namespace.nspname = 'testns' AND pg_namespace.nspowner = pg_roles.oid; - -set session role regress_schemauser_renamed; -DROP SCHEMA testns CASCADE; - --- clean up -\c - - -DROP ROLE regress_schemauser1; -DROP ROLE regress_schemauser_renamed; - - --- test that dependent privileges are revoked (or not) properly -\c - - -set session role regress_priv_user1; -create table dep_priv_test (a int); -grant select on dep_priv_test to regress_priv_user2 with grant option; -grant select on dep_priv_test to regress_priv_user3 with grant option; -set session role regress_priv_user2; -grant select on dep_priv_test to regress_priv_user4 with grant option; -set session role regress_priv_user3; -grant select on dep_priv_test to regress_priv_user4 with grant option; -set session role regress_priv_user4; -grant select on dep_priv_test to regress_priv_user5; -\dp dep_priv_test -set session role regress_priv_user2; -revoke select on dep_priv_test from regress_priv_user4 cascade; -\dp dep_priv_test -set session role regress_priv_user3; -revoke select on dep_priv_test from regress_priv_user4 cascade; -\dp dep_priv_test -set session role regress_priv_user1; -drop table dep_priv_test; - - --- clean up - -\c - -drop sequence x_seq; - -DROP AGGREGATE priv_testagg1(int); -DROP FUNCTION priv_testfunc2(int); -DROP FUNCTION priv_testfunc4(boolean); -DROP PROCEDURE priv_testproc1(int); - -DROP VIEW atestv0; -DROP VIEW atestv1; -DROP VIEW atestv2; --- this should cascade to drop atestv4 -DROP VIEW atestv3 CASCADE; --- this should complain "does not exist" -DROP VIEW atestv4; - -DROP TABLE atest1; -DROP TABLE atest2; -DROP TABLE atest3; -DROP TABLE atest4; -DROP TABLE atest5; -DROP TABLE atest6; -DROP TABLE atestc; -DROP TABLE atestp1; -DROP TABLE atestp2; - -SELECT lo_unlink(oid) FROM pg_largeobject_metadata WHERE oid >= 1000 AND oid < 3000 ORDER BY oid; - -DROP GROUP regress_priv_group1; -DROP GROUP regress_priv_group2; - --- these are needed to clean up permissions -REVOKE USAGE ON LANGUAGE sql FROM regress_priv_user1; -DROP OWNED BY regress_priv_user1; - -DROP USER regress_priv_user1; -DROP USER regress_priv_user2; -DROP USER regress_priv_user3; -DROP USER regress_priv_user4; -DROP USER regress_priv_user5; -DROP USER regress_priv_user6; -DROP USER regress_priv_user7; -DROP USER regress_priv_user8; -- does not exist - - --- permissions with LOCK TABLE -CREATE USER regress_locktable_user; -CREATE TABLE lock_table (a int); - --- LOCK TABLE and SELECT permission -GRANT SELECT ON lock_table TO regress_locktable_user; -SET SESSION AUTHORIZATION regress_locktable_user; -BEGIN; -LOCK TABLE lock_table IN ROW EXCLUSIVE MODE; -- should fail -ROLLBACK; -BEGIN; -LOCK TABLE lock_table IN ACCESS SHARE MODE; -- should pass -COMMIT; -BEGIN; -LOCK TABLE lock_table IN ACCESS EXCLUSIVE MODE; -- should fail -ROLLBACK; -\c -REVOKE SELECT ON lock_table FROM regress_locktable_user; - --- LOCK TABLE and INSERT permission -GRANT INSERT ON lock_table TO regress_locktable_user; -SET SESSION AUTHORIZATION regress_locktable_user; -BEGIN; -LOCK TABLE lock_table IN ROW EXCLUSIVE MODE; -- should pass -COMMIT; -BEGIN; -LOCK TABLE lock_table IN ACCESS SHARE MODE; -- should fail -ROLLBACK; -BEGIN; -LOCK TABLE lock_table IN ACCESS EXCLUSIVE MODE; -- should fail -ROLLBACK; -\c -REVOKE INSERT ON lock_table FROM regress_locktable_user; - --- LOCK TABLE and UPDATE permission -GRANT UPDATE ON lock_table TO regress_locktable_user; -SET SESSION AUTHORIZATION regress_locktable_user; -BEGIN; -LOCK TABLE lock_table IN ROW EXCLUSIVE MODE; -- should pass -COMMIT; -BEGIN; -LOCK TABLE lock_table IN ACCESS SHARE MODE; -- should fail -ROLLBACK; -BEGIN; -LOCK TABLE lock_table IN ACCESS EXCLUSIVE MODE; -- should pass -COMMIT; -\c -REVOKE UPDATE ON lock_table FROM regress_locktable_user; - --- LOCK TABLE and DELETE permission -GRANT DELETE ON lock_table TO regress_locktable_user; -SET SESSION AUTHORIZATION regress_locktable_user; -BEGIN; -LOCK TABLE lock_table IN ROW EXCLUSIVE MODE; -- should pass -COMMIT; -BEGIN; -LOCK TABLE lock_table IN ACCESS SHARE MODE; -- should fail -ROLLBACK; -BEGIN; -LOCK TABLE lock_table IN ACCESS EXCLUSIVE MODE; -- should pass -COMMIT; -\c -REVOKE DELETE ON lock_table FROM regress_locktable_user; - --- LOCK TABLE and TRUNCATE permission -GRANT TRUNCATE ON lock_table TO regress_locktable_user; -SET SESSION AUTHORIZATION regress_locktable_user; -BEGIN; -LOCK TABLE lock_table IN ROW EXCLUSIVE MODE; -- should pass -COMMIT; -BEGIN; -LOCK TABLE lock_table IN ACCESS SHARE MODE; -- should fail -ROLLBACK; -BEGIN; -LOCK TABLE lock_table IN ACCESS EXCLUSIVE MODE; -- should pass -COMMIT; -\c -REVOKE TRUNCATE ON lock_table FROM regress_locktable_user; - --- clean up -DROP TABLE lock_table; -DROP USER regress_locktable_user; - --- test to check privileges of system views pg_shmem_allocations and --- pg_backend_memory_contexts. - --- switch to superuser -\c - - -CREATE ROLE regress_readallstats; - -SELECT has_table_privilege('regress_readallstats','pg_backend_memory_contexts','SELECT'); -- no -SELECT has_table_privilege('regress_readallstats','pg_shmem_allocations','SELECT'); -- no - -GRANT pg_read_all_stats TO regress_readallstats; - -SELECT has_table_privilege('regress_readallstats','pg_backend_memory_contexts','SELECT'); -- yes -SELECT has_table_privilege('regress_readallstats','pg_shmem_allocations','SELECT'); -- yes - --- run query to ensure that functions within views can be executed -SET ROLE regress_readallstats; -SELECT COUNT(*) >= 0 AS ok FROM pg_backend_memory_contexts; -SELECT COUNT(*) >= 0 AS ok FROM pg_shmem_allocations; -RESET ROLE; - --- clean up -DROP ROLE regress_readallstats; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpsql.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpsql.sql deleted file mode 100644 index 1149c6a839..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpsql.sql +++ /dev/null @@ -1,1707 +0,0 @@ --- --- Tests for psql features that aren't closely connected to any --- specific server features --- - --- \set - --- fail: invalid name -\set invalid/name foo --- fail: invalid value for special variable -\set AUTOCOMMIT foo -\set FETCH_COUNT foo --- check handling of built-in boolean variable -\echo :ON_ERROR_ROLLBACK -\set ON_ERROR_ROLLBACK -\echo :ON_ERROR_ROLLBACK -\set ON_ERROR_ROLLBACK foo -\echo :ON_ERROR_ROLLBACK -\set ON_ERROR_ROLLBACK on -\echo :ON_ERROR_ROLLBACK -\unset ON_ERROR_ROLLBACK -\echo :ON_ERROR_ROLLBACK - --- \g and \gx - -SELECT 1 as one, 2 as two \g -\gx -SELECT 3 as three, 4 as four \gx -\g - --- \gx should work in FETCH_COUNT mode too -\set FETCH_COUNT 1 - -SELECT 1 as one, 2 as two \g -\gx -SELECT 3 as three, 4 as four \gx -\g - -\unset FETCH_COUNT - --- \g/\gx with pset options - -SELECT 1 as one, 2 as two \g (format=csv csv_fieldsep='\t') -\g -SELECT 1 as one, 2 as two \gx (title='foo bar') -\g - --- \gset - -select 10 as test01, 20 as test02, 'Hello' as test03 \gset pref01_ - -\echo :pref01_test01 :pref01_test02 :pref01_test03 - --- should fail: bad variable name -select 10 as "bad name" -\gset - -select 97 as "EOF", 'ok' as _foo \gset IGNORE -\echo :IGNORE_foo :IGNOREEOF - --- multiple backslash commands in one line -select 1 as x, 2 as y \gset pref01_ \\ \echo :pref01_x -select 3 as x, 4 as y \gset pref01_ \echo :pref01_x \echo :pref01_y -select 5 as x, 6 as y \gset pref01_ \\ \g \echo :pref01_x :pref01_y -select 7 as x, 8 as y \g \gset pref01_ \echo :pref01_x :pref01_y - --- NULL should unset the variable -\set var2 xyz -select 1 as var1, NULL as var2, 3 as var3 \gset -\echo :var1 :var2 :var3 - --- \gset requires just one tuple -select 10 as test01, 20 as test02 from generate_series(1,3) \gset -select 10 as test01, 20 as test02 from generate_series(1,0) \gset - --- \gset should work in FETCH_COUNT mode too -\set FETCH_COUNT 1 - -select 1 as x, 2 as y \gset pref01_ \\ \echo :pref01_x -select 3 as x, 4 as y \gset pref01_ \echo :pref01_x \echo :pref01_y -select 10 as test01, 20 as test02 from generate_series(1,3) \gset -select 10 as test01, 20 as test02 from generate_series(1,0) \gset - -\unset FETCH_COUNT - --- \gdesc - -SELECT - NULL AS zero, - 1 AS one, - 2.0 AS two, - 'three' AS three, - $1 AS four, - sin($2) as five, - 'foo'::varchar(4) as six, - CURRENT_DATE AS now -\gdesc - --- should work with tuple-returning utilities, such as EXECUTE -PREPARE test AS SELECT 1 AS first, 2 AS second; -EXECUTE test \gdesc -EXPLAIN EXECUTE test \gdesc - --- should fail cleanly - syntax error -SELECT 1 + \gdesc - --- check behavior with empty results -SELECT \gdesc -CREATE TABLE bububu(a int) \gdesc - --- subject command should not have executed -TABLE bububu; -- fail - --- query buffer should remain unchanged -SELECT 1 AS x, 'Hello', 2 AS y, true AS "dirty\name" -\gdesc -\g - --- all on one line -SELECT 3 AS x, 'Hello', 4 AS y, true AS "dirty\name" \gdesc \g - --- \gexec - -create temporary table gexec_test(a int, b text, c date, d float); -select format('create index on gexec_test(%I)', attname) -from pg_attribute -where attrelid = 'gexec_test'::regclass and attnum > 0 -order by attnum -\gexec - --- \gexec should work in FETCH_COUNT mode too --- (though the fetch limit applies to the executed queries not the meta query) -\set FETCH_COUNT 1 - -select 'select 1 as ones', 'select x.y, x.y*2 as double from generate_series(1,4) as x(y)' -union all -select 'drop table gexec_test', NULL -union all -select 'drop table gexec_test', 'select ''2000-01-01''::date as party_over' -\gexec - -\unset FETCH_COUNT - --- \setenv, \getenv - --- ensure MYVAR isn't set -\setenv MYVAR --- in which case, reading it doesn't change the target -\getenv res MYVAR -\echo :res --- now set it -\setenv MYVAR 'environment value' -\getenv res MYVAR -\echo :res - --- show all pset options -\pset - --- test multi-line headers, wrapping, and newline indicators --- in aligned, unaligned, and wrapped formats -prepare q as select array_to_string(array_agg(repeat('x',2*n)),E'\n') as "ab - -c", array_to_string(array_agg(repeat('y',20-2*n)),E'\n') as "a -bc" from generate_series(1,10) as n(n) group by n>1 order by n>1; - -\pset linestyle ascii - -\pset expanded off -\pset columns 40 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset expanded on -\pset columns 20 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset linestyle old-ascii - -\pset expanded off -\pset columns 40 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset expanded on -\pset columns 20 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -deallocate q; - --- test single-line header and data -prepare q as select repeat('x',2*n) as "0123456789abcdef", repeat('y',20-2*n) as "0123456789" from generate_series(1,10) as n; - -\pset linestyle ascii - -\pset expanded off -\pset columns 40 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset expanded on -\pset columns 30 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset expanded on -\pset columns 20 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset linestyle old-ascii - -\pset expanded off -\pset columns 40 - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset expanded on - -\pset border 0 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 1 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -\pset border 2 -\pset format unaligned -execute q; -\pset format aligned -execute q; -\pset format wrapped -execute q; - -deallocate q; - -\pset linestyle ascii -\pset border 1 - --- support table for output-format tests (useful to create a footer) - -create table psql_serial_tab (id serial); - --- test header/footer/tuples_only behavior in aligned/unaligned/wrapped cases - -\pset format aligned - -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false --- empty table is a special case for this format -select 1 where false; - -\pset format unaligned - -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -\pset format wrapped - -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - --- check conditional am display -\pset expanded off - -CREATE SCHEMA tableam_display; -CREATE ROLE regress_display_role; -ALTER SCHEMA tableam_display OWNER TO regress_display_role; -SET search_path TO tableam_display; -CREATE ACCESS METHOD heap_psql TYPE TABLE HANDLER heap_tableam_handler; -SET ROLE TO regress_display_role; --- Use only relations with a physical size of zero. -CREATE TABLE tbl_heap_psql(f1 int, f2 char(100)) using heap_psql; -CREATE TABLE tbl_heap(f1 int, f2 char(100)) using heap; -CREATE VIEW view_heap_psql AS SELECT f1 from tbl_heap_psql; -CREATE MATERIALIZED VIEW mat_view_heap_psql USING heap_psql AS SELECT f1 from tbl_heap_psql; -\d+ tbl_heap_psql -\d+ tbl_heap -\set HIDE_TABLEAM off -\d+ tbl_heap_psql -\d+ tbl_heap --- AM is displayed for tables, indexes and materialized views. -\d+ -\dt+ -\dm+ --- But not for views and sequences. -\dv+ -\set HIDE_TABLEAM on -\d+ -RESET ROLE; -RESET search_path; -DROP SCHEMA tableam_display CASCADE; -DROP ACCESS METHOD heap_psql; -DROP ROLE regress_display_role; - --- test numericlocale (as best we can without control of psql's locale) - -\pset format aligned -\pset expanded off -\pset numericlocale true - -select n, -n as m, n * 111 as x, '1e90'::float8 as f -from generate_series(0,3) n; - -\pset numericlocale false - --- test asciidoc output format - -\pset format asciidoc - -\pset border 1 -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -prepare q as - select 'some|text' as "a|title", ' ' as "empty ", n as int - from generate_series(1,2) as n; - -\pset expanded off -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -\pset expanded on -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -deallocate q; - --- test csv output format - -\pset format csv - -\pset border 1 -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -prepare q as - select 'some"text' as "a""title", E' \n' as "junk", - ' ' as "empty", n as int - from generate_series(1,2) as n; - -\pset expanded off -execute q; - -\pset expanded on -execute q; - -deallocate q; - --- special cases -\pset expanded off -select 'comma,comma' as comma, 'semi;semi' as semi; -\pset csv_fieldsep ';' -select 'comma,comma' as comma, 'semi;semi' as semi; -select '\.' as data; -\pset csv_fieldsep '.' -select '\' as d1, '' as d2; - --- illegal csv separators -\pset csv_fieldsep '' -\pset csv_fieldsep '\0' -\pset csv_fieldsep '\n' -\pset csv_fieldsep '\r' -\pset csv_fieldsep '"' -\pset csv_fieldsep ',,' - -\pset csv_fieldsep ',' - --- test html output format - -\pset format html - -\pset border 1 -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -prepare q as - select 'some"text' as "a&title", E' \n' as "junk", - ' ' as "empty", n as int - from generate_series(1,2) as n; - -\pset expanded off -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset tableattr foobar -execute q; -\pset tableattr - -\pset expanded on -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset tableattr foobar -execute q; -\pset tableattr - -deallocate q; - --- test latex output format - -\pset format latex - -\pset border 1 -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -prepare q as - select 'some\more_text' as "a$title", E' #%&^~|\n{bar}' as "junk", - ' ' as "empty", n as int - from generate_series(1,2) as n; - -\pset expanded off -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -\pset border 3 -execute q; - -\pset expanded on -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -\pset border 3 -execute q; - -deallocate q; - --- test latex-longtable output format - -\pset format latex-longtable - -\pset border 1 -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -prepare q as - select 'some\more_text' as "a$title", E' #%&^~|\n{bar}' as "junk", - ' ' as "empty", n as int - from generate_series(1,2) as n; - -\pset expanded off -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -\pset border 3 -execute q; - -\pset tableattr lr -execute q; -\pset tableattr - -\pset expanded on -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -\pset border 3 -execute q; - -\pset tableattr lr -execute q; -\pset tableattr - -deallocate q; - --- test troff-ms output format - -\pset format troff-ms - -\pset border 1 -\pset expanded off -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false -\pset expanded on -\d psql_serial_tab_id_seq -\pset tuples_only true -\df exp -\pset tuples_only false - -prepare q as - select 'some\text' as "a\title", E' \n' as "junk", - ' ' as "empty", n as int - from generate_series(1,2) as n; - -\pset expanded off -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -\pset expanded on -\pset border 0 -execute q; - -\pset border 1 -execute q; - -\pset border 2 -execute q; - -deallocate q; - --- check ambiguous format requests - -\pset format a -\pset format l - --- clean up after output format tests - -drop table psql_serial_tab; - -\pset format aligned -\pset expanded off -\pset border 1 - --- \echo and allied features - -\echo this is a test -\echo -n without newline -\echo with -n newline -\echo '-n' with newline - -\set foo bar -\echo foo = :foo - -\qecho this is a test -\qecho foo = :foo - -\warn this is a test -\warn foo = :foo - --- tests for \if ... \endif - -\if true - select 'okay'; - select 'still okay'; -\else - not okay; - still not okay -\endif - --- at this point query buffer should still have last valid line -\g - --- \if should work okay on part of a query -select - \if true - 42 - \else - (bogus - \endif - forty_two; - -select \if false \\ (bogus \else \\ 42 \endif \\ forty_two; - --- test a large nested if using a variety of true-equivalents -\if true - \if 1 - \if yes - \if on - \echo 'all true' - \else - \echo 'should not print #1-1' - \endif - \else - \echo 'should not print #1-2' - \endif - \else - \echo 'should not print #1-3' - \endif -\else - \echo 'should not print #1-4' -\endif - --- test a variety of false-equivalents in an if/elif/else structure -\if false - \echo 'should not print #2-1' -\elif 0 - \echo 'should not print #2-2' -\elif no - \echo 'should not print #2-3' -\elif off - \echo 'should not print #2-4' -\else - \echo 'all false' -\endif - --- test true-false elif after initial true branch -\if true - \echo 'should print #2-5' -\elif true - \echo 'should not print #2-6' -\elif false - \echo 'should not print #2-7' -\else - \echo 'should not print #2-8' -\endif - --- test simple true-then-else -\if true - \echo 'first thing true' -\else - \echo 'should not print #3-1' -\endif - --- test simple false-true-else -\if false - \echo 'should not print #4-1' -\elif true - \echo 'second thing true' -\else - \echo 'should not print #5-1' -\endif - --- invalid boolean expressions are false -\if invalid boolean expression - \echo 'will not print #6-1' -\else - \echo 'will print anyway #6-2' -\endif - --- test un-matched endif -\endif - --- test un-matched else -\else - --- test un-matched elif -\elif - --- test double-else error -\if true -\else -\else -\endif - --- test elif out-of-order -\if false -\else -\elif -\endif - --- test if-endif matching in a false branch -\if false - \if false - \echo 'should not print #7-1' - \else - \echo 'should not print #7-2' - \endif - \echo 'should not print #7-3' -\else - \echo 'should print #7-4' -\endif - --- show that vars and backticks are not expanded when ignoring extra args -\set foo bar -\echo :foo :'foo' :"foo" -\pset fieldsep | `nosuchcommand` :foo :'foo' :"foo" - --- show that vars and backticks are not expanded and commands are ignored --- when in a false if-branch -\set try_to_quit '\\q' -\if false - :try_to_quit - \echo `nosuchcommand` :foo :'foo' :"foo" - \pset fieldsep | `nosuchcommand` :foo :'foo' :"foo" - \a - \C arg1 - \c arg1 arg2 arg3 arg4 - \cd arg1 - \conninfo - \copy arg1 arg2 arg3 arg4 arg5 arg6 - \copyright - SELECT 1 as one, 2, 3 \crosstabview - \dt arg1 - \e arg1 arg2 - \ef whole_line - \ev whole_line - \echo arg1 arg2 arg3 arg4 arg5 - \echo arg1 - \encoding arg1 - \errverbose - \f arg1 - \g arg1 - \gx arg1 - \gexec - SELECT 1 AS one \gset - \h - \? - \html - \i arg1 - \ir arg1 - \l arg1 - \lo arg1 arg2 - \lo_list - \o arg1 - \p - \password arg1 - \prompt arg1 arg2 - \pset arg1 arg2 - \q - \reset - \s arg1 - \set arg1 arg2 arg3 arg4 arg5 arg6 arg7 - \setenv arg1 arg2 - \sf whole_line - \sv whole_line - \t arg1 - \T arg1 - \timing arg1 - \unset arg1 - \w arg1 - \watch arg1 - \x arg1 - -- \else here is eaten as part of OT_FILEPIPE argument - \w |/no/such/file \else - -- \endif here is eaten as part of whole-line argument - \! whole_line \endif - \z -\else - \echo 'should print #8-1' -\endif - --- :{?...} defined variable test -\set i 1 -\if :{?i} - \echo '#9-1 ok, variable i is defined' -\else - \echo 'should not print #9-2' -\endif - -\if :{?no_such_variable} - \echo 'should not print #10-1' -\else - \echo '#10-2 ok, variable no_such_variable is not defined' -\endif - -SELECT :{?i} AS i_is_defined; - -SELECT NOT :{?no_such_var} AS no_such_var_is_not_defined; - --- SHOW_CONTEXT - -\set SHOW_CONTEXT never -do $$ -begin - raise notice 'foo'; - raise exception 'bar'; -end $$; - -\set SHOW_CONTEXT errors -do $$ -begin - raise notice 'foo'; - raise exception 'bar'; -end $$; - -\set SHOW_CONTEXT always -do $$ -begin - raise notice 'foo'; - raise exception 'bar'; -end $$; - --- test printing and clearing the query buffer -SELECT 1; -\p -SELECT 2 \r -\p -SELECT 3 \p -UNION SELECT 4 \p -UNION SELECT 5 -ORDER BY 1; -\r -\p - --- tests for special result variables - --- working query, 2 rows selected -SELECT 1 AS stuff UNION SELECT 2; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT - --- syntax error -SELECT 1 UNION; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT -\echo 'last error message:' :LAST_ERROR_MESSAGE -\echo 'last error code:' :LAST_ERROR_SQLSTATE - --- empty query -; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT --- must have kept previous values -\echo 'last error message:' :LAST_ERROR_MESSAGE -\echo 'last error code:' :LAST_ERROR_SQLSTATE - --- other query error -DROP TABLE this_table_does_not_exist; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT -\echo 'last error message:' :LAST_ERROR_MESSAGE -\echo 'last error code:' :LAST_ERROR_SQLSTATE - --- nondefault verbosity error settings (except verbose, which is too unstable) -\set VERBOSITY terse -SELECT 1 UNION; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'last error message:' :LAST_ERROR_MESSAGE - -\set VERBOSITY sqlstate -SELECT 1/0; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'last error message:' :LAST_ERROR_MESSAGE - -\set VERBOSITY default - --- working \gdesc -SELECT 3 AS three, 4 AS four \gdesc -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT - --- \gdesc with an error -SELECT 4 AS \gdesc -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT -\echo 'last error message:' :LAST_ERROR_MESSAGE -\echo 'last error code:' :LAST_ERROR_SQLSTATE - --- check row count for a cursor-fetched query -\set FETCH_COUNT 10 -select unique2 from tenk1 order by unique2 limit 19; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT - --- cursor-fetched query with an error after the first group -select 1/(15-unique2) from tenk1 order by unique2 limit 19; -\echo 'error:' :ERROR -\echo 'error code:' :SQLSTATE -\echo 'number of rows:' :ROW_COUNT -\echo 'last error message:' :LAST_ERROR_MESSAGE -\echo 'last error code:' :LAST_ERROR_SQLSTATE - -\unset FETCH_COUNT - -create schema testpart; -create role regress_partitioning_role; - -alter schema testpart owner to regress_partitioning_role; - -set role to regress_partitioning_role; - --- run test inside own schema and hide other partitions -set search_path to testpart; - -create table testtable_apple(logdate date); -create table testtable_orange(logdate date); -create index testtable_apple_index on testtable_apple(logdate); -create index testtable_orange_index on testtable_orange(logdate); - -create table testpart_apple(logdate date) partition by range(logdate); -create table testpart_orange(logdate date) partition by range(logdate); - -create index testpart_apple_index on testpart_apple(logdate); -create index testpart_orange_index on testpart_orange(logdate); - --- only partition related object should be displayed -\dP test*apple* -\dPt test*apple* -\dPi test*apple* - -drop table testtable_apple; -drop table testtable_orange; -drop table testpart_apple; -drop table testpart_orange; - -create table parent_tab (id int) partition by range (id); -create index parent_index on parent_tab (id); -create table child_0_10 partition of parent_tab - for values from (0) to (10); -create table child_10_20 partition of parent_tab - for values from (10) to (20); -create table child_20_30 partition of parent_tab - for values from (20) to (30); -insert into parent_tab values (generate_series(0,29)); -create table child_30_40 partition of parent_tab -for values from (30) to (40) - partition by range(id); -create table child_30_35 partition of child_30_40 - for values from (30) to (35); -create table child_35_40 partition of child_30_40 - for values from (35) to (40); -insert into parent_tab values (generate_series(30,39)); - -\dPt -\dPi - -\dP testpart.* -\dP - -\dPtn -\dPin -\dPn -\dPn testpart.* - -drop table parent_tab cascade; - -drop schema testpart; - -set search_path to default; - -set role to default; -drop role regress_partitioning_role; - --- \d on toast table (use pg_statistic's toast table, which has a known name) -\d pg_toast.pg_toast_2619 - --- check printing info about access methods -\dA -\dA * -\dA h* -\dA foo -\dA foo bar -\dA+ -\dA+ * -\dA+ h* -\dA+ foo -\dAc brin pg*.oid* -\dAf spgist -\dAf btree int4 -\dAo+ btree float_ops -\dAo * pg_catalog.jsonb_path_ops -\dAp+ btree float_ops -\dAp * pg_catalog.uuid_ops - --- check \dconfig -set work_mem = 10240; -\dconfig work_mem -\dconfig+ work* -reset work_mem; - --- check \df, \do with argument specifications -\df *sqrt -\df *sqrt num* -\df int*pl -\df int*pl int4 -\df int*pl * pg_catalog.int8 -\df acl* aclitem[] -\df has_database_privilege oid text -\df has_database_privilege oid text - -\dfa bit* small* -\do - pg_catalog.int4 -\do && anyarray * - --- AUTOCOMMIT - -CREATE TABLE ac_test (a int); -\set AUTOCOMMIT off - -INSERT INTO ac_test VALUES (1); -COMMIT; -SELECT * FROM ac_test; -COMMIT; - -INSERT INTO ac_test VALUES (2); -ROLLBACK; -SELECT * FROM ac_test; -COMMIT; - -BEGIN; -INSERT INTO ac_test VALUES (3); -COMMIT; -SELECT * FROM ac_test; -COMMIT; - -BEGIN; -INSERT INTO ac_test VALUES (4); -ROLLBACK; -SELECT * FROM ac_test; -COMMIT; - -\set AUTOCOMMIT on -DROP TABLE ac_test; -SELECT * FROM ac_test; -- should be gone now - --- ON_ERROR_ROLLBACK - -\set ON_ERROR_ROLLBACK on -CREATE TABLE oer_test (a int); - -BEGIN; -INSERT INTO oer_test VALUES (1); -INSERT INTO oer_test VALUES ('foo'); -INSERT INTO oer_test VALUES (3); -COMMIT; -SELECT * FROM oer_test; - -BEGIN; -INSERT INTO oer_test VALUES (4); -ROLLBACK; -SELECT * FROM oer_test; - -BEGIN; -INSERT INTO oer_test VALUES (5); -COMMIT AND CHAIN; -INSERT INTO oer_test VALUES (6); -COMMIT; -SELECT * FROM oer_test; - -DROP TABLE oer_test; -\set ON_ERROR_ROLLBACK off - --- ECHO errors -\set ECHO errors -SELECT * FROM notexists; -\set ECHO all - --- --- combined queries --- -CREATE FUNCTION warn(msg TEXT) RETURNS BOOLEAN LANGUAGE plpgsql -AS $$ - BEGIN RAISE NOTICE 'warn %', msg ; RETURN TRUE ; END -$$; - --- show both -SELECT 1 AS one \; SELECT warn('1.5') \; SELECT 2 AS two ; --- \gset applies to last query only -SELECT 3 AS three \; SELECT warn('3.5') \; SELECT 4 AS four \gset -\echo :three :four --- syntax error stops all processing -SELECT 5 \; SELECT 6 + \; SELECT warn('6.5') \; SELECT 7 ; --- with aborted transaction, stop on first error -BEGIN \; SELECT 8 AS eight \; SELECT 9/0 AS nine \; ROLLBACK \; SELECT 10 AS ten ; --- close previously aborted transaction -ROLLBACK; - --- miscellaneous SQL commands --- (non SELECT output is sent to stderr, thus is not shown in expected results) -SELECT 'ok' AS "begin" \; -CREATE TABLE psql_comics(s TEXT) \; -INSERT INTO psql_comics VALUES ('Calvin'), ('hobbes') \; -COPY psql_comics FROM STDIN \; -UPDATE psql_comics SET s = 'Hobbes' WHERE s = 'hobbes' \; -DELETE FROM psql_comics WHERE s = 'Moe' \; -COPY psql_comics TO STDOUT \; -TRUNCATE psql_comics \; -DROP TABLE psql_comics \; -SELECT 'ok' AS "done" ; -Moe -Susie -\. - -\set SHOW_ALL_RESULTS off -SELECT 1 AS one \; SELECT warn('1.5') \; SELECT 2 AS two ; - -\set SHOW_ALL_RESULTS on -DROP FUNCTION warn(TEXT); - --- --- AUTOCOMMIT and combined queries --- -\set AUTOCOMMIT off -\echo '# AUTOCOMMIT:' :AUTOCOMMIT --- BEGIN is now implicit - -CREATE TABLE foo(s TEXT) \; -ROLLBACK; - -CREATE TABLE foo(s TEXT) \; -INSERT INTO foo(s) VALUES ('hello'), ('world') \; -COMMIT; - -DROP TABLE foo \; -ROLLBACK; - --- table foo is still there -SELECT * FROM foo ORDER BY 1 \; -DROP TABLE foo \; -COMMIT; - -\set AUTOCOMMIT on -\echo '# AUTOCOMMIT:' :AUTOCOMMIT --- BEGIN now explicit for multi-statement transactions - -BEGIN \; -CREATE TABLE foo(s TEXT) \; -INSERT INTO foo(s) VALUES ('hello'), ('world') \; -COMMIT; - -BEGIN \; -DROP TABLE foo \; -ROLLBACK \; - --- implicit transactions -SELECT * FROM foo ORDER BY 1 \; -DROP TABLE foo; - --- --- test ON_ERROR_ROLLBACK and combined queries --- -CREATE FUNCTION psql_error(msg TEXT) RETURNS BOOLEAN AS $$ - BEGIN - RAISE EXCEPTION 'error %', msg; - END; -$$ LANGUAGE plpgsql; - -\set ON_ERROR_ROLLBACK on -\echo '# ON_ERROR_ROLLBACK:' :ON_ERROR_ROLLBACK -\echo '# AUTOCOMMIT:' :AUTOCOMMIT - -BEGIN; -CREATE TABLE bla(s NO_SUCH_TYPE); -- fails -CREATE TABLE bla(s TEXT); -- succeeds -SELECT psql_error('oops!'); -- fails -INSERT INTO bla VALUES ('Calvin'), ('Hobbes'); -COMMIT; - -SELECT * FROM bla ORDER BY 1; - -BEGIN; -INSERT INTO bla VALUES ('Susie'); -- succeeds --- now with combined queries -INSERT INTO bla VALUES ('Rosalyn') \; -- will rollback -SELECT 'before error' AS show \; -- will show nevertheless! - SELECT psql_error('boum!') \; -- failure - SELECT 'after error' AS noshow; -- hidden by preceding error -INSERT INTO bla(s) VALUES ('Moe') \; -- will rollback - SELECT psql_error('bam!'); -INSERT INTO bla VALUES ('Miss Wormwood'); -- succeeds -COMMIT; -SELECT * FROM bla ORDER BY 1; - --- some with autocommit off -\set AUTOCOMMIT off -\echo '# AUTOCOMMIT:' :AUTOCOMMIT - --- implicit BEGIN -INSERT INTO bla VALUES ('Dad'); -- succeeds -SELECT psql_error('bad!'); -- implicit partial rollback - -INSERT INTO bla VALUES ('Mum') \; -- will rollback -SELECT COUNT(*) AS "#mum" -FROM bla WHERE s = 'Mum' \; -- but be counted here -SELECT psql_error('bad!'); -- implicit partial rollback -COMMIT; - -SELECT COUNT(*) AS "#mum" -FROM bla WHERE s = 'Mum' \; -- no mum here -SELECT * FROM bla ORDER BY 1; - --- reset all -\set AUTOCOMMIT on -\set ON_ERROR_ROLLBACK off -\echo '# final ON_ERROR_ROLLBACK:' :ON_ERROR_ROLLBACK -DROP TABLE bla; -DROP FUNCTION psql_error; - --- check describing invalid multipart names -\dA regression.heap -\dA nonesuch.heap -\dt host.regression.pg_catalog.pg_class -\dt |.pg_catalog.pg_class -\dt nonesuch.pg_catalog.pg_class -\da host.regression.pg_catalog.sum -\da +.pg_catalog.sum -\da nonesuch.pg_catalog.sum -\dAc nonesuch.brin -\dAc regression.brin -\dAf nonesuch.brin -\dAf regression.brin -\dAo nonesuch.brin -\dAo regression.brin -\dAp nonesuch.brin -\dAp regression.brin -\db nonesuch.pg_default -\db regression.pg_default -\dc host.regression.public.conversion -\dc (.public.conversion -\dc nonesuch.public.conversion -\dC host.regression.pg_catalog.int8 -\dC ).pg_catalog.int8 -\dC nonesuch.pg_catalog.int8 -\dd host.regression.pg_catalog.pg_class -\dd [.pg_catalog.pg_class -\dd nonesuch.pg_catalog.pg_class -\dD host.regression.public.gtestdomain1 -\dD ].public.gtestdomain1 -\dD nonesuch.public.gtestdomain1 -\ddp host.regression.pg_catalog.pg_class -\ddp {.pg_catalog.pg_class -\ddp nonesuch.pg_catalog.pg_class -\dE host.regression.public.ft -\dE }.public.ft -\dE nonesuch.public.ft -\di host.regression.public.tenk1_hundred -\di ..public.tenk1_hundred -\di nonesuch.public.tenk1_hundred -\dm host.regression.public.mvtest_bb -\dm ^.public.mvtest_bb -\dm nonesuch.public.mvtest_bb -\ds host.regression.public.check_seq -\ds regression|mydb.public.check_seq -\ds nonesuch.public.check_seq -\dt host.regression.public.b_star -\dt regres+ion.public.b_star -\dt nonesuch.public.b_star -\dv host.regression.public.shoe -\dv regress(ion).public.shoe -\dv nonesuch.public.shoe -\des nonesuch.server -\des regression.server -\des nonesuch.server -\des regression.server -\des nonesuch.username -\des regression.username -\dew nonesuch.fdw -\dew regression.fdw -\df host.regression.public.namelen -\df regres[qrstuv]ion.public.namelen -\df nonesuch.public.namelen -\dF host.regression.pg_catalog.arabic -\dF regres{1,2}ion.pg_catalog.arabic -\dF nonesuch.pg_catalog.arabic -\dFd host.regression.pg_catalog.arabic_stem -\dFd regres?ion.pg_catalog.arabic_stem -\dFd nonesuch.pg_catalog.arabic_stem -\dFp host.regression.pg_catalog.default -\dFp ^regression.pg_catalog.default -\dFp nonesuch.pg_catalog.default -\dFt host.regression.pg_catalog.ispell -\dFt regression$.pg_catalog.ispell -\dFt nonesuch.pg_catalog.ispell -\dg nonesuch.pg_database_owner -\dg regression.pg_database_owner -\dL host.regression.plpgsql -\dL *.plpgsql -\dL nonesuch.plpgsql -\dn host.regression.public -\dn """".public -\dn nonesuch.public -\do host.regression.public.!=- -\do "regression|mydb".public.!=- -\do nonesuch.public.!=- -\dO host.regression.pg_catalog.POSIX -\dO .pg_catalog.POSIX -\dO nonesuch.pg_catalog.POSIX -\dp host.regression.public.a_star -\dp "regres+ion".public.a_star -\dp nonesuch.public.a_star -\dP host.regression.public.mlparted -\dP "regres(sion)".public.mlparted -\dP nonesuch.public.mlparted -\drds nonesuch.lc_messages -\drds regression.lc_messages -\dRp public.mypub -\dRp regression.mypub -\dRs public.mysub -\dRs regression.mysub -\dT host.regression.public.widget -\dT "regression{1,2}".public.widget -\dT nonesuch.public.widget -\dx regression.plpgsql -\dx nonesuch.plpgsql -\dX host.regression.public.func_deps_stat -\dX "^regression$".public.func_deps_stat -\dX nonesuch.public.func_deps_stat -\dy regression.myevt -\dy nonesuch.myevt - --- check that dots within quoted name segments are not counted -\dA "no.such.access.method" -\dt "no.such.table.relation" -\da "no.such.aggregate.function" -\dAc "no.such.operator.class" -\dAf "no.such.operator.family" -\dAo "no.such.operator.of.operator.family" -\dAp "no.such.operator.support.function.of.operator.family" -\db "no.such.tablespace" -\dc "no.such.conversion" -\dC "no.such.cast" -\dd "no.such.object.description" -\dD "no.such.domain" -\ddp "no.such.default.access.privilege" -\di "no.such.index.relation" -\dm "no.such.materialized.view" -\ds "no.such.relation" -\dt "no.such.relation" -\dv "no.such.relation" -\des "no.such.foreign.server" -\dew "no.such.foreign.data.wrapper" -\df "no.such.function" -\dF "no.such.text.search.configuration" -\dFd "no.such.text.search.dictionary" -\dFp "no.such.text.search.parser" -\dFt "no.such.text.search.template" -\dg "no.such.role" -\dL "no.such.language" -\dn "no.such.schema" -\do "no.such.operator" -\dO "no.such.collation" -\dp "no.such.access.privilege" -\dP "no.such.partitioned.relation" -\drds "no.such.setting" -\dRp "no.such.publication" -\dRs "no.such.subscription" -\dT "no.such.data.type" -\dx "no.such.installed.extension" -\dX "no.such.extended.statistics" -\dy "no.such.event.trigger" - --- again, but with dotted schema qualifications. -\dA "no.such.schema"."no.such.access.method" -\dt "no.such.schema"."no.such.table.relation" -\da "no.such.schema"."no.such.aggregate.function" -\dAc "no.such.schema"."no.such.operator.class" -\dAf "no.such.schema"."no.such.operator.family" -\dAo "no.such.schema"."no.such.operator.of.operator.family" -\dAp "no.such.schema"."no.such.operator.support.function.of.operator.family" -\db "no.such.schema"."no.such.tablespace" -\dc "no.such.schema"."no.such.conversion" -\dC "no.such.schema"."no.such.cast" -\dd "no.such.schema"."no.such.object.description" -\dD "no.such.schema"."no.such.domain" -\ddp "no.such.schema"."no.such.default.access.privilege" -\di "no.such.schema"."no.such.index.relation" -\dm "no.such.schema"."no.such.materialized.view" -\ds "no.such.schema"."no.such.relation" -\dt "no.such.schema"."no.such.relation" -\dv "no.such.schema"."no.such.relation" -\des "no.such.schema"."no.such.foreign.server" -\dew "no.such.schema"."no.such.foreign.data.wrapper" -\df "no.such.schema"."no.such.function" -\dF "no.such.schema"."no.such.text.search.configuration" -\dFd "no.such.schema"."no.such.text.search.dictionary" -\dFp "no.such.schema"."no.such.text.search.parser" -\dFt "no.such.schema"."no.such.text.search.template" -\dg "no.such.schema"."no.such.role" -\dL "no.such.schema"."no.such.language" -\do "no.such.schema"."no.such.operator" -\dO "no.such.schema"."no.such.collation" -\dp "no.such.schema"."no.such.access.privilege" -\dP "no.such.schema"."no.such.partitioned.relation" -\drds "no.such.schema"."no.such.setting" -\dRp "no.such.schema"."no.such.publication" -\dRs "no.such.schema"."no.such.subscription" -\dT "no.such.schema"."no.such.data.type" -\dx "no.such.schema"."no.such.installed.extension" -\dX "no.such.schema"."no.such.extended.statistics" -\dy "no.such.schema"."no.such.event.trigger" - --- again, but with current database and dotted schema qualifications. -\dt regression."no.such.schema"."no.such.table.relation" -\da regression."no.such.schema"."no.such.aggregate.function" -\dc regression."no.such.schema"."no.such.conversion" -\dC regression."no.such.schema"."no.such.cast" -\dd regression."no.such.schema"."no.such.object.description" -\dD regression."no.such.schema"."no.such.domain" -\di regression."no.such.schema"."no.such.index.relation" -\dm regression."no.such.schema"."no.such.materialized.view" -\ds regression."no.such.schema"."no.such.relation" -\dt regression."no.such.schema"."no.such.relation" -\dv regression."no.such.schema"."no.such.relation" -\df regression."no.such.schema"."no.such.function" -\dF regression."no.such.schema"."no.such.text.search.configuration" -\dFd regression."no.such.schema"."no.such.text.search.dictionary" -\dFp regression."no.such.schema"."no.such.text.search.parser" -\dFt regression."no.such.schema"."no.such.text.search.template" -\do regression."no.such.schema"."no.such.operator" -\dO regression."no.such.schema"."no.such.collation" -\dp regression."no.such.schema"."no.such.access.privilege" -\dP regression."no.such.schema"."no.such.partitioned.relation" -\dT regression."no.such.schema"."no.such.data.type" -\dX regression."no.such.schema"."no.such.extended.statistics" - --- again, but with dotted database and dotted schema qualifications. -\dt "no.such.database"."no.such.schema"."no.such.table.relation" -\da "no.such.database"."no.such.schema"."no.such.aggregate.function" -\dc "no.such.database"."no.such.schema"."no.such.conversion" -\dC "no.such.database"."no.such.schema"."no.such.cast" -\dd "no.such.database"."no.such.schema"."no.such.object.description" -\dD "no.such.database"."no.such.schema"."no.such.domain" -\ddp "no.such.database"."no.such.schema"."no.such.default.access.privilege" -\di "no.such.database"."no.such.schema"."no.such.index.relation" -\dm "no.such.database"."no.such.schema"."no.such.materialized.view" -\ds "no.such.database"."no.such.schema"."no.such.relation" -\dt "no.such.database"."no.such.schema"."no.such.relation" -\dv "no.such.database"."no.such.schema"."no.such.relation" -\df "no.such.database"."no.such.schema"."no.such.function" -\dF "no.such.database"."no.such.schema"."no.such.text.search.configuration" -\dFd "no.such.database"."no.such.schema"."no.such.text.search.dictionary" -\dFp "no.such.database"."no.such.schema"."no.such.text.search.parser" -\dFt "no.such.database"."no.such.schema"."no.such.text.search.template" -\do "no.such.database"."no.such.schema"."no.such.operator" -\dO "no.such.database"."no.such.schema"."no.such.collation" -\dp "no.such.database"."no.such.schema"."no.such.access.privilege" -\dP "no.such.database"."no.such.schema"."no.such.partitioned.relation" -\dT "no.such.database"."no.such.schema"."no.such.data.type" -\dX "no.such.database"."no.such.schema"."no.such.extended.statistics" diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpublication.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpublication.sql deleted file mode 100644 index 9eb86fd54f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fpublication.sql +++ /dev/null @@ -1,1062 +0,0 @@ --- --- PUBLICATION --- -CREATE ROLE regress_publication_user LOGIN SUPERUSER; -CREATE ROLE regress_publication_user2; -CREATE ROLE regress_publication_user_dummy LOGIN NOSUPERUSER; -SET SESSION AUTHORIZATION 'regress_publication_user'; - --- suppress warning that depends on wal_level -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_default; -RESET client_min_messages; - -COMMENT ON PUBLICATION testpub_default IS 'test publication'; -SELECT obj_description(p.oid, 'pg_publication') FROM pg_publication p; - -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpib_ins_trunct WITH (publish = insert); -RESET client_min_messages; - -ALTER PUBLICATION testpub_default SET (publish = update); - --- error cases -CREATE PUBLICATION testpub_xxx WITH (foo); -CREATE PUBLICATION testpub_xxx WITH (publish = 'cluster, vacuum'); -CREATE PUBLICATION testpub_xxx WITH (publish_via_partition_root = 'true', publish_via_partition_root = '0'); - -\dRp - -ALTER PUBLICATION testpub_default SET (publish = 'insert, update, delete'); - -\dRp - ---- adding tables -CREATE SCHEMA pub_test; -CREATE TABLE testpub_tbl1 (id serial primary key, data text); -CREATE TABLE pub_test.testpub_nopk (foo int, bar int); -CREATE VIEW testpub_view AS SELECT 1; -CREATE TABLE testpub_parted (a int) PARTITION BY LIST (a); - -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_foralltables FOR ALL TABLES WITH (publish = 'insert'); -RESET client_min_messages; -ALTER PUBLICATION testpub_foralltables SET (publish = 'insert, update'); - -CREATE TABLE testpub_tbl2 (id serial primary key, data text); --- fail - can't add to for all tables publication -ALTER PUBLICATION testpub_foralltables ADD TABLE testpub_tbl2; --- fail - can't drop from all tables publication -ALTER PUBLICATION testpub_foralltables DROP TABLE testpub_tbl2; --- fail - can't add to for all tables publication -ALTER PUBLICATION testpub_foralltables SET TABLE pub_test.testpub_nopk; - --- fail - can't add schema to 'FOR ALL TABLES' publication -ALTER PUBLICATION testpub_foralltables ADD ALL TABLES IN SCHEMA pub_test; --- fail - can't drop schema from 'FOR ALL TABLES' publication -ALTER PUBLICATION testpub_foralltables DROP ALL TABLES IN SCHEMA pub_test; --- fail - can't set schema to 'FOR ALL TABLES' publication -ALTER PUBLICATION testpub_foralltables SET ALL TABLES IN SCHEMA pub_test; - -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_fortable FOR TABLE testpub_tbl1; -RESET client_min_messages; --- should be able to add schema to 'FOR TABLE' publication -ALTER PUBLICATION testpub_fortable ADD ALL TABLES IN SCHEMA pub_test; -\dRp+ testpub_fortable --- should be able to drop schema from 'FOR TABLE' publication -ALTER PUBLICATION testpub_fortable DROP ALL TABLES IN SCHEMA pub_test; -\dRp+ testpub_fortable --- should be able to set schema to 'FOR TABLE' publication -ALTER PUBLICATION testpub_fortable SET ALL TABLES IN SCHEMA pub_test; -\dRp+ testpub_fortable - -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_forschema FOR ALL TABLES IN SCHEMA pub_test; -RESET client_min_messages; --- fail - can't create publication with schema and table of the same schema -CREATE PUBLICATION testpub_for_tbl_schema FOR ALL TABLES IN SCHEMA pub_test, TABLE pub_test.testpub_nopk; --- fail - can't add a table of the same schema to the schema publication -ALTER PUBLICATION testpub_forschema ADD TABLE pub_test.testpub_nopk; --- fail - can't drop a table from the schema publication which isn't in the --- publication -ALTER PUBLICATION testpub_forschema DROP TABLE pub_test.testpub_nopk; --- should be able to set table to schema publication -ALTER PUBLICATION testpub_forschema SET TABLE pub_test.testpub_nopk; -\dRp+ testpub_forschema - -SELECT pubname, puballtables FROM pg_publication WHERE pubname = 'testpub_foralltables'; -\d+ testpub_tbl2 -\dRp+ testpub_foralltables - -DROP TABLE testpub_tbl2; -DROP PUBLICATION testpub_foralltables, testpub_fortable, testpub_forschema; - -CREATE TABLE testpub_tbl3 (a int); -CREATE TABLE testpub_tbl3a (b text) INHERITS (testpub_tbl3); -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub3 FOR TABLE testpub_tbl3; -CREATE PUBLICATION testpub4 FOR TABLE ONLY testpub_tbl3; -RESET client_min_messages; -\dRp+ testpub3 -\dRp+ testpub4 - -DROP TABLE testpub_tbl3, testpub_tbl3a; -DROP PUBLICATION testpub3, testpub4; - --- Tests for partitioned tables -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_forparted; -CREATE PUBLICATION testpub_forparted1; -RESET client_min_messages; -CREATE TABLE testpub_parted1 (LIKE testpub_parted); -CREATE TABLE testpub_parted2 (LIKE testpub_parted); -ALTER PUBLICATION testpub_forparted1 SET (publish='insert'); -ALTER TABLE testpub_parted ATTACH PARTITION testpub_parted1 FOR VALUES IN (1); -ALTER TABLE testpub_parted ATTACH PARTITION testpub_parted2 FOR VALUES IN (2); --- works despite missing REPLICA IDENTITY, because updates are not replicated -UPDATE testpub_parted1 SET a = 1; --- only parent is listed as being in publication, not the partition -ALTER PUBLICATION testpub_forparted ADD TABLE testpub_parted; -\dRp+ testpub_forparted --- should now fail, because parent's publication replicates updates -UPDATE testpub_parted1 SET a = 1; -ALTER TABLE testpub_parted DETACH PARTITION testpub_parted1; --- works again, because parent's publication is no longer considered -UPDATE testpub_parted1 SET a = 1; -ALTER PUBLICATION testpub_forparted SET (publish_via_partition_root = true); -\dRp+ testpub_forparted --- still fail, because parent's publication replicates updates -UPDATE testpub_parted2 SET a = 2; -ALTER PUBLICATION testpub_forparted DROP TABLE testpub_parted; --- works again, because update is no longer replicated -UPDATE testpub_parted2 SET a = 2; -DROP TABLE testpub_parted1, testpub_parted2; -DROP PUBLICATION testpub_forparted, testpub_forparted1; - --- Tests for row filters -CREATE TABLE testpub_rf_tbl1 (a integer, b text); -CREATE TABLE testpub_rf_tbl2 (c text, d integer); -CREATE TABLE testpub_rf_tbl3 (e integer); -CREATE TABLE testpub_rf_tbl4 (g text); -CREATE TABLE testpub_rf_tbl5 (a xml); -CREATE SCHEMA testpub_rf_schema1; -CREATE TABLE testpub_rf_schema1.testpub_rf_tbl5 (h integer); -CREATE SCHEMA testpub_rf_schema2; -CREATE TABLE testpub_rf_schema2.testpub_rf_tbl6 (i integer); -SET client_min_messages = 'ERROR'; --- Firstly, test using the option publish='insert' because the row filter --- validation of referenced columns is less strict than for delete/update. -CREATE PUBLICATION testpub5 FOR TABLE testpub_rf_tbl1, testpub_rf_tbl2 WHERE (c <> 'test' AND d < 5) WITH (publish = 'insert'); -RESET client_min_messages; -\dRp+ testpub5 -\d testpub_rf_tbl3 -ALTER PUBLICATION testpub5 ADD TABLE testpub_rf_tbl3 WHERE (e > 1000 AND e < 2000); -\dRp+ testpub5 -\d testpub_rf_tbl3 -ALTER PUBLICATION testpub5 DROP TABLE testpub_rf_tbl2; -\dRp+ testpub5 --- remove testpub_rf_tbl1 and add testpub_rf_tbl3 again (another WHERE expression) -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl3 WHERE (e > 300 AND e < 500); -\dRp+ testpub5 -\d testpub_rf_tbl3 --- test \d (now it displays filter information) -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_rf_yes FOR TABLE testpub_rf_tbl1 WHERE (a > 1) WITH (publish = 'insert'); -CREATE PUBLICATION testpub_rf_no FOR TABLE testpub_rf_tbl1; -RESET client_min_messages; -\d testpub_rf_tbl1 -DROP PUBLICATION testpub_rf_yes, testpub_rf_no; --- some more syntax tests to exercise other parser pathways -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_syntax1 FOR TABLE testpub_rf_tbl1, ONLY testpub_rf_tbl3 WHERE (e < 999) WITH (publish = 'insert'); -RESET client_min_messages; -\dRp+ testpub_syntax1 -DROP PUBLICATION testpub_syntax1; -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_syntax2 FOR TABLE testpub_rf_tbl1, testpub_rf_schema1.testpub_rf_tbl5 WHERE (h < 999) WITH (publish = 'insert'); -RESET client_min_messages; -\dRp+ testpub_syntax2 -DROP PUBLICATION testpub_syntax2; --- fail - schemas don't allow WHERE clause -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_syntax3 FOR ALL TABLES IN SCHEMA testpub_rf_schema1 WHERE (a = 123); -CREATE PUBLICATION testpub_syntax3 FOR ALL TABLES IN SCHEMA testpub_rf_schema1, testpub_rf_schema1 WHERE (a = 123); -RESET client_min_messages; --- fail - duplicate tables are not allowed if that table has any WHERE clause -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_dups FOR TABLE testpub_rf_tbl1 WHERE (a = 1), testpub_rf_tbl1 WITH (publish = 'insert'); -CREATE PUBLICATION testpub_dups FOR TABLE testpub_rf_tbl1, testpub_rf_tbl1 WHERE (a = 2) WITH (publish = 'insert'); -RESET client_min_messages; --- fail - publication WHERE clause must be boolean -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl3 WHERE (1234); --- fail - aggregate functions not allowed in WHERE clause -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl3 WHERE (e < AVG(e)); --- fail - user-defined operators are not allowed -CREATE FUNCTION testpub_rf_func1(integer, integer) RETURNS boolean AS $$ SELECT hashint4($1) > $2 $$ LANGUAGE SQL; -CREATE OPERATOR =#> (PROCEDURE = testpub_rf_func1, LEFTARG = integer, RIGHTARG = integer); -CREATE PUBLICATION testpub6 FOR TABLE testpub_rf_tbl3 WHERE (e =#> 27); --- fail - user-defined functions are not allowed -CREATE FUNCTION testpub_rf_func2() RETURNS integer AS $$ BEGIN RETURN 123; END; $$ LANGUAGE plpgsql; -ALTER PUBLICATION testpub5 ADD TABLE testpub_rf_tbl1 WHERE (a >= testpub_rf_func2()); --- fail - non-immutable functions are not allowed. random() is volatile. -ALTER PUBLICATION testpub5 ADD TABLE testpub_rf_tbl1 WHERE (a < random()); --- fail - user-defined collations are not allowed -CREATE COLLATION user_collation FROM "C"; -ALTER PUBLICATION testpub5 ADD TABLE testpub_rf_tbl1 WHERE (b < '2' COLLATE user_collation); --- ok - NULLIF is allowed -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (NULLIF(1,2) = a); --- ok - built-in operators are allowed -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (a IS NULL); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE ((a > 5) IS FALSE); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (a IS DISTINCT FROM 5); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE ((a, a + 1) < (2, 3)); --- ok - built-in type coercions between two binary compatible datatypes are allowed -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (b::varchar < '2'); --- ok - immutable built-in functions are allowed -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl4 WHERE (length(g) < 6); --- fail - user-defined types are not allowed -CREATE TYPE rf_bug_status AS ENUM ('new', 'open', 'closed'); -CREATE TABLE rf_bug (id serial, description text, status rf_bug_status); -CREATE PUBLICATION testpub6 FOR TABLE rf_bug WHERE (status = 'open') WITH (publish = 'insert'); -DROP TABLE rf_bug; -DROP TYPE rf_bug_status; --- fail - row filter expression is not simple -CREATE PUBLICATION testpub6 FOR TABLE testpub_rf_tbl1 WHERE (a IN (SELECT generate_series(1,5))); --- fail - system columns are not allowed -CREATE PUBLICATION testpub6 FOR TABLE testpub_rf_tbl1 WHERE ('(0,1)'::tid = ctid); --- ok - conditional expressions are allowed -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl5 WHERE (a IS DOCUMENT); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl5 WHERE (xmlexists('//foo[text() = ''bar'']' PASSING BY VALUE a)); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (NULLIF(1, 2) = a); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (CASE a WHEN 5 THEN true ELSE false END); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (COALESCE(b, 'foo') = 'foo'); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (GREATEST(a, 10) > 10); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (a IN (2, 4, 6)); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (ARRAY[a] <@ ARRAY[2, 4, 6]); -ALTER PUBLICATION testpub5 SET TABLE testpub_rf_tbl1 WHERE (ROW(a, 2) IS NULL); --- fail - WHERE not allowed in DROP -ALTER PUBLICATION testpub5 DROP TABLE testpub_rf_tbl1 WHERE (e < 27); --- fail - cannot ALTER SET table which is a member of a pre-existing schema -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub6 FOR ALL TABLES IN SCHEMA testpub_rf_schema2; -ALTER PUBLICATION testpub6 SET ALL TABLES IN SCHEMA testpub_rf_schema2, TABLE testpub_rf_schema2.testpub_rf_tbl6 WHERE (i < 99); -RESET client_min_messages; - -DROP TABLE testpub_rf_tbl1; -DROP TABLE testpub_rf_tbl2; -DROP TABLE testpub_rf_tbl3; -DROP TABLE testpub_rf_tbl4; -DROP TABLE testpub_rf_tbl5; -DROP TABLE testpub_rf_schema1.testpub_rf_tbl5; -DROP TABLE testpub_rf_schema2.testpub_rf_tbl6; -DROP SCHEMA testpub_rf_schema1; -DROP SCHEMA testpub_rf_schema2; -DROP PUBLICATION testpub5; -DROP PUBLICATION testpub6; -DROP OPERATOR =#>(integer, integer); -DROP FUNCTION testpub_rf_func1(integer, integer); -DROP FUNCTION testpub_rf_func2(); -DROP COLLATION user_collation; - --- ====================================================== --- More row filter tests for validating column references -CREATE TABLE rf_tbl_abcd_nopk(a int, b int, c int, d int); -CREATE TABLE rf_tbl_abcd_pk(a int, b int, c int, d int, PRIMARY KEY(a,b)); -CREATE TABLE rf_tbl_abcd_part_pk (a int PRIMARY KEY, b int) PARTITION by RANGE (a); -CREATE TABLE rf_tbl_abcd_part_pk_1 (b int, a int PRIMARY KEY); -ALTER TABLE rf_tbl_abcd_part_pk ATTACH PARTITION rf_tbl_abcd_part_pk_1 FOR VALUES FROM (1) TO (10); - --- Case 1. REPLICA IDENTITY DEFAULT (means use primary key or nothing) --- 1a. REPLICA IDENTITY is DEFAULT and table has a PK. -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub6 FOR TABLE rf_tbl_abcd_pk WHERE (a > 99); -RESET client_min_messages; --- ok - "a" is a PK col -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (b > 99); --- ok - "b" is a PK col -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (c > 99); --- fail - "c" is not part of the PK -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (d > 99); --- fail - "d" is not part of the PK -UPDATE rf_tbl_abcd_pk SET a = 1; --- 1b. REPLICA IDENTITY is DEFAULT and table has no PK -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk WHERE (a > 99); --- fail - "a" is not part of REPLICA IDENTITY -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Case 2. REPLICA IDENTITY FULL -ALTER TABLE rf_tbl_abcd_pk REPLICA IDENTITY FULL; -ALTER TABLE rf_tbl_abcd_nopk REPLICA IDENTITY FULL; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (c > 99); --- ok - "c" is in REPLICA IDENTITY now even though not in PK -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk WHERE (a > 99); --- ok - "a" is in REPLICA IDENTITY now -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Case 3. REPLICA IDENTITY NOTHING -ALTER TABLE rf_tbl_abcd_pk REPLICA IDENTITY NOTHING; -ALTER TABLE rf_tbl_abcd_nopk REPLICA IDENTITY NOTHING; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (a > 99); --- fail - "a" is in PK but it is not part of REPLICA IDENTITY NOTHING -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (c > 99); --- fail - "c" is not in PK and not in REPLICA IDENTITY NOTHING -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk WHERE (a > 99); --- fail - "a" is not in REPLICA IDENTITY NOTHING -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Case 4. REPLICA IDENTITY INDEX -ALTER TABLE rf_tbl_abcd_pk ALTER COLUMN c SET NOT NULL; -CREATE UNIQUE INDEX idx_abcd_pk_c ON rf_tbl_abcd_pk(c); -ALTER TABLE rf_tbl_abcd_pk REPLICA IDENTITY USING INDEX idx_abcd_pk_c; -ALTER TABLE rf_tbl_abcd_nopk ALTER COLUMN c SET NOT NULL; -CREATE UNIQUE INDEX idx_abcd_nopk_c ON rf_tbl_abcd_nopk(c); -ALTER TABLE rf_tbl_abcd_nopk REPLICA IDENTITY USING INDEX idx_abcd_nopk_c; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (a > 99); --- fail - "a" is in PK but it is not part of REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk WHERE (c > 99); --- ok - "c" is not in PK but it is part of REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk WHERE (a > 99); --- fail - "a" is not in REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_nopk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk WHERE (c > 99); --- ok - "c" is part of REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Tests for partitioned table - --- set PUBLISH_VIA_PARTITION_ROOT to false and test row filter for partitioned --- table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- fail - cannot use row filter for partitioned table -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk WHERE (a > 99); --- ok - can use row filter for partition -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk_1 WHERE (a > 99); --- ok - "a" is a PK col -UPDATE rf_tbl_abcd_part_pk SET a = 1; --- set PUBLISH_VIA_PARTITION_ROOT to true and test row filter for partitioned --- table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=1); --- ok - can use row filter for partitioned table -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk WHERE (a > 99); --- ok - "a" is a PK col -UPDATE rf_tbl_abcd_part_pk SET a = 1; --- fail - cannot set PUBLISH_VIA_PARTITION_ROOT to false if any row filter is --- used for partitioned table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- remove partitioned table's row filter -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk; --- ok - we don't have row filter for partitioned table. -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- Now change the root filter to use a column "b" --- (which is not in the replica identity) -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk_1 WHERE (b > 99); --- ok - we don't have row filter for partitioned table. -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- fail - "b" is not in REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_part_pk SET a = 1; --- set PUBLISH_VIA_PARTITION_ROOT to true --- can use row filter for partitioned table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=1); --- ok - can use row filter for partitioned table -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk WHERE (b > 99); --- fail - "b" is not in REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_part_pk SET a = 1; - -DROP PUBLICATION testpub6; -DROP TABLE rf_tbl_abcd_pk; -DROP TABLE rf_tbl_abcd_nopk; -DROP TABLE rf_tbl_abcd_part_pk; --- ====================================================== - --- fail - duplicate tables are not allowed if that table has any column lists -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_dups FOR TABLE testpub_tbl1 (a), testpub_tbl1 WITH (publish = 'insert'); -CREATE PUBLICATION testpub_dups FOR TABLE testpub_tbl1, testpub_tbl1 (a) WITH (publish = 'insert'); -RESET client_min_messages; - --- test for column lists -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_fortable FOR TABLE testpub_tbl1; -CREATE PUBLICATION testpub_fortable_insert WITH (publish = 'insert'); -RESET client_min_messages; -CREATE TABLE testpub_tbl5 (a int PRIMARY KEY, b text, c text, - d int generated always as (a + length(b)) stored); --- error: column "x" does not exist -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl5 (a, x); --- error: replica identity "a" not included in the column list -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl5 (b, c); -UPDATE testpub_tbl5 SET a = 1; -ALTER PUBLICATION testpub_fortable DROP TABLE testpub_tbl5; --- error: generated column "d" can't be in list -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl5 (a, d); --- error: system attributes "ctid" not allowed in column list -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl5 (a, ctid); --- ok -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl5 (a, c); -ALTER TABLE testpub_tbl5 DROP COLUMN c; -- no dice --- ok: for insert-only publication, any column list is acceptable -ALTER PUBLICATION testpub_fortable_insert ADD TABLE testpub_tbl5 (b, c); - -/* not all replica identities are good enough */ -CREATE UNIQUE INDEX testpub_tbl5_b_key ON testpub_tbl5 (b, c); -ALTER TABLE testpub_tbl5 ALTER b SET NOT NULL, ALTER c SET NOT NULL; -ALTER TABLE testpub_tbl5 REPLICA IDENTITY USING INDEX testpub_tbl5_b_key; --- error: replica identity (b,c) is not covered by column list (a, c) -UPDATE testpub_tbl5 SET a = 1; -ALTER PUBLICATION testpub_fortable DROP TABLE testpub_tbl5; - --- error: change the replica identity to "b", and column list to (a, c) --- then update fails, because (a, c) does not cover replica identity -ALTER TABLE testpub_tbl5 REPLICA IDENTITY USING INDEX testpub_tbl5_b_key; -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl5 (a, c); -UPDATE testpub_tbl5 SET a = 1; - -/* But if upd/del are not published, it works OK */ -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_table_ins WITH (publish = 'insert, truncate'); -RESET client_min_messages; -ALTER PUBLICATION testpub_table_ins ADD TABLE testpub_tbl5 (a); -- ok -\dRp+ testpub_table_ins - --- tests with REPLICA IDENTITY FULL -CREATE TABLE testpub_tbl6 (a int, b text, c text); -ALTER TABLE testpub_tbl6 REPLICA IDENTITY FULL; - -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl6 (a, b, c); -UPDATE testpub_tbl6 SET a = 1; -ALTER PUBLICATION testpub_fortable DROP TABLE testpub_tbl6; - -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl6; -- ok -UPDATE testpub_tbl6 SET a = 1; - --- make sure changing the column list is propagated to the catalog -CREATE TABLE testpub_tbl7 (a int primary key, b text, c text); -ALTER PUBLICATION testpub_fortable ADD TABLE testpub_tbl7 (a, b); -\d+ testpub_tbl7 --- ok: the column list is the same, we should skip this table (or at least not fail) -ALTER PUBLICATION testpub_fortable SET TABLE testpub_tbl7 (a, b); -\d+ testpub_tbl7 --- ok: the column list changes, make sure the catalog gets updated -ALTER PUBLICATION testpub_fortable SET TABLE testpub_tbl7 (a, c); -\d+ testpub_tbl7 - --- column list for partitioned tables has to cover replica identities for --- all child relations -CREATE TABLE testpub_tbl8 (a int, b text, c text) PARTITION BY HASH (a); --- first partition has replica identity "a" -CREATE TABLE testpub_tbl8_0 PARTITION OF testpub_tbl8 FOR VALUES WITH (modulus 2, remainder 0); -ALTER TABLE testpub_tbl8_0 ADD PRIMARY KEY (a); -ALTER TABLE testpub_tbl8_0 REPLICA IDENTITY USING INDEX testpub_tbl8_0_pkey; --- second partition has replica identity "b" -CREATE TABLE testpub_tbl8_1 PARTITION OF testpub_tbl8 FOR VALUES WITH (modulus 2, remainder 1); -ALTER TABLE testpub_tbl8_1 ADD PRIMARY KEY (b); -ALTER TABLE testpub_tbl8_1 REPLICA IDENTITY USING INDEX testpub_tbl8_1_pkey; - --- ok: column list covers both "a" and "b" -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_col_list FOR TABLE testpub_tbl8 (a, b) WITH (publish_via_partition_root = 'true'); -RESET client_min_messages; - --- ok: the same thing, but try plain ADD TABLE -ALTER PUBLICATION testpub_col_list DROP TABLE testpub_tbl8; -ALTER PUBLICATION testpub_col_list ADD TABLE testpub_tbl8 (a, b); -UPDATE testpub_tbl8 SET a = 1; - --- failure: column list does not cover replica identity for the second partition -ALTER PUBLICATION testpub_col_list DROP TABLE testpub_tbl8; -ALTER PUBLICATION testpub_col_list ADD TABLE testpub_tbl8 (a, c); -UPDATE testpub_tbl8 SET a = 1; -ALTER PUBLICATION testpub_col_list DROP TABLE testpub_tbl8; - --- failure: one of the partitions has REPLICA IDENTITY FULL -ALTER TABLE testpub_tbl8_1 REPLICA IDENTITY FULL; -ALTER PUBLICATION testpub_col_list ADD TABLE testpub_tbl8 (a, c); -UPDATE testpub_tbl8 SET a = 1; -ALTER PUBLICATION testpub_col_list DROP TABLE testpub_tbl8; - --- add table and then try changing replica identity -ALTER TABLE testpub_tbl8_1 REPLICA IDENTITY USING INDEX testpub_tbl8_1_pkey; -ALTER PUBLICATION testpub_col_list ADD TABLE testpub_tbl8 (a, b); - --- failure: replica identity full can't be used with a column list -ALTER TABLE testpub_tbl8_1 REPLICA IDENTITY FULL; -UPDATE testpub_tbl8 SET a = 1; - --- failure: replica identity has to be covered by the column list -ALTER TABLE testpub_tbl8_1 DROP CONSTRAINT testpub_tbl8_1_pkey; -ALTER TABLE testpub_tbl8_1 ADD PRIMARY KEY (c); -ALTER TABLE testpub_tbl8_1 REPLICA IDENTITY USING INDEX testpub_tbl8_1_pkey; -UPDATE testpub_tbl8 SET a = 1; - -DROP TABLE testpub_tbl8; - --- column list for partitioned tables has to cover replica identities for --- all child relations -CREATE TABLE testpub_tbl8 (a int, b text, c text) PARTITION BY HASH (a); -ALTER PUBLICATION testpub_col_list ADD TABLE testpub_tbl8 (a, b); --- first partition has replica identity "a" -CREATE TABLE testpub_tbl8_0 (a int, b text, c text); -ALTER TABLE testpub_tbl8_0 ADD PRIMARY KEY (a); -ALTER TABLE testpub_tbl8_0 REPLICA IDENTITY USING INDEX testpub_tbl8_0_pkey; --- second partition has replica identity "b" -CREATE TABLE testpub_tbl8_1 (a int, b text, c text); -ALTER TABLE testpub_tbl8_1 ADD PRIMARY KEY (c); -ALTER TABLE testpub_tbl8_1 REPLICA IDENTITY USING INDEX testpub_tbl8_1_pkey; - --- ok: attaching first partition works, because (a) is in column list -ALTER TABLE testpub_tbl8 ATTACH PARTITION testpub_tbl8_0 FOR VALUES WITH (modulus 2, remainder 0); --- failure: second partition has replica identity (c), which si not in column list -ALTER TABLE testpub_tbl8 ATTACH PARTITION testpub_tbl8_1 FOR VALUES WITH (modulus 2, remainder 1); -UPDATE testpub_tbl8 SET a = 1; - --- failure: changing replica identity to FULL for partition fails, because --- of the column list on the parent -ALTER TABLE testpub_tbl8_0 REPLICA IDENTITY FULL; -UPDATE testpub_tbl8 SET a = 1; - -DROP TABLE testpub_tbl5, testpub_tbl6, testpub_tbl7, testpub_tbl8, testpub_tbl8_1; -DROP PUBLICATION testpub_table_ins, testpub_fortable, testpub_fortable_insert, testpub_col_list; --- ====================================================== - --- Test combination of column list and row filter -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_both_filters; -RESET client_min_messages; -CREATE TABLE testpub_tbl_both_filters (a int, b int, c int, PRIMARY KEY (a,c)); -ALTER TABLE testpub_tbl_both_filters REPLICA IDENTITY USING INDEX testpub_tbl_both_filters_pkey; -ALTER PUBLICATION testpub_both_filters ADD TABLE testpub_tbl_both_filters (a,c) WHERE (c != 1); -\dRp+ testpub_both_filters -\d+ testpub_tbl_both_filters - -DROP TABLE testpub_tbl_both_filters; -DROP PUBLICATION testpub_both_filters; --- ====================================================== - --- More column list tests for validating column references -CREATE TABLE rf_tbl_abcd_nopk(a int, b int, c int, d int); -CREATE TABLE rf_tbl_abcd_pk(a int, b int, c int, d int, PRIMARY KEY(a,b)); -CREATE TABLE rf_tbl_abcd_part_pk (a int PRIMARY KEY, b int) PARTITION by RANGE (a); -CREATE TABLE rf_tbl_abcd_part_pk_1 (b int, a int PRIMARY KEY); -ALTER TABLE rf_tbl_abcd_part_pk ATTACH PARTITION rf_tbl_abcd_part_pk_1 FOR VALUES FROM (1) TO (10); - --- Case 1. REPLICA IDENTITY DEFAULT (means use primary key or nothing) - --- 1a. REPLICA IDENTITY is DEFAULT and table has a PK. -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub6 FOR TABLE rf_tbl_abcd_pk (a, b); -RESET client_min_messages; --- ok - (a,b) coverts all PK cols -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (a, b, c); --- ok - (a,b,c) coverts all PK cols -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (a); --- fail - "b" is missing from the column list -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (b); --- fail - "a" is missing from the column list -UPDATE rf_tbl_abcd_pk SET a = 1; - --- 1b. REPLICA IDENTITY is DEFAULT and table has no PK -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk (a); --- ok - there's no replica identity, so any column list works --- note: it fails anyway, just a bit later because UPDATE requires RI -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Case 2. REPLICA IDENTITY FULL -ALTER TABLE rf_tbl_abcd_pk REPLICA IDENTITY FULL; -ALTER TABLE rf_tbl_abcd_nopk REPLICA IDENTITY FULL; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (c); --- fail - with REPLICA IDENTITY FULL no column list is allowed -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk (a, b, c, d); --- fail - with REPLICA IDENTITY FULL no column list is allowed -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Case 3. REPLICA IDENTITY NOTHING -ALTER TABLE rf_tbl_abcd_pk REPLICA IDENTITY NOTHING; -ALTER TABLE rf_tbl_abcd_nopk REPLICA IDENTITY NOTHING; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (a); --- ok - REPLICA IDENTITY NOTHING means all column lists are valid --- it still fails later because without RI we can't replicate updates -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (a, b, c, d); --- ok - REPLICA IDENTITY NOTHING means all column lists are valid --- it still fails later because without RI we can't replicate updates -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk (d); --- ok - REPLICA IDENTITY NOTHING means all column lists are valid --- it still fails later because without RI we can't replicate updates -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Case 4. REPLICA IDENTITY INDEX -ALTER TABLE rf_tbl_abcd_pk ALTER COLUMN c SET NOT NULL; -CREATE UNIQUE INDEX idx_abcd_pk_c ON rf_tbl_abcd_pk(c); -ALTER TABLE rf_tbl_abcd_pk REPLICA IDENTITY USING INDEX idx_abcd_pk_c; -ALTER TABLE rf_tbl_abcd_nopk ALTER COLUMN c SET NOT NULL; -CREATE UNIQUE INDEX idx_abcd_nopk_c ON rf_tbl_abcd_nopk(c); -ALTER TABLE rf_tbl_abcd_nopk REPLICA IDENTITY USING INDEX idx_abcd_nopk_c; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (a); --- fail - column list "a" does not cover the REPLICA IDENTITY INDEX on "c" -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_pk (c); --- ok - column list "c" does cover the REPLICA IDENTITY INDEX on "c" -UPDATE rf_tbl_abcd_pk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk (a); --- fail - column list "a" does not cover the REPLICA IDENTITY INDEX on "c" -UPDATE rf_tbl_abcd_nopk SET a = 1; -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_nopk (c); --- ok - column list "c" does cover the REPLICA IDENTITY INDEX on "c" -UPDATE rf_tbl_abcd_nopk SET a = 1; - --- Tests for partitioned table - --- set PUBLISH_VIA_PARTITION_ROOT to false and test column list for partitioned --- table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- fail - cannot use column list for partitioned table -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk (a); --- ok - can use column list for partition -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk_1 (a); --- ok - "a" is a PK col -UPDATE rf_tbl_abcd_part_pk SET a = 1; --- set PUBLISH_VIA_PARTITION_ROOT to true and test column list for partitioned --- table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=1); --- ok - can use column list for partitioned table -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk (a); --- ok - "a" is a PK col -UPDATE rf_tbl_abcd_part_pk SET a = 1; --- fail - cannot set PUBLISH_VIA_PARTITION_ROOT to false if any column list is --- used for partitioned table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- remove partitioned table's column list -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk; --- ok - we don't have column list for partitioned table. -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- Now change the root column list to use a column "b" --- (which is not in the replica identity) -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk_1 (b); --- ok - we don't have column list for partitioned table. -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=0); --- fail - "b" is not in REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_part_pk SET a = 1; --- set PUBLISH_VIA_PARTITION_ROOT to true --- can use column list for partitioned table -ALTER PUBLICATION testpub6 SET (PUBLISH_VIA_PARTITION_ROOT=1); --- ok - can use column list for partitioned table -ALTER PUBLICATION testpub6 SET TABLE rf_tbl_abcd_part_pk (b); --- fail - "b" is not in REPLICA IDENTITY INDEX -UPDATE rf_tbl_abcd_part_pk SET a = 1; - -DROP PUBLICATION testpub6; -DROP TABLE rf_tbl_abcd_pk; -DROP TABLE rf_tbl_abcd_nopk; -DROP TABLE rf_tbl_abcd_part_pk; --- ====================================================== - --- Test cache invalidation FOR ALL TABLES publication -SET client_min_messages = 'ERROR'; -CREATE TABLE testpub_tbl4(a int); -INSERT INTO testpub_tbl4 values(1); -UPDATE testpub_tbl4 set a = 2; -CREATE PUBLICATION testpub_foralltables FOR ALL TABLES; -RESET client_min_messages; --- fail missing REPLICA IDENTITY -UPDATE testpub_tbl4 set a = 3; -DROP PUBLICATION testpub_foralltables; --- should pass after dropping the publication -UPDATE testpub_tbl4 set a = 3; -DROP TABLE testpub_tbl4; - --- fail - view -CREATE PUBLICATION testpub_fortbl FOR TABLE testpub_view; - -CREATE TEMPORARY TABLE testpub_temptbl(a int); --- fail - temporary table -CREATE PUBLICATION testpub_fortemptbl FOR TABLE testpub_temptbl; -DROP TABLE testpub_temptbl; - -CREATE UNLOGGED TABLE testpub_unloggedtbl(a int); --- fail - unlogged table -CREATE PUBLICATION testpub_forunloggedtbl FOR TABLE testpub_unloggedtbl; -DROP TABLE testpub_unloggedtbl; - --- fail - system table -CREATE PUBLICATION testpub_forsystemtbl FOR TABLE pg_publication; - -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_fortbl FOR TABLE testpub_tbl1, pub_test.testpub_nopk; -RESET client_min_messages; --- fail - already added -ALTER PUBLICATION testpub_fortbl ADD TABLE testpub_tbl1; --- fail - already added -CREATE PUBLICATION testpub_fortbl FOR TABLE testpub_tbl1; - -\dRp+ testpub_fortbl - --- fail - view -ALTER PUBLICATION testpub_default ADD TABLE testpub_view; - -ALTER PUBLICATION testpub_default ADD TABLE testpub_tbl1; -ALTER PUBLICATION testpub_default SET TABLE testpub_tbl1; -ALTER PUBLICATION testpub_default ADD TABLE pub_test.testpub_nopk; - -ALTER PUBLICATION testpib_ins_trunct ADD TABLE pub_test.testpub_nopk, testpub_tbl1; - -\d+ pub_test.testpub_nopk -\d+ testpub_tbl1 -\dRp+ testpub_default - -ALTER PUBLICATION testpub_default DROP TABLE testpub_tbl1, pub_test.testpub_nopk; --- fail - nonexistent -ALTER PUBLICATION testpub_default DROP TABLE pub_test.testpub_nopk; - -\d+ testpub_tbl1 - --- verify relation cache invalidation when a primary key is added using --- an existing index -CREATE TABLE pub_test.testpub_addpk (id int not null, data int); -ALTER PUBLICATION testpub_default ADD TABLE pub_test.testpub_addpk; -INSERT INTO pub_test.testpub_addpk VALUES(1, 11); -CREATE UNIQUE INDEX testpub_addpk_id_idx ON pub_test.testpub_addpk(id); --- fail: -UPDATE pub_test.testpub_addpk SET id = 2; -ALTER TABLE pub_test.testpub_addpk ADD PRIMARY KEY USING INDEX testpub_addpk_id_idx; --- now it should work: -UPDATE pub_test.testpub_addpk SET id = 2; -DROP TABLE pub_test.testpub_addpk; - --- permissions -SET ROLE regress_publication_user2; -CREATE PUBLICATION testpub2; -- fail - -SET ROLE regress_publication_user; -GRANT CREATE ON DATABASE regression TO regress_publication_user2; -SET ROLE regress_publication_user2; -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub2; -- ok -CREATE PUBLICATION testpub3 FOR ALL TABLES IN SCHEMA pub_test; -- fail -CREATE PUBLICATION testpub3; -- ok -RESET client_min_messages; - -ALTER PUBLICATION testpub2 ADD TABLE testpub_tbl1; -- fail -ALTER PUBLICATION testpub3 ADD ALL TABLES IN SCHEMA pub_test; -- fail - -SET ROLE regress_publication_user; -GRANT regress_publication_user TO regress_publication_user2; -SET ROLE regress_publication_user2; -ALTER PUBLICATION testpub2 ADD TABLE testpub_tbl1; -- ok - -DROP PUBLICATION testpub2; -DROP PUBLICATION testpub3; - -SET ROLE regress_publication_user; -CREATE ROLE regress_publication_user3; -GRANT regress_publication_user2 TO regress_publication_user3; -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub4 FOR ALL TABLES IN SCHEMA pub_test; -RESET client_min_messages; -ALTER PUBLICATION testpub4 OWNER TO regress_publication_user3; -SET ROLE regress_publication_user3; --- fail - new owner must be superuser -ALTER PUBLICATION testpub4 owner to regress_publication_user2; -- fail -ALTER PUBLICATION testpub4 owner to regress_publication_user; -- ok - -SET ROLE regress_publication_user; -DROP PUBLICATION testpub4; -DROP ROLE regress_publication_user3; - -REVOKE CREATE ON DATABASE regression FROM regress_publication_user2; - -DROP TABLE testpub_parted; -DROP TABLE testpub_tbl1; - -\dRp+ testpub_default - --- fail - must be owner of publication -SET ROLE regress_publication_user_dummy; -ALTER PUBLICATION testpub_default RENAME TO testpub_dummy; -RESET ROLE; - -ALTER PUBLICATION testpub_default RENAME TO testpub_foo; - -\dRp testpub_foo - --- rename back to keep the rest simple -ALTER PUBLICATION testpub_foo RENAME TO testpub_default; - -ALTER PUBLICATION testpub_default OWNER TO regress_publication_user2; - -\dRp testpub_default - --- adding schemas and tables -CREATE SCHEMA pub_test1; -CREATE SCHEMA pub_test2; -CREATE SCHEMA pub_test3; -CREATE SCHEMA "CURRENT_SCHEMA"; -CREATE TABLE pub_test1.tbl (id int, data text); -CREATE TABLE pub_test1.tbl1 (id serial primary key, data text); -CREATE TABLE pub_test2.tbl1 (id serial primary key, data text); -CREATE TABLE "CURRENT_SCHEMA"."CURRENT_SCHEMA"(id int); - --- suppress warning that depends on wal_level -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub1_forschema FOR ALL TABLES IN SCHEMA pub_test1; -\dRp+ testpub1_forschema - -CREATE PUBLICATION testpub2_forschema FOR ALL TABLES IN SCHEMA pub_test1, pub_test2, pub_test3; -\dRp+ testpub2_forschema - --- check create publication on CURRENT_SCHEMA -CREATE PUBLICATION testpub3_forschema FOR ALL TABLES IN SCHEMA CURRENT_SCHEMA; -CREATE PUBLICATION testpub4_forschema FOR ALL TABLES IN SCHEMA "CURRENT_SCHEMA"; -CREATE PUBLICATION testpub5_forschema FOR ALL TABLES IN SCHEMA CURRENT_SCHEMA, "CURRENT_SCHEMA"; -CREATE PUBLICATION testpub6_forschema FOR ALL TABLES IN SCHEMA "CURRENT_SCHEMA", CURRENT_SCHEMA; -CREATE PUBLICATION testpub_fortable FOR TABLE "CURRENT_SCHEMA"."CURRENT_SCHEMA"; - -RESET client_min_messages; - -\dRp+ testpub3_forschema -\dRp+ testpub4_forschema -\dRp+ testpub5_forschema -\dRp+ testpub6_forschema -\dRp+ testpub_fortable - --- check create publication on CURRENT_SCHEMA where search_path is not set -SET SEARCH_PATH=''; -CREATE PUBLICATION testpub_forschema FOR ALL TABLES IN SCHEMA CURRENT_SCHEMA; -RESET SEARCH_PATH; - --- check create publication on CURRENT_SCHEMA where TABLE/ALL TABLES in SCHEMA --- is not specified -CREATE PUBLICATION testpub_forschema1 FOR CURRENT_SCHEMA; - --- check create publication on CURRENT_SCHEMA along with FOR TABLE -CREATE PUBLICATION testpub_forschema1 FOR TABLE CURRENT_SCHEMA; - --- check create publication on a schema that does not exist -CREATE PUBLICATION testpub_forschema FOR ALL TABLES IN SCHEMA non_existent_schema; - --- check create publication on a system schema -CREATE PUBLICATION testpub_forschema FOR ALL TABLES IN SCHEMA pg_catalog; - --- check create publication on an object which is not schema -CREATE PUBLICATION testpub1_forschema1 FOR ALL TABLES IN SCHEMA testpub_view; - --- dropping the schema should reflect the change in publication -DROP SCHEMA pub_test3; -\dRp+ testpub2_forschema - --- renaming the schema should reflect the change in publication -ALTER SCHEMA pub_test1 RENAME to pub_test1_renamed; -\dRp+ testpub2_forschema - -ALTER SCHEMA pub_test1_renamed RENAME to pub_test1; -\dRp+ testpub2_forschema - --- alter publication add schema -ALTER PUBLICATION testpub1_forschema ADD ALL TABLES IN SCHEMA pub_test2; -\dRp+ testpub1_forschema - --- add non existent schema -ALTER PUBLICATION testpub1_forschema ADD ALL TABLES IN SCHEMA non_existent_schema; -\dRp+ testpub1_forschema - --- add a schema which is already added to the publication -ALTER PUBLICATION testpub1_forschema ADD ALL TABLES IN SCHEMA pub_test1; -\dRp+ testpub1_forschema - --- alter publication drop schema -ALTER PUBLICATION testpub1_forschema DROP ALL TABLES IN SCHEMA pub_test2; -\dRp+ testpub1_forschema - --- drop schema that is not present in the publication -ALTER PUBLICATION testpub1_forschema DROP ALL TABLES IN SCHEMA pub_test2; -\dRp+ testpub1_forschema - --- drop a schema that does not exist in the system -ALTER PUBLICATION testpub1_forschema DROP ALL TABLES IN SCHEMA non_existent_schema; -\dRp+ testpub1_forschema - --- drop all schemas -ALTER PUBLICATION testpub1_forschema DROP ALL TABLES IN SCHEMA pub_test1; -\dRp+ testpub1_forschema - --- alter publication set multiple schema -ALTER PUBLICATION testpub1_forschema SET ALL TABLES IN SCHEMA pub_test1, pub_test2; -\dRp+ testpub1_forschema - --- alter publication set non-existent schema -ALTER PUBLICATION testpub1_forschema SET ALL TABLES IN SCHEMA non_existent_schema; -\dRp+ testpub1_forschema - --- alter publication set it duplicate schemas should set the schemas after --- removing the duplicate schemas -ALTER PUBLICATION testpub1_forschema SET ALL TABLES IN SCHEMA pub_test1, pub_test1; -\dRp+ testpub1_forschema - --- Verify that it fails to add a schema with a column specification -ALTER PUBLICATION testpub1_forschema ADD ALL TABLES IN SCHEMA foo (a, b); -ALTER PUBLICATION testpub1_forschema ADD ALL TABLES IN SCHEMA foo, bar (a, b); - --- cleanup pub_test1 schema for invalidation tests -ALTER PUBLICATION testpub2_forschema DROP ALL TABLES IN SCHEMA pub_test1; -DROP PUBLICATION testpub3_forschema, testpub4_forschema, testpub5_forschema, testpub6_forschema, testpub_fortable; -DROP SCHEMA "CURRENT_SCHEMA" CASCADE; - --- verify relation cache invalidations through update statement for the --- default REPLICA IDENTITY on the relation, if schema is part of the --- publication then update will fail because relation's relreplident --- option will be set, if schema is not part of the publication then update --- will be successful. -INSERT INTO pub_test1.tbl VALUES(1, 'test'); - --- fail -UPDATE pub_test1.tbl SET id = 2; -ALTER PUBLICATION testpub1_forschema DROP ALL TABLES IN SCHEMA pub_test1; - --- success -UPDATE pub_test1.tbl SET id = 2; -ALTER PUBLICATION testpub1_forschema SET ALL TABLES IN SCHEMA pub_test1; - --- fail -UPDATE pub_test1.tbl SET id = 2; - --- verify invalidation of partition table having parent and child tables in --- different schema -CREATE SCHEMA pub_testpart1; -CREATE SCHEMA pub_testpart2; - -CREATE TABLE pub_testpart1.parent1 (a int) partition by list (a); -CREATE TABLE pub_testpart2.child_parent1 partition of pub_testpart1.parent1 for values in (1); -INSERT INTO pub_testpart2.child_parent1 values(1); -UPDATE pub_testpart2.child_parent1 set a = 1; -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpubpart_forschema FOR ALL TABLES IN SCHEMA pub_testpart1; -RESET client_min_messages; - --- fail -UPDATE pub_testpart1.parent1 set a = 1; -UPDATE pub_testpart2.child_parent1 set a = 1; - -DROP PUBLICATION testpubpart_forschema; - --- verify invalidation of partition tables for schema publication that has --- parent and child tables of different partition hierarchies -CREATE TABLE pub_testpart2.parent2 (a int) partition by list (a); -CREATE TABLE pub_testpart1.child_parent2 partition of pub_testpart2.parent2 for values in (1); -INSERT INTO pub_testpart1.child_parent2 values(1); -UPDATE pub_testpart1.child_parent2 set a = 1; -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpubpart_forschema FOR ALL TABLES IN SCHEMA pub_testpart2; -RESET client_min_messages; - --- fail -UPDATE pub_testpart2.child_parent1 set a = 1; -UPDATE pub_testpart2.parent2 set a = 1; -UPDATE pub_testpart1.child_parent2 set a = 1; - --- alter publication set 'ALL TABLES IN SCHEMA' on an empty publication. -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub3_forschema; -RESET client_min_messages; -\dRp+ testpub3_forschema -ALTER PUBLICATION testpub3_forschema SET ALL TABLES IN SCHEMA pub_test1; -\dRp+ testpub3_forschema - --- create publication including both 'FOR TABLE' and 'FOR ALL TABLES IN SCHEMA' -SET client_min_messages = 'ERROR'; -CREATE PUBLICATION testpub_forschema_fortable FOR ALL TABLES IN SCHEMA pub_test1, TABLE pub_test2.tbl1; -CREATE PUBLICATION testpub_fortable_forschema FOR TABLE pub_test2.tbl1, ALL TABLES IN SCHEMA pub_test1; -RESET client_min_messages; - -\dRp+ testpub_forschema_fortable -\dRp+ testpub_fortable_forschema - --- fail specifying table without any of 'FOR ALL TABLES IN SCHEMA' or ---'FOR TABLE' or 'FOR ALL TABLES' -CREATE PUBLICATION testpub_error FOR pub_test2.tbl1; - -DROP VIEW testpub_view; - -DROP PUBLICATION testpub_default; -DROP PUBLICATION testpib_ins_trunct; -DROP PUBLICATION testpub_fortbl; -DROP PUBLICATION testpub1_forschema; -DROP PUBLICATION testpub2_forschema; -DROP PUBLICATION testpub3_forschema; -DROP PUBLICATION testpub_forschema_fortable; -DROP PUBLICATION testpub_fortable_forschema; -DROP PUBLICATION testpubpart_forschema; - -DROP SCHEMA pub_test CASCADE; -DROP SCHEMA pub_test1 CASCADE; -DROP SCHEMA pub_test2 CASCADE; -DROP SCHEMA pub_testpart1 CASCADE; -DROP SCHEMA pub_testpart2 CASCADE; - --- Test the list of partitions published with or without --- 'PUBLISH_VIA_PARTITION_ROOT' parameter -SET client_min_messages = 'ERROR'; -CREATE SCHEMA sch1; -CREATE SCHEMA sch2; -CREATE TABLE sch1.tbl1 (a int) PARTITION BY RANGE(a); -CREATE TABLE sch2.tbl1_part1 PARTITION OF sch1.tbl1 FOR VALUES FROM (1) to (10); --- Schema publication that does not include the schema that has the parent table -CREATE PUBLICATION pub FOR ALL TABLES IN SCHEMA sch2 WITH (PUBLISH_VIA_PARTITION_ROOT=1); -SELECT * FROM pg_publication_tables; - -DROP PUBLICATION pub; --- Table publication that does not include the parent table -CREATE PUBLICATION pub FOR TABLE sch2.tbl1_part1 WITH (PUBLISH_VIA_PARTITION_ROOT=1); -SELECT * FROM pg_publication_tables; - --- Table publication that includes both the parent table and the child table -ALTER PUBLICATION pub ADD TABLE sch1.tbl1; -SELECT * FROM pg_publication_tables; - -DROP PUBLICATION pub; --- Schema publication that does not include the schema that has the parent table -CREATE PUBLICATION pub FOR ALL TABLES IN SCHEMA sch2 WITH (PUBLISH_VIA_PARTITION_ROOT=0); -SELECT * FROM pg_publication_tables; - -DROP PUBLICATION pub; --- Table publication that does not include the parent table -CREATE PUBLICATION pub FOR TABLE sch2.tbl1_part1 WITH (PUBLISH_VIA_PARTITION_ROOT=0); -SELECT * FROM pg_publication_tables; - --- Table publication that includes both the parent table and the child table -ALTER PUBLICATION pub ADD TABLE sch1.tbl1; -SELECT * FROM pg_publication_tables; - -DROP PUBLICATION pub; -DROP TABLE sch2.tbl1_part1; -DROP TABLE sch1.tbl1; - -CREATE TABLE sch1.tbl1 (a int) PARTITION BY RANGE(a); -CREATE TABLE sch1.tbl1_part1 PARTITION OF sch1.tbl1 FOR VALUES FROM (1) to (10); -CREATE TABLE sch1.tbl1_part2 PARTITION OF sch1.tbl1 FOR VALUES FROM (10) to (20); -CREATE TABLE sch1.tbl1_part3 (a int) PARTITION BY RANGE(a); -ALTER TABLE sch1.tbl1 ATTACH PARTITION sch1.tbl1_part3 FOR VALUES FROM (20) to (30); -CREATE PUBLICATION pub FOR ALL TABLES IN SCHEMA sch1 WITH (PUBLISH_VIA_PARTITION_ROOT=1); -SELECT * FROM pg_publication_tables; - -RESET client_min_messages; -DROP PUBLICATION pub; -DROP TABLE sch1.tbl1; -DROP SCHEMA sch1 cascade; -DROP SCHEMA sch2 cascade; - -RESET SESSION AUTHORIZATION; -DROP ROLE regress_publication_user, regress_publication_user2; -DROP ROLE regress_publication_user_dummy; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frangefuncs.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frangefuncs.sql deleted file mode 100644 index 7e5cde14c4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frangefuncs.sql +++ /dev/null @@ -1,784 +0,0 @@ -CREATE TABLE rngfunc2(rngfuncid int, f2 int); -INSERT INTO rngfunc2 VALUES(1, 11); -INSERT INTO rngfunc2 VALUES(2, 22); -INSERT INTO rngfunc2 VALUES(1, 111); - -CREATE FUNCTION rngfunct(int) returns setof rngfunc2 as 'SELECT * FROM rngfunc2 WHERE rngfuncid = $1 ORDER BY f2;' LANGUAGE SQL; - --- function with ORDINALITY -select * from rngfunct(1) with ordinality as z(a,b,ord); -select * from rngfunct(1) with ordinality as z(a,b,ord) where b > 100; -- ordinal 2, not 1 --- ordinality vs. column names and types -select a,b,ord from rngfunct(1) with ordinality as z(a,b,ord); -select a,ord from unnest(array['a','b']) with ordinality as z(a,ord); -select * from unnest(array['a','b']) with ordinality as z(a,ord); -select a,ord from unnest(array[1.0::float8]) with ordinality as z(a,ord); -select * from unnest(array[1.0::float8]) with ordinality as z(a,ord); -select row_to_json(s.*) from generate_series(11,14) with ordinality s; --- ordinality vs. views -create temporary view vw_ord as select * from (values (1)) v(n) join rngfunct(1) with ordinality as z(a,b,ord) on (n=ord); -select * from vw_ord; -select definition from pg_views where viewname='vw_ord'; -drop view vw_ord; - --- multiple functions -select * from rows from(rngfunct(1),rngfunct(2)) with ordinality as z(a,b,c,d,ord); -create temporary view vw_ord as select * from (values (1)) v(n) join rows from(rngfunct(1),rngfunct(2)) with ordinality as z(a,b,c,d,ord) on (n=ord); -select * from vw_ord; -select definition from pg_views where viewname='vw_ord'; -drop view vw_ord; - --- expansions of unnest() -select * from unnest(array[10,20],array['foo','bar'],array[1.0]); -select * from unnest(array[10,20],array['foo','bar'],array[1.0]) with ordinality as z(a,b,c,ord); -select * from rows from(unnest(array[10,20],array['foo','bar'],array[1.0])) with ordinality as z(a,b,c,ord); -select * from rows from(unnest(array[10,20],array['foo','bar']), generate_series(101,102)) with ordinality as z(a,b,c,ord); -create temporary view vw_ord as select * from unnest(array[10,20],array['foo','bar'],array[1.0]) as z(a,b,c); -select * from vw_ord; -select definition from pg_views where viewname='vw_ord'; -drop view vw_ord; -create temporary view vw_ord as select * from rows from(unnest(array[10,20],array['foo','bar'],array[1.0])) as z(a,b,c); -select * from vw_ord; -select definition from pg_views where viewname='vw_ord'; -drop view vw_ord; -create temporary view vw_ord as select * from rows from(unnest(array[10,20],array['foo','bar']), generate_series(1,2)) as z(a,b,c); -select * from vw_ord; -select definition from pg_views where viewname='vw_ord'; -drop view vw_ord; - --- ordinality and multiple functions vs. rewind and reverse scan -begin; -declare rf_cur scroll cursor for select * from rows from(generate_series(1,5),generate_series(1,2)) with ordinality as g(i,j,o); -fetch all from rf_cur; -fetch backward all from rf_cur; -fetch all from rf_cur; -fetch next from rf_cur; -fetch next from rf_cur; -fetch prior from rf_cur; -fetch absolute 1 from rf_cur; -fetch next from rf_cur; -fetch next from rf_cur; -fetch next from rf_cur; -fetch prior from rf_cur; -fetch prior from rf_cur; -fetch prior from rf_cur; -commit; - --- function with implicit LATERAL -select * from rngfunc2, rngfunct(rngfunc2.rngfuncid) z where rngfunc2.f2 = z.f2; - --- function with implicit LATERAL and explicit ORDINALITY -select * from rngfunc2, rngfunct(rngfunc2.rngfuncid) with ordinality as z(rngfuncid,f2,ord) where rngfunc2.f2 = z.f2; - --- function in subselect -select * from rngfunc2 where f2 in (select f2 from rngfunct(rngfunc2.rngfuncid) z where z.rngfuncid = rngfunc2.rngfuncid) ORDER BY 1,2; - --- function in subselect -select * from rngfunc2 where f2 in (select f2 from rngfunct(1) z where z.rngfuncid = rngfunc2.rngfuncid) ORDER BY 1,2; - --- function in subselect -select * from rngfunc2 where f2 in (select f2 from rngfunct(rngfunc2.rngfuncid) z where z.rngfuncid = 1) ORDER BY 1,2; - --- nested functions -select rngfunct.rngfuncid, rngfunct.f2 from rngfunct(sin(pi()/2)::int) ORDER BY 1,2; - -CREATE TABLE rngfunc (rngfuncid int, rngfuncsubid int, rngfuncname text, primary key(rngfuncid,rngfuncsubid)); -INSERT INTO rngfunc VALUES(1,1,'Joe'); -INSERT INTO rngfunc VALUES(1,2,'Ed'); -INSERT INTO rngfunc VALUES(2,1,'Mary'); - --- sql, proretset = f, prorettype = b -CREATE FUNCTION getrngfunc1(int) RETURNS int AS 'SELECT $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc1(1) AS t1; -SELECT * FROM getrngfunc1(1) WITH ORDINALITY AS t1(v,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc1(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc1(1) WITH ORDINALITY as t1(v,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- sql, proretset = t, prorettype = b -CREATE FUNCTION getrngfunc2(int) RETURNS setof int AS 'SELECT rngfuncid FROM rngfunc WHERE rngfuncid = $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc2(1) AS t1; -SELECT * FROM getrngfunc2(1) WITH ORDINALITY AS t1(v,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc2(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc2(1) WITH ORDINALITY AS t1(v,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- sql, proretset = t, prorettype = b -CREATE FUNCTION getrngfunc3(int) RETURNS setof text AS 'SELECT rngfuncname FROM rngfunc WHERE rngfuncid = $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc3(1) AS t1; -SELECT * FROM getrngfunc3(1) WITH ORDINALITY AS t1(v,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc3(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc3(1) WITH ORDINALITY AS t1(v,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- sql, proretset = f, prorettype = c -CREATE FUNCTION getrngfunc4(int) RETURNS rngfunc AS 'SELECT * FROM rngfunc WHERE rngfuncid = $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc4(1) AS t1; -SELECT * FROM getrngfunc4(1) WITH ORDINALITY AS t1(a,b,c,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc4(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc4(1) WITH ORDINALITY AS t1(a,b,c,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- sql, proretset = t, prorettype = c -CREATE FUNCTION getrngfunc5(int) RETURNS setof rngfunc AS 'SELECT * FROM rngfunc WHERE rngfuncid = $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc5(1) AS t1; -SELECT * FROM getrngfunc5(1) WITH ORDINALITY AS t1(a,b,c,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc5(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc5(1) WITH ORDINALITY AS t1(a,b,c,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- sql, proretset = f, prorettype = record -CREATE FUNCTION getrngfunc6(int) RETURNS RECORD AS 'SELECT * FROM rngfunc WHERE rngfuncid = $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc6(1) AS t1(rngfuncid int, rngfuncsubid int, rngfuncname text); -SELECT * FROM ROWS FROM( getrngfunc6(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text) ) WITH ORDINALITY; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc6(1) AS -(rngfuncid int, rngfuncsubid int, rngfuncname text); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS - SELECT * FROM ROWS FROM( getrngfunc6(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text) ) - WITH ORDINALITY; -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- sql, proretset = t, prorettype = record -CREATE FUNCTION getrngfunc7(int) RETURNS setof record AS 'SELECT * FROM rngfunc WHERE rngfuncid = $1;' LANGUAGE SQL; -SELECT * FROM getrngfunc7(1) AS t1(rngfuncid int, rngfuncsubid int, rngfuncname text); -SELECT * FROM ROWS FROM( getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text) ) WITH ORDINALITY; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc7(1) AS -(rngfuncid int, rngfuncsubid int, rngfuncname text); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS - SELECT * FROM ROWS FROM( getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text) ) - WITH ORDINALITY; -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- plpgsql, proretset = f, prorettype = b -CREATE FUNCTION getrngfunc8(int) RETURNS int AS 'DECLARE rngfuncint int; BEGIN SELECT rngfuncid into rngfuncint FROM rngfunc WHERE rngfuncid = $1; RETURN rngfuncint; END;' LANGUAGE plpgsql; -SELECT * FROM getrngfunc8(1) AS t1; -SELECT * FROM getrngfunc8(1) WITH ORDINALITY AS t1(v,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc8(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc8(1) WITH ORDINALITY AS t1(v,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- plpgsql, proretset = f, prorettype = c -CREATE FUNCTION getrngfunc9(int) RETURNS rngfunc AS 'DECLARE rngfunctup rngfunc%ROWTYPE; BEGIN SELECT * into rngfunctup FROM rngfunc WHERE rngfuncid = $1; RETURN rngfunctup; END;' LANGUAGE plpgsql; -SELECT * FROM getrngfunc9(1) AS t1; -SELECT * FROM getrngfunc9(1) WITH ORDINALITY AS t1(a,b,c,o); -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc9(1); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; -CREATE VIEW vw_getrngfunc AS SELECT * FROM getrngfunc9(1) WITH ORDINALITY AS t1(a,b,c,o); -SELECT * FROM vw_getrngfunc; -DROP VIEW vw_getrngfunc; - --- mix 'n match kinds, to exercise expandRTE and related logic - -select * from rows from(getrngfunc1(1),getrngfunc2(1),getrngfunc3(1),getrngfunc4(1),getrngfunc5(1), - getrngfunc6(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text), - getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text), - getrngfunc8(1),getrngfunc9(1)) - with ordinality as t1(a,b,c,d,e,f,g,h,i,j,k,l,m,o,p,q,r,s,t,u); -select * from rows from(getrngfunc9(1),getrngfunc8(1), - getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text), - getrngfunc6(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text), - getrngfunc5(1),getrngfunc4(1),getrngfunc3(1),getrngfunc2(1),getrngfunc1(1)) - with ordinality as t1(a,b,c,d,e,f,g,h,i,j,k,l,m,o,p,q,r,s,t,u); - -create temporary view vw_rngfunc as - select * from rows from(getrngfunc9(1), - getrngfunc7(1) AS (rngfuncid int, rngfuncsubid int, rngfuncname text), - getrngfunc1(1)) - with ordinality as t1(a,b,c,d,e,f,g,n); -select * from vw_rngfunc; -select pg_get_viewdef('vw_rngfunc'); -drop view vw_rngfunc; - -DROP FUNCTION getrngfunc1(int); -DROP FUNCTION getrngfunc2(int); -DROP FUNCTION getrngfunc3(int); -DROP FUNCTION getrngfunc4(int); -DROP FUNCTION getrngfunc5(int); -DROP FUNCTION getrngfunc6(int); -DROP FUNCTION getrngfunc7(int); -DROP FUNCTION getrngfunc8(int); -DROP FUNCTION getrngfunc9(int); -DROP FUNCTION rngfunct(int); -DROP TABLE rngfunc2; -DROP TABLE rngfunc; - --- Rescan tests -- -CREATE TEMPORARY SEQUENCE rngfunc_rescan_seq1; -CREATE TEMPORARY SEQUENCE rngfunc_rescan_seq2; -CREATE TYPE rngfunc_rescan_t AS (i integer, s bigint); - -CREATE FUNCTION rngfunc_sql(int,int) RETURNS setof rngfunc_rescan_t AS 'SELECT i, nextval(''rngfunc_rescan_seq1'') FROM generate_series($1,$2) i;' LANGUAGE SQL; --- plpgsql functions use materialize mode -CREATE FUNCTION rngfunc_mat(int,int) RETURNS setof rngfunc_rescan_t AS 'begin for i in $1..$2 loop return next (i, nextval(''rngfunc_rescan_seq2'')); end loop; end;' LANGUAGE plpgsql; - ---invokes ExecReScanFunctionScan - all these cases should materialize the function only once --- LEFT JOIN on a condition that the planner can't prove to be true is used to ensure the function --- is on the inner path of a nestloop join - -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN rngfunc_sql(11,13) ON (r+i)<100; -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN rngfunc_sql(11,13) WITH ORDINALITY AS f(i,s,o) ON (r+i)<100; - -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN rngfunc_mat(11,13) ON (r+i)<100; -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN rngfunc_mat(11,13) WITH ORDINALITY AS f(i,s,o) ON (r+i)<100; -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN ROWS FROM( rngfunc_sql(11,13), rngfunc_mat(11,13) ) WITH ORDINALITY AS f(i1,s1,i2,s2,o) ON (r+i1+i2)<100; - -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN generate_series(11,13) f(i) ON (r+i)<100; -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN generate_series(11,13) WITH ORDINALITY AS f(i,o) ON (r+i)<100; - -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN unnest(array[10,20,30]) f(i) ON (r+i)<100; -SELECT * FROM (VALUES (1),(2),(3)) v(r) LEFT JOIN unnest(array[10,20,30]) WITH ORDINALITY AS f(i,o) ON (r+i)<100; - ---invokes ExecReScanFunctionScan with chgParam != NULL (using implied LATERAL) - -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_sql(10+r,13); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_sql(10+r,13) WITH ORDINALITY AS f(i,s,o); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_sql(11,10+r); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_sql(11,10+r) WITH ORDINALITY AS f(i,s,o); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (11,12),(13,15),(16,20)) v(r1,r2), rngfunc_sql(r1,r2); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (11,12),(13,15),(16,20)) v(r1,r2), rngfunc_sql(r1,r2) WITH ORDINALITY AS f(i,s,o); - -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_mat(10+r,13); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_mat(10+r,13) WITH ORDINALITY AS f(i,s,o); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_mat(11,10+r); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), rngfunc_mat(11,10+r) WITH ORDINALITY AS f(i,s,o); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (11,12),(13,15),(16,20)) v(r1,r2), rngfunc_mat(r1,r2); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (11,12),(13,15),(16,20)) v(r1,r2), rngfunc_mat(r1,r2) WITH ORDINALITY AS f(i,s,o); - --- selective rescan of multiple functions: - -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), ROWS FROM( rngfunc_sql(11,11), rngfunc_mat(10+r,13) ); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), ROWS FROM( rngfunc_sql(10+r,13), rngfunc_mat(11,11) ); -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM (VALUES (1),(2),(3)) v(r), ROWS FROM( rngfunc_sql(10+r,13), rngfunc_mat(10+r,13) ); - -SELECT setval('rngfunc_rescan_seq1',1,false),setval('rngfunc_rescan_seq2',1,false); -SELECT * FROM generate_series(1,2) r1, generate_series(r1,3) r2, ROWS FROM( rngfunc_sql(10+r1,13), rngfunc_mat(10+r2,13) ); - -SELECT * FROM (VALUES (1),(2),(3)) v(r), generate_series(10+r,20-r) f(i); -SELECT * FROM (VALUES (1),(2),(3)) v(r), generate_series(10+r,20-r) WITH ORDINALITY AS f(i,o); - -SELECT * FROM (VALUES (1),(2),(3)) v(r), unnest(array[r*10,r*20,r*30]) f(i); -SELECT * FROM (VALUES (1),(2),(3)) v(r), unnest(array[r*10,r*20,r*30]) WITH ORDINALITY AS f(i,o); - --- deep nesting - -SELECT * FROM (VALUES (1),(2),(3)) v1(r1), - LATERAL (SELECT r1, * FROM (VALUES (10),(20),(30)) v2(r2) - LEFT JOIN generate_series(21,23) f(i) ON ((r2+i)<100) OFFSET 0) s1; -SELECT * FROM (VALUES (1),(2),(3)) v1(r1), - LATERAL (SELECT r1, * FROM (VALUES (10),(20),(30)) v2(r2) - LEFT JOIN generate_series(20+r1,23) f(i) ON ((r2+i)<100) OFFSET 0) s1; -SELECT * FROM (VALUES (1),(2),(3)) v1(r1), - LATERAL (SELECT r1, * FROM (VALUES (10),(20),(30)) v2(r2) - LEFT JOIN generate_series(r2,r2+3) f(i) ON ((r2+i)<100) OFFSET 0) s1; -SELECT * FROM (VALUES (1),(2),(3)) v1(r1), - LATERAL (SELECT r1, * FROM (VALUES (10),(20),(30)) v2(r2) - LEFT JOIN generate_series(r1,2+r2/5) f(i) ON ((r2+i)<100) OFFSET 0) s1; - --- check handling of FULL JOIN with multiple lateral references (bug #15741) - -SELECT * -FROM (VALUES (1),(2)) v1(r1) - LEFT JOIN LATERAL ( - SELECT * - FROM generate_series(1, v1.r1) AS gs1 - LEFT JOIN LATERAL ( - SELECT * - FROM generate_series(1, gs1) AS gs2 - LEFT JOIN generate_series(1, gs2) AS gs3 ON TRUE - ) AS ss1 ON TRUE - FULL JOIN generate_series(1, v1.r1) AS gs4 ON FALSE - ) AS ss0 ON TRUE; - -DROP FUNCTION rngfunc_sql(int,int); -DROP FUNCTION rngfunc_mat(int,int); -DROP SEQUENCE rngfunc_rescan_seq1; -DROP SEQUENCE rngfunc_rescan_seq2; - --- --- Test cases involving OUT parameters --- - -CREATE FUNCTION rngfunc(in f1 int, out f2 int) -AS 'select $1+1' LANGUAGE sql; -SELECT rngfunc(42); -SELECT * FROM rngfunc(42); -SELECT * FROM rngfunc(42) AS p(x); - --- explicit spec of return type is OK -CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int) RETURNS int -AS 'select $1+1' LANGUAGE sql; --- error, wrong result type -CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int) RETURNS float -AS 'select $1+1' LANGUAGE sql; --- with multiple OUT params you must get a RECORD result -CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int, out f3 text) RETURNS int -AS 'select $1+1' LANGUAGE sql; -CREATE OR REPLACE FUNCTION rngfunc(in f1 int, out f2 int, out f3 text) -RETURNS record -AS 'select $1+1' LANGUAGE sql; - -CREATE OR REPLACE FUNCTION rngfuncr(in f1 int, out f2 int, out text) -AS $$select $1-1, $1::text || 'z'$$ LANGUAGE sql; -SELECT f1, rngfuncr(f1) FROM int4_tbl; -SELECT * FROM rngfuncr(42); -SELECT * FROM rngfuncr(42) AS p(a,b); - -CREATE OR REPLACE FUNCTION rngfuncb(in f1 int, inout f2 int, out text) -AS $$select $2-1, $1::text || 'z'$$ LANGUAGE sql; -SELECT f1, rngfuncb(f1, f1/2) FROM int4_tbl; -SELECT * FROM rngfuncb(42, 99); -SELECT * FROM rngfuncb(42, 99) AS p(a,b); - --- Can reference function with or without OUT params for DROP, etc -DROP FUNCTION rngfunc(int); -DROP FUNCTION rngfuncr(in f2 int, out f1 int, out text); -DROP FUNCTION rngfuncb(in f1 int, inout f2 int); - --- --- For my next trick, polymorphic OUT parameters --- - -CREATE FUNCTION dup (f1 anyelement, f2 out anyelement, f3 out anyarray) -AS 'select $1, array[$1,$1]' LANGUAGE sql; -SELECT dup(22); -SELECT dup('xyz'); -- fails -SELECT dup('xyz'::text); -SELECT * FROM dup('xyz'::text); - --- fails, as we are attempting to rename first argument -CREATE OR REPLACE FUNCTION dup (inout f2 anyelement, out f3 anyarray) -AS 'select $1, array[$1,$1]' LANGUAGE sql; - -DROP FUNCTION dup(anyelement); - --- equivalent behavior, though different name exposed for input arg -CREATE OR REPLACE FUNCTION dup (inout f2 anyelement, out f3 anyarray) -AS 'select $1, array[$1,$1]' LANGUAGE sql; -SELECT dup(22); - -DROP FUNCTION dup(anyelement); - --- fails, no way to deduce outputs -CREATE FUNCTION bad (f1 int, out f2 anyelement, out f3 anyarray) -AS 'select $1, array[$1,$1]' LANGUAGE sql; - -CREATE FUNCTION dup (f1 anycompatible, f2 anycompatiblearray, f3 out anycompatible, f4 out anycompatiblearray) -AS 'select $1, $2' LANGUAGE sql; -SELECT dup(22, array[44]); -SELECT dup(4.5, array[44]); -SELECT dup(22, array[44::bigint]); -SELECT *, pg_typeof(f3), pg_typeof(f4) FROM dup(22, array[44::bigint]); - -DROP FUNCTION dup(f1 anycompatible, f2 anycompatiblearray); - -CREATE FUNCTION dup (f1 anycompatiblerange, f2 out anycompatible, f3 out anycompatiblearray, f4 out anycompatiblerange) -AS 'select lower($1), array[lower($1), upper($1)], $1' LANGUAGE sql; -SELECT dup(int4range(4,7)); -SELECT dup(numrange(4,7)); -SELECT dup(textrange('aaa', 'bbb')); - -DROP FUNCTION dup(f1 anycompatiblerange); - --- fails, no way to deduce outputs -CREATE FUNCTION bad (f1 anyarray, out f2 anycompatible, out f3 anycompatiblearray) -AS 'select $1, array[$1,$1]' LANGUAGE sql; - --- --- table functions --- - -CREATE OR REPLACE FUNCTION rngfunc() -RETURNS TABLE(a int) -AS $$ SELECT a FROM generate_series(1,5) a(a) $$ LANGUAGE sql; -SELECT * FROM rngfunc(); -DROP FUNCTION rngfunc(); - -CREATE OR REPLACE FUNCTION rngfunc(int) -RETURNS TABLE(a int, b int) -AS $$ SELECT a, b - FROM generate_series(1,$1) a(a), - generate_series(1,$1) b(b) $$ LANGUAGE sql; -SELECT * FROM rngfunc(3); -DROP FUNCTION rngfunc(int); - --- case that causes change of typmod knowledge during inlining -CREATE OR REPLACE FUNCTION rngfunc() -RETURNS TABLE(a varchar(5)) -AS $$ SELECT 'hello'::varchar(5) $$ LANGUAGE sql STABLE; -SELECT * FROM rngfunc() GROUP BY 1; -DROP FUNCTION rngfunc(); - --- --- some tests on SQL functions with RETURNING --- - -create temp table tt(f1 serial, data text); - -create function insert_tt(text) returns int as -$$ insert into tt(data) values($1) returning f1 $$ -language sql; - -select insert_tt('foo'); -select insert_tt('bar'); -select * from tt; - --- insert will execute to completion even if function needs just 1 row -create or replace function insert_tt(text) returns int as -$$ insert into tt(data) values($1),($1||$1) returning f1 $$ -language sql; - -select insert_tt('fool'); -select * from tt; - --- setof does what's expected -create or replace function insert_tt2(text,text) returns setof int as -$$ insert into tt(data) values($1),($2) returning f1 $$ -language sql; - -select insert_tt2('foolish','barrish'); -select * from insert_tt2('baz','quux'); -select * from tt; - --- limit doesn't prevent execution to completion -select insert_tt2('foolish','barrish') limit 1; -select * from tt; - --- triggers will fire, too -create function noticetrigger() returns trigger as $$ -begin - raise notice 'noticetrigger % %', new.f1, new.data; - return null; -end $$ language plpgsql; -create trigger tnoticetrigger after insert on tt for each row -execute procedure noticetrigger(); - -select insert_tt2('foolme','barme') limit 1; -select * from tt; - --- and rules work -create temp table tt_log(f1 int, data text); - -create rule insert_tt_rule as on insert to tt do also - insert into tt_log values(new.*); - -select insert_tt2('foollog','barlog') limit 1; -select * from tt; --- note that nextval() gets executed a second time in the rule expansion, --- which is expected. -select * from tt_log; - --- test case for a whole-row-variable bug -create function rngfunc1(n integer, out a text, out b text) - returns setof record - language sql - as $$ select 'foo ' || i, 'bar ' || i from generate_series(1,$1) i $$; - -set work_mem='64kB'; -select t.a, t, t.a from rngfunc1(10000) t limit 1; -reset work_mem; -select t.a, t, t.a from rngfunc1(10000) t limit 1; - -drop function rngfunc1(n integer); - --- test use of SQL functions returning record --- this is supported in some cases where the query doesn't specify --- the actual record type ... - -create function array_to_set(anyarray) returns setof record as $$ - select i AS "index", $1[i] AS "value" from generate_subscripts($1, 1) i -$$ language sql strict immutable; - -select array_to_set(array['one', 'two']); -select * from array_to_set(array['one', 'two']) as t(f1 int,f2 text); -select * from array_to_set(array['one', 'two']); -- fail --- after-the-fact coercion of the columns is now possible, too -select * from array_to_set(array['one', 'two']) as t(f1 numeric(4,2),f2 text); --- and if it doesn't work, you get a compile-time not run-time error -select * from array_to_set(array['one', 'two']) as t(f1 point,f2 text); - --- with "strict", this function can't be inlined in FROM -explain (verbose, costs off) - select * from array_to_set(array['one', 'two']) as t(f1 numeric(4,2),f2 text); - --- but without, it can be: - -create or replace function array_to_set(anyarray) returns setof record as $$ - select i AS "index", $1[i] AS "value" from generate_subscripts($1, 1) i -$$ language sql immutable; - -select array_to_set(array['one', 'two']); -select * from array_to_set(array['one', 'two']) as t(f1 int,f2 text); -select * from array_to_set(array['one', 'two']) as t(f1 numeric(4,2),f2 text); -select * from array_to_set(array['one', 'two']) as t(f1 point,f2 text); -explain (verbose, costs off) - select * from array_to_set(array['one', 'two']) as t(f1 numeric(4,2),f2 text); - -create temp table rngfunc(f1 int8, f2 int8); - -create function testrngfunc() returns record as $$ - insert into rngfunc values (1,2) returning *; -$$ language sql; - -select testrngfunc(); -select * from testrngfunc() as t(f1 int8,f2 int8); -select * from testrngfunc(); -- fail - -drop function testrngfunc(); - -create function testrngfunc() returns setof record as $$ - insert into rngfunc values (1,2), (3,4) returning *; -$$ language sql; - -select testrngfunc(); -select * from testrngfunc() as t(f1 int8,f2 int8); -select * from testrngfunc(); -- fail - -drop function testrngfunc(); - --- Check that typmod imposed by a composite type is honored -create type rngfunc_type as (f1 numeric(35,6), f2 numeric(35,2)); - -create function testrngfunc() returns rngfunc_type as $$ - select 7.136178319899999964, 7.136178319899999964; -$$ language sql immutable; - -explain (verbose, costs off) -select testrngfunc(); -select testrngfunc(); -explain (verbose, costs off) -select * from testrngfunc(); -select * from testrngfunc(); - -create or replace function testrngfunc() returns rngfunc_type as $$ - select 7.136178319899999964, 7.136178319899999964; -$$ language sql volatile; - -explain (verbose, costs off) -select testrngfunc(); -select testrngfunc(); -explain (verbose, costs off) -select * from testrngfunc(); -select * from testrngfunc(); - -drop function testrngfunc(); - -create function testrngfunc() returns setof rngfunc_type as $$ - select 7.136178319899999964, 7.136178319899999964; -$$ language sql immutable; - -explain (verbose, costs off) -select testrngfunc(); -select testrngfunc(); -explain (verbose, costs off) -select * from testrngfunc(); -select * from testrngfunc(); - -create or replace function testrngfunc() returns setof rngfunc_type as $$ - select 7.136178319899999964, 7.136178319899999964; -$$ language sql volatile; - -explain (verbose, costs off) -select testrngfunc(); -select testrngfunc(); -explain (verbose, costs off) -select * from testrngfunc(); -select * from testrngfunc(); - -create or replace function testrngfunc() returns setof rngfunc_type as $$ - select 1, 2 union select 3, 4 order by 1; -$$ language sql immutable; - -explain (verbose, costs off) -select testrngfunc(); -select testrngfunc(); -explain (verbose, costs off) -select * from testrngfunc(); -select * from testrngfunc(); - --- Check a couple of error cases while we're here -select * from testrngfunc() as t(f1 int8,f2 int8); -- fail, composite result -select * from pg_get_keywords() as t(f1 int8,f2 int8); -- fail, OUT params -select * from sin(3) as t(f1 int8,f2 int8); -- fail, scalar result type - -drop type rngfunc_type cascade; - --- --- Check some cases involving added/dropped columns in a rowtype result --- - -create temp table users (userid text, seq int, email text, todrop bool, moredrop int, enabled bool); -insert into users values ('id',1,'email',true,11,true); -insert into users values ('id2',2,'email2',true,12,true); -alter table users drop column todrop; - -create or replace function get_first_user() returns users as -$$ SELECT * FROM users ORDER BY userid LIMIT 1; $$ -language sql stable; - -SELECT get_first_user(); -SELECT * FROM get_first_user(); - -create or replace function get_users() returns setof users as -$$ SELECT * FROM users ORDER BY userid; $$ -language sql stable; - -SELECT get_users(); -SELECT * FROM get_users(); -SELECT * FROM get_users() WITH ORDINALITY; -- make sure ordinality copes - --- multiple functions vs. dropped columns -SELECT * FROM ROWS FROM(generate_series(10,11), get_users()) WITH ORDINALITY; -SELECT * FROM ROWS FROM(get_users(), generate_series(10,11)) WITH ORDINALITY; - --- check that we can cope with post-parsing changes in rowtypes -create temp view usersview as -SELECT * FROM ROWS FROM(get_users(), generate_series(10,11)) WITH ORDINALITY; - -select * from usersview; -alter table users add column junk text; -select * from usersview; -begin; -alter table users drop column moredrop; -select * from usersview; -- expect clean failure -rollback; -alter table users alter column seq type numeric; -select * from usersview; -- expect clean failure - -drop view usersview; -drop function get_first_user(); -drop function get_users(); -drop table users; - --- check behavior with type coercion required for a set-op - -create or replace function rngfuncbar() returns setof text as -$$ select 'foo'::varchar union all select 'bar'::varchar ; $$ -language sql stable; - -select rngfuncbar(); -select * from rngfuncbar(); --- this function is now inlinable, too: -explain (verbose, costs off) select * from rngfuncbar(); - -drop function rngfuncbar(); - --- check handling of a SQL function with multiple OUT params (bug #5777) - -create or replace function rngfuncbar(out integer, out numeric) as -$$ select (1, 2.1) $$ language sql; - -select * from rngfuncbar(); - -create or replace function rngfuncbar(out integer, out numeric) as -$$ select (1, 2) $$ language sql; - -select * from rngfuncbar(); -- fail - -create or replace function rngfuncbar(out integer, out numeric) as -$$ select (1, 2.1, 3) $$ language sql; - -select * from rngfuncbar(); -- fail - -drop function rngfuncbar(); - --- check whole-row-Var handling in nested lateral functions (bug #11703) - -create function extractq2(t int8_tbl) returns int8 as $$ - select t.q2 -$$ language sql immutable; - -explain (verbose, costs off) -select x from int8_tbl, extractq2(int8_tbl) f(x); - -select x from int8_tbl, extractq2(int8_tbl) f(x); - -create function extractq2_2(t int8_tbl) returns table(ret1 int8) as $$ - select extractq2(t) offset 0 -$$ language sql immutable; - -explain (verbose, costs off) -select x from int8_tbl, extractq2_2(int8_tbl) f(x); - -select x from int8_tbl, extractq2_2(int8_tbl) f(x); - --- without the "offset 0", this function gets optimized quite differently - -create function extractq2_2_opt(t int8_tbl) returns table(ret1 int8) as $$ - select extractq2(t) -$$ language sql immutable; - -explain (verbose, costs off) -select x from int8_tbl, extractq2_2_opt(int8_tbl) f(x); - -select x from int8_tbl, extractq2_2_opt(int8_tbl) f(x); - --- check handling of nulls in SRF results (bug #7808) - -create type rngfunc2 as (a integer, b text); - -select *, row_to_json(u) from unnest(array[(1,'foo')::rngfunc2, null::rngfunc2]) u; -select *, row_to_json(u) from unnest(array[null::rngfunc2, null::rngfunc2]) u; -select *, row_to_json(u) from unnest(array[null::rngfunc2, (1,'foo')::rngfunc2, null::rngfunc2]) u; -select *, row_to_json(u) from unnest(array[]::rngfunc2[]) u; - -drop type rngfunc2; - --- check handling of functions pulled up into function RTEs (bug #17227) - -explain (verbose, costs off) -select * from - (select jsonb_path_query_array(module->'lectures', '$[*]') as lecture - from unnest(array['{"lectures": [{"id": "1"}]}'::jsonb]) - as unnested_modules(module)) as ss, - jsonb_to_recordset(ss.lecture) as j (id text); - -select * from - (select jsonb_path_query_array(module->'lectures', '$[*]') as lecture - from unnest(array['{"lectures": [{"id": "1"}]}'::jsonb]) - as unnested_modules(module)) as ss, - jsonb_to_recordset(ss.lecture) as j (id text); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frangetypes.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frangetypes.sql deleted file mode 100644 index 1a10f67f19..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frangetypes.sql +++ /dev/null @@ -1,618 +0,0 @@ --- Tests for range data types. - --- --- test input parser --- (type textrange was already made in test_setup.sql) --- - --- negative tests; should fail -select ''::textrange; -select '-[a,z)'::textrange; -select '[a,z) - '::textrange; -select '(",a)'::textrange; -select '(,,a)'::textrange; -select '(),a)'::textrange; -select '(a,))'::textrange; -select '(],a)'::textrange; -select '(a,])'::textrange; -select '[z,a]'::textrange; - --- should succeed -select ' empty '::textrange; -select ' ( empty, empty ) '::textrange; -select ' ( " a " " a ", " z " " z " ) '::textrange; -select '(a,)'::textrange; -select '[,z]'::textrange; -select '[a,]'::textrange; -select '(,)'::textrange; -select '[ , ]'::textrange; -select '["",""]'::textrange; -select '[",",","]'::textrange; -select '["\\","\\"]'::textrange; -select '(\\,a)'::textrange; -select '((,z)'::textrange; -select '([,z)'::textrange; -select '(!,()'::textrange; -select '(!,[)'::textrange; -select '[a,a]'::textrange; --- these are allowed but normalize to empty: -select '[a,a)'::textrange; -select '(a,a]'::textrange; -select '(a,a)'::textrange; - --- --- create some test data and test the operators --- - -CREATE TABLE numrange_test (nr NUMRANGE); -create index numrange_test_btree on numrange_test(nr); - -INSERT INTO numrange_test VALUES('[,)'); -INSERT INTO numrange_test VALUES('[3,]'); -INSERT INTO numrange_test VALUES('[, 5)'); -INSERT INTO numrange_test VALUES(numrange(1.1, 2.2)); -INSERT INTO numrange_test VALUES('empty'); -INSERT INTO numrange_test VALUES(numrange(1.7, 1.7, '[]')); - -SELECT nr, isempty(nr), lower(nr), upper(nr) FROM numrange_test; -SELECT nr, lower_inc(nr), lower_inf(nr), upper_inc(nr), upper_inf(nr) FROM numrange_test; - -SELECT * FROM numrange_test WHERE range_contains(nr, numrange(1.9,1.91)); -SELECT * FROM numrange_test WHERE nr @> numrange(1.0,10000.1); -SELECT * FROM numrange_test WHERE range_contained_by(numrange(-1e7,-10000.1), nr); -SELECT * FROM numrange_test WHERE 1.9 <@ nr; - -select * from numrange_test where nr = 'empty'; -select * from numrange_test where nr = '(1.1, 2.2)'; -select * from numrange_test where nr = '[1.1, 2.2)'; -select * from numrange_test where nr < 'empty'; -select * from numrange_test where nr < numrange(-1000.0, -1000.0,'[]'); -select * from numrange_test where nr < numrange(0.0, 1.0,'[]'); -select * from numrange_test where nr < numrange(1000.0, 1001.0,'[]'); -select * from numrange_test where nr <= 'empty'; -select * from numrange_test where nr >= 'empty'; -select * from numrange_test where nr > 'empty'; -select * from numrange_test where nr > numrange(-1001.0, -1000.0,'[]'); -select * from numrange_test where nr > numrange(0.0, 1.0,'[]'); -select * from numrange_test where nr > numrange(1000.0, 1000.0,'[]'); - -select numrange(2.0, 1.0); - -select numrange(2.0, 3.0) -|- numrange(3.0, 4.0); -select range_adjacent(numrange(2.0, 3.0), numrange(3.1, 4.0)); -select range_adjacent(numrange(2.0, 3.0), numrange(3.1, null)); -select numrange(2.0, 3.0, '[]') -|- numrange(3.0, 4.0, '()'); -select numrange(1.0, 2.0) -|- numrange(2.0, 3.0,'[]'); -select range_adjacent(numrange(2.0, 3.0, '(]'), numrange(1.0, 2.0, '(]')); - -select numrange(1.1, 3.3) <@ numrange(0.1,10.1); -select numrange(0.1, 10.1) <@ numrange(1.1,3.3); - -select numrange(1.1, 2.2) - numrange(2.0, 3.0); -select numrange(1.1, 2.2) - numrange(2.2, 3.0); -select numrange(1.1, 2.2,'[]') - numrange(2.0, 3.0); -select range_minus(numrange(10.1,12.2,'[]'), numrange(110.0,120.2,'(]')); -select range_minus(numrange(10.1,12.2,'[]'), numrange(0.0,120.2,'(]')); - -select numrange(4.5, 5.5, '[]') && numrange(5.5, 6.5); -select numrange(1.0, 2.0) << numrange(3.0, 4.0); -select numrange(1.0, 3.0,'[]') << numrange(3.0, 4.0,'[]'); -select numrange(1.0, 3.0,'()') << numrange(3.0, 4.0,'()'); -select numrange(1.0, 2.0) >> numrange(3.0, 4.0); -select numrange(3.0, 70.0) &< numrange(6.6, 100.0); - -select numrange(1.1, 2.2) < numrange(1.0, 200.2); -select numrange(1.1, 2.2) < numrange(1.1, 1.2); - -select numrange(1.0, 2.0) + numrange(2.0, 3.0); -select numrange(1.0, 2.0) + numrange(1.5, 3.0); -select numrange(1.0, 2.0) + numrange(2.5, 3.0); -- should fail - -select range_merge(numrange(1.0, 2.0), numrange(2.0, 3.0)); -select range_merge(numrange(1.0, 2.0), numrange(1.5, 3.0)); -select range_merge(numrange(1.0, 2.0), numrange(2.5, 3.0)); -- shouldn't fail - -select numrange(1.0, 2.0) * numrange(2.0, 3.0); -select numrange(1.0, 2.0) * numrange(1.5, 3.0); -select numrange(1.0, 2.0) * numrange(2.5, 3.0); - -select range_intersect_agg(nr) from numrange_test; -select range_intersect_agg(nr) from numrange_test where false; -select range_intersect_agg(nr) from numrange_test where nr @> 4.0; - -analyze numrange_test; - -create table numrange_test2(nr numrange); -create index numrange_test2_hash_idx on numrange_test2 using hash (nr); - -INSERT INTO numrange_test2 VALUES('[, 5)'); -INSERT INTO numrange_test2 VALUES(numrange(1.1, 2.2)); -INSERT INTO numrange_test2 VALUES(numrange(1.1, 2.2)); -INSERT INTO numrange_test2 VALUES(numrange(1.1, 2.2,'()')); -INSERT INTO numrange_test2 VALUES('empty'); - -select * from numrange_test2 where nr = 'empty'::numrange; -select * from numrange_test2 where nr = numrange(1.1, 2.2); -select * from numrange_test2 where nr = numrange(1.1, 2.3); - -set enable_nestloop=t; -set enable_hashjoin=f; -set enable_mergejoin=f; -select * from numrange_test natural join numrange_test2 order by nr; -set enable_nestloop=f; -set enable_hashjoin=t; -set enable_mergejoin=f; -select * from numrange_test natural join numrange_test2 order by nr; -set enable_nestloop=f; -set enable_hashjoin=f; -set enable_mergejoin=t; -select * from numrange_test natural join numrange_test2 order by nr; - -set enable_nestloop to default; -set enable_hashjoin to default; -set enable_mergejoin to default; - --- keep numrange_test around to help exercise dump/reload -DROP TABLE numrange_test2; - --- --- Apply a subset of the above tests on a collatable type, too --- - -CREATE TABLE textrange_test (tr textrange); -create index textrange_test_btree on textrange_test(tr); - -INSERT INTO textrange_test VALUES('[,)'); -INSERT INTO textrange_test VALUES('["a",]'); -INSERT INTO textrange_test VALUES('[,"q")'); -INSERT INTO textrange_test VALUES(textrange('b', 'g')); -INSERT INTO textrange_test VALUES('empty'); -INSERT INTO textrange_test VALUES(textrange('d', 'd', '[]')); - -SELECT tr, isempty(tr), lower(tr), upper(tr) FROM textrange_test; -SELECT tr, lower_inc(tr), lower_inf(tr), upper_inc(tr), upper_inf(tr) FROM textrange_test; - -SELECT * FROM textrange_test WHERE range_contains(tr, textrange('f', 'fx')); -SELECT * FROM textrange_test WHERE tr @> textrange('a', 'z'); -SELECT * FROM textrange_test WHERE range_contained_by(textrange('0','9'), tr); -SELECT * FROM textrange_test WHERE 'e'::text <@ tr; - -select * from textrange_test where tr = 'empty'; -select * from textrange_test where tr = '("b","g")'; -select * from textrange_test where tr = '["b","g")'; -select * from textrange_test where tr < 'empty'; - - --- test canonical form for int4range -select int4range(1, 10, '[]'); -select int4range(1, 10, '[)'); -select int4range(1, 10, '(]'); -select int4range(1, 10, '()'); -select int4range(1, 2, '()'); - --- test canonical form for daterange -select daterange('2000-01-10'::date, '2000-01-20'::date, '[]'); -select daterange('2000-01-10'::date, '2000-01-20'::date, '[)'); -select daterange('2000-01-10'::date, '2000-01-20'::date, '(]'); -select daterange('2000-01-10'::date, '2000-01-20'::date, '()'); -select daterange('2000-01-10'::date, '2000-01-11'::date, '()'); -select daterange('2000-01-10'::date, '2000-01-11'::date, '(]'); -select daterange('-infinity'::date, '2000-01-01'::date, '()'); -select daterange('-infinity'::date, '2000-01-01'::date, '[)'); -select daterange('2000-01-01'::date, 'infinity'::date, '[)'); -select daterange('2000-01-01'::date, 'infinity'::date, '[]'); - --- test GiST index that's been built incrementally -create table test_range_gist(ir int4range); -create index test_range_gist_idx on test_range_gist using gist (ir); - -insert into test_range_gist select int4range(g, g+10) from generate_series(1,2000) g; -insert into test_range_gist select 'empty'::int4range from generate_series(1,500) g; -insert into test_range_gist select int4range(g, g+10000) from generate_series(1,1000) g; -insert into test_range_gist select 'empty'::int4range from generate_series(1,500) g; -insert into test_range_gist select int4range(NULL,g*10,'(]') from generate_series(1,100) g; -insert into test_range_gist select int4range(g*10,NULL,'(]') from generate_series(1,100) g; -insert into test_range_gist select int4range(g, g+10) from generate_series(1,2000) g; - --- test statistics and selectivity estimation as well --- --- We don't check the accuracy of selectivity estimation, but at least check --- it doesn't fall. -analyze test_range_gist; - --- first, verify non-indexed results -SET enable_seqscan = t; -SET enable_indexscan = f; -SET enable_bitmapscan = f; - -select count(*) from test_range_gist where ir @> 'empty'::int4range; -select count(*) from test_range_gist where ir = int4range(10,20); -select count(*) from test_range_gist where ir @> 10; -select count(*) from test_range_gist where ir @> int4range(10,20); -select count(*) from test_range_gist where ir && int4range(10,20); -select count(*) from test_range_gist where ir <@ int4range(10,50); -select count(*) from test_range_gist where ir << int4range(100,500); -select count(*) from test_range_gist where ir >> int4range(100,500); -select count(*) from test_range_gist where ir &< int4range(100,500); -select count(*) from test_range_gist where ir &> int4range(100,500); -select count(*) from test_range_gist where ir -|- int4range(100,500); -select count(*) from test_range_gist where ir @> '{}'::int4multirange; -select count(*) from test_range_gist where ir @> int4multirange(int4range(10,20), int4range(30,40)); -select count(*) from test_range_gist where ir && '{(10,20),(30,40),(50,60)}'::int4multirange; -select count(*) from test_range_gist where ir <@ '{(10,30),(40,60),(70,90)}'::int4multirange; -select count(*) from test_range_gist where ir << int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir >> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir &< int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir &> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir -|- int4multirange(int4range(100,200), int4range(400,500)); - --- now check same queries using index -SET enable_seqscan = f; -SET enable_indexscan = t; -SET enable_bitmapscan = f; - -select count(*) from test_range_gist where ir @> 'empty'::int4range; -select count(*) from test_range_gist where ir = int4range(10,20); -select count(*) from test_range_gist where ir @> 10; -select count(*) from test_range_gist where ir @> int4range(10,20); -select count(*) from test_range_gist where ir && int4range(10,20); -select count(*) from test_range_gist where ir <@ int4range(10,50); -select count(*) from test_range_gist where ir << int4range(100,500); -select count(*) from test_range_gist where ir >> int4range(100,500); -select count(*) from test_range_gist where ir &< int4range(100,500); -select count(*) from test_range_gist where ir &> int4range(100,500); -select count(*) from test_range_gist where ir -|- int4range(100,500); -select count(*) from test_range_gist where ir @> '{}'::int4multirange; -select count(*) from test_range_gist where ir @> int4multirange(int4range(10,20), int4range(30,40)); -select count(*) from test_range_gist where ir && '{(10,20),(30,40),(50,60)}'::int4multirange; -select count(*) from test_range_gist where ir <@ '{(10,30),(40,60),(70,90)}'::int4multirange; -select count(*) from test_range_gist where ir << int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir >> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir &< int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir &> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir -|- int4multirange(int4range(100,200), int4range(400,500)); - --- now check same queries using a bulk-loaded index -drop index test_range_gist_idx; -create index test_range_gist_idx on test_range_gist using gist (ir); - -select count(*) from test_range_gist where ir @> 'empty'::int4range; -select count(*) from test_range_gist where ir = int4range(10,20); -select count(*) from test_range_gist where ir @> 10; -select count(*) from test_range_gist where ir @> int4range(10,20); -select count(*) from test_range_gist where ir && int4range(10,20); -select count(*) from test_range_gist where ir <@ int4range(10,50); -select count(*) from test_range_gist where ir << int4range(100,500); -select count(*) from test_range_gist where ir >> int4range(100,500); -select count(*) from test_range_gist where ir &< int4range(100,500); -select count(*) from test_range_gist where ir &> int4range(100,500); -select count(*) from test_range_gist where ir -|- int4range(100,500); -select count(*) from test_range_gist where ir @> '{}'::int4multirange; -select count(*) from test_range_gist where ir @> int4multirange(int4range(10,20), int4range(30,40)); -select count(*) from test_range_gist where ir && '{(10,20),(30,40),(50,60)}'::int4multirange; -select count(*) from test_range_gist where ir <@ '{(10,30),(40,60),(70,90)}'::int4multirange; -select count(*) from test_range_gist where ir << int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir >> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir &< int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir &> int4multirange(int4range(100,200), int4range(400,500)); -select count(*) from test_range_gist where ir -|- int4multirange(int4range(100,200), int4range(400,500)); - --- test SP-GiST index that's been built incrementally -create table test_range_spgist(ir int4range); -create index test_range_spgist_idx on test_range_spgist using spgist (ir); - -insert into test_range_spgist select int4range(g, g+10) from generate_series(1,2000) g; -insert into test_range_spgist select 'empty'::int4range from generate_series(1,500) g; -insert into test_range_spgist select int4range(g, g+10000) from generate_series(1,1000) g; -insert into test_range_spgist select 'empty'::int4range from generate_series(1,500) g; -insert into test_range_spgist select int4range(NULL,g*10,'(]') from generate_series(1,100) g; -insert into test_range_spgist select int4range(g*10,NULL,'(]') from generate_series(1,100) g; -insert into test_range_spgist select int4range(g, g+10) from generate_series(1,2000) g; - --- first, verify non-indexed results -SET enable_seqscan = t; -SET enable_indexscan = f; -SET enable_bitmapscan = f; - -select count(*) from test_range_spgist where ir @> 'empty'::int4range; -select count(*) from test_range_spgist where ir = int4range(10,20); -select count(*) from test_range_spgist where ir @> 10; -select count(*) from test_range_spgist where ir @> int4range(10,20); -select count(*) from test_range_spgist where ir && int4range(10,20); -select count(*) from test_range_spgist where ir <@ int4range(10,50); -select count(*) from test_range_spgist where ir << int4range(100,500); -select count(*) from test_range_spgist where ir >> int4range(100,500); -select count(*) from test_range_spgist where ir &< int4range(100,500); -select count(*) from test_range_spgist where ir &> int4range(100,500); -select count(*) from test_range_spgist where ir -|- int4range(100,500); - --- now check same queries using index -SET enable_seqscan = f; -SET enable_indexscan = t; -SET enable_bitmapscan = f; - -select count(*) from test_range_spgist where ir @> 'empty'::int4range; -select count(*) from test_range_spgist where ir = int4range(10,20); -select count(*) from test_range_spgist where ir @> 10; -select count(*) from test_range_spgist where ir @> int4range(10,20); -select count(*) from test_range_spgist where ir && int4range(10,20); -select count(*) from test_range_spgist where ir <@ int4range(10,50); -select count(*) from test_range_spgist where ir << int4range(100,500); -select count(*) from test_range_spgist where ir >> int4range(100,500); -select count(*) from test_range_spgist where ir &< int4range(100,500); -select count(*) from test_range_spgist where ir &> int4range(100,500); -select count(*) from test_range_spgist where ir -|- int4range(100,500); - --- now check same queries using a bulk-loaded index -drop index test_range_spgist_idx; -create index test_range_spgist_idx on test_range_spgist using spgist (ir); - -select count(*) from test_range_spgist where ir @> 'empty'::int4range; -select count(*) from test_range_spgist where ir = int4range(10,20); -select count(*) from test_range_spgist where ir @> 10; -select count(*) from test_range_spgist where ir @> int4range(10,20); -select count(*) from test_range_spgist where ir && int4range(10,20); -select count(*) from test_range_spgist where ir <@ int4range(10,50); -select count(*) from test_range_spgist where ir << int4range(100,500); -select count(*) from test_range_spgist where ir >> int4range(100,500); -select count(*) from test_range_spgist where ir &< int4range(100,500); -select count(*) from test_range_spgist where ir &> int4range(100,500); -select count(*) from test_range_spgist where ir -|- int4range(100,500); - --- test index-only scans -explain (costs off) -select ir from test_range_spgist where ir -|- int4range(10,20) order by ir; -select ir from test_range_spgist where ir -|- int4range(10,20) order by ir; - -RESET enable_seqscan; -RESET enable_indexscan; -RESET enable_bitmapscan; - --- test elem <@ range operator -create table test_range_elem(i int4); -create index test_range_elem_idx on test_range_elem (i); -insert into test_range_elem select i from generate_series(1,100) i; - -SET enable_seqscan = f; - -select count(*) from test_range_elem where i <@ int4range(10,50); - --- also test spgist index on anyrange expression -create index on test_range_elem using spgist(int4range(i,i+10)); -explain (costs off) -select count(*) from test_range_elem where int4range(i,i+10) <@ int4range(10,30); -select count(*) from test_range_elem where int4range(i,i+10) <@ int4range(10,30); - -RESET enable_seqscan; - -drop table test_range_elem; - --- --- Btree_gist is not included by default, so to test exclusion --- constraints with range types, use singleton int ranges for the "=" --- portion of the constraint. --- - -create table test_range_excl( - room int4range, - speaker int4range, - during tsrange, - exclude using gist (room with =, during with &&), - exclude using gist (speaker with =, during with &&) -); - -insert into test_range_excl - values(int4range(123, 123, '[]'), int4range(1, 1, '[]'), '[2010-01-02 10:00, 2010-01-02 11:00)'); -insert into test_range_excl - values(int4range(123, 123, '[]'), int4range(2, 2, '[]'), '[2010-01-02 11:00, 2010-01-02 12:00)'); -insert into test_range_excl - values(int4range(123, 123, '[]'), int4range(3, 3, '[]'), '[2010-01-02 10:10, 2010-01-02 11:00)'); -insert into test_range_excl - values(int4range(124, 124, '[]'), int4range(3, 3, '[]'), '[2010-01-02 10:10, 2010-01-02 11:10)'); -insert into test_range_excl - values(int4range(125, 125, '[]'), int4range(1, 1, '[]'), '[2010-01-02 10:10, 2010-01-02 11:00)'); - --- test bigint ranges -select int8range(10000000000::int8, 20000000000::int8,'(]'); --- test tstz ranges -set timezone to '-08'; -select '[2010-01-01 01:00:00 -05, 2010-01-01 02:00:00 -08)'::tstzrange; --- should fail -select '[2010-01-01 01:00:00 -08, 2010-01-01 02:00:00 -05)'::tstzrange; -set timezone to default; - --- --- Test user-defined range of floats --- (type float8range was already made in test_setup.sql) --- - ---should fail -create type bogus_float8range as range (subtype=float8, subtype_diff=float4mi); - -select '[123.001, 5.e9)'::float8range @> 888.882::float8; -create table float8range_test(f8r float8range, i int); -insert into float8range_test values(float8range(-100.00007, '1.111113e9'), 42); -select * from float8range_test; -drop table float8range_test; - --- --- Test range types over domains --- - -create domain mydomain as int4; -create type mydomainrange as range(subtype=mydomain); -select '[4,50)'::mydomainrange @> 7::mydomain; -drop domain mydomain; -- fail -drop domain mydomain cascade; - --- --- Test domains over range types --- - -create domain restrictedrange as int4range check (upper(value) < 10); -select '[4,5)'::restrictedrange @> 7; -select '[4,50)'::restrictedrange @> 7; -- should fail -drop domain restrictedrange; - --- --- Test multiple range types over the same subtype --- - -create type textrange1 as range(subtype=text, collation="C"); -create type textrange2 as range(subtype=text, collation="C"); - -select textrange1('a','Z') @> 'b'::text; -select textrange2('a','z') @> 'b'::text; - -drop type textrange1; -drop type textrange2; - --- --- Test polymorphic type system --- - -create function anyarray_anyrange_func(a anyarray, r anyrange) - returns anyelement as 'select $1[1] + lower($2);' language sql; - -select anyarray_anyrange_func(ARRAY[1,2], int4range(10,20)); - --- should fail -select anyarray_anyrange_func(ARRAY[1,2], numrange(10,20)); - -drop function anyarray_anyrange_func(anyarray, anyrange); - --- should fail -create function bogus_func(anyelement) - returns anyrange as 'select int4range(1,10)' language sql; - --- should fail -create function bogus_func(int) - returns anyrange as 'select int4range(1,10)' language sql; - -create function range_add_bounds(anyrange) - returns anyelement as 'select lower($1) + upper($1)' language sql; - -select range_add_bounds(int4range(1, 17)); -select range_add_bounds(numrange(1.0001, 123.123)); - -create function rangetypes_sql(q anyrange, b anyarray, out c anyelement) - as $$ select upper($1) + $2[1] $$ - language sql; - -select rangetypes_sql(int4range(1,10), ARRAY[2,20]); -select rangetypes_sql(numrange(1,10), ARRAY[2,20]); -- match failure - -create function anycompatiblearray_anycompatiblerange_func(a anycompatiblearray, r anycompatiblerange) - returns anycompatible as 'select $1[1] + lower($2);' language sql; - -select anycompatiblearray_anycompatiblerange_func(ARRAY[1,2], int4range(10,20)); - -select anycompatiblearray_anycompatiblerange_func(ARRAY[1,2], numrange(10,20)); - --- should fail -select anycompatiblearray_anycompatiblerange_func(ARRAY[1.1,2], int4range(10,20)); - -drop function anycompatiblearray_anycompatiblerange_func(anycompatiblearray, anycompatiblerange); - --- should fail -create function bogus_func(anycompatible) - returns anycompatiblerange as 'select int4range(1,10)' language sql; - --- --- Arrays of ranges --- - -select ARRAY[numrange(1.1, 1.2), numrange(12.3, 155.5)]; - -create table i8r_array (f1 int, f2 int8range[]); -insert into i8r_array values (42, array[int8range(1,10), int8range(2,20)]); -select * from i8r_array; -drop table i8r_array; - --- --- Ranges of arrays --- - -create type arrayrange as range (subtype=int4[]); - -select arrayrange(ARRAY[1,2], ARRAY[2,1]); -select arrayrange(ARRAY[2,1], ARRAY[1,2]); -- fail - -select array[1,1] <@ arrayrange(array[1,2], array[2,1]); -select array[1,3] <@ arrayrange(array[1,2], array[2,1]); - --- --- Ranges of composites --- - -create type two_ints as (a int, b int); -create type two_ints_range as range (subtype = two_ints); - --- with force_parallel_mode on, this exercises tqueue.c's range remapping -select *, row_to_json(upper(t)) as u from - (values (two_ints_range(row(1,2), row(3,4))), - (two_ints_range(row(5,6), row(7,8)))) v(t); - --- this must be rejected to avoid self-inclusion issues: -alter type two_ints add attribute c two_ints_range; - -drop type two_ints cascade; - --- --- Check behavior when subtype lacks a hash function --- - -create type cashrange as range (subtype = money); - -set enable_sort = off; -- try to make it pick a hash setop implementation - -select '(2,5)'::cashrange except select '(5,6)'::cashrange; - -reset enable_sort; - --- --- OUT/INOUT/TABLE functions --- - --- infer anyrange from anyrange -create function outparam_succeed(i anyrange, out r anyrange, out t text) - as $$ select $1, 'foo'::text $$ language sql; - -select * from outparam_succeed(int4range(1,2)); - -create function outparam2_succeed(r anyrange, out lu anyarray, out ul anyarray) - as $$ select array[lower($1), upper($1)], array[upper($1), lower($1)] $$ - language sql; - -select * from outparam2_succeed(int4range(1,11)); - --- infer anyarray from anyrange -create function outparam_succeed2(i anyrange, out r anyarray, out t text) - as $$ select ARRAY[upper($1)], 'foo'::text $$ language sql; - -select * from outparam_succeed2(int4range(int4range(1,2))); - --- infer anyelement from anyrange -create function inoutparam_succeed(out i anyelement, inout r anyrange) - as $$ select upper($1), $1 $$ language sql; - -select * from inoutparam_succeed(int4range(1,2)); - -create function table_succeed(r anyrange) - returns table(l anyelement, u anyelement) - as $$ select lower($1), upper($1) $$ - language sql; - -select * from table_succeed(int4range(1,11)); - --- should fail -create function outparam_fail(i anyelement, out r anyrange, out t text) - as $$ select '[1,10]', 'foo' $$ language sql; - ---should fail -create function inoutparam_fail(inout i anyelement, out r anyrange) - as $$ select $1, '[1,10]' $$ language sql; - ---should fail -create function table_fail(i anyelement) returns table(i anyelement, r anyrange) - as $$ select $1, '[1,10]' $$ language sql; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Freindex_catalog.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Freindex_catalog.sql deleted file mode 100644 index 8203641cf9..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Freindex_catalog.sql +++ /dev/null @@ -1,52 +0,0 @@ --- --- Check that system tables can be reindexed. --- --- Note that this test currently is not included in the default --- schedules, as currently reindexing catalog tables can cause --- deadlocks: --- --- * The lock upgrade between the ShareLock acquired for the reindex --- and RowExclusiveLock needed for pg_class/pg_index locks can --- trigger deadlocks. --- --- * The uniqueness checks performed when reindexing a unique/primary --- key index possibly need to wait for the transaction of a --- about-to-deleted row in pg_class to commit. That can cause --- deadlocks because, in contrast to user tables, locks on catalog --- tables are routinely released before commit - therefore the lock --- held for reindexing doesn't guarantee that no running transaction --- performed modifications in the table underlying the index. --- --- This is particularly problematic as such conflicts can be --- triggered even when run in isolation, as a previous session's --- temporary table cleanup might still be running (even when the --- session ended from a client perspective). - - --- Check reindexing of whole tables -REINDEX TABLE pg_class; -- mapped, non-shared, critical -REINDEX TABLE pg_index; -- non-mapped, non-shared, critical -REINDEX TABLE pg_operator; -- non-mapped, non-shared, critical -REINDEX TABLE pg_database; -- mapped, shared, critical -REINDEX TABLE pg_shdescription; -- mapped, shared non-critical - --- Check that individual system indexes can be reindexed. That's a bit --- different from the entire-table case because reindex_relation --- treats e.g. pg_class special. -REINDEX INDEX pg_class_oid_index; -- mapped, non-shared, critical -REINDEX INDEX pg_class_relname_nsp_index; -- mapped, non-shared, non-critical -REINDEX INDEX pg_index_indexrelid_index; -- non-mapped, non-shared, critical -REINDEX INDEX pg_index_indrelid_index; -- non-mapped, non-shared, non-critical -REINDEX INDEX pg_database_oid_index; -- mapped, shared, critical -REINDEX INDEX pg_shdescription_o_c_index; -- mapped, shared, non-critical - --- Check the same REINDEX INDEX statements under parallelism. -BEGIN; -SET min_parallel_table_scan_size = 0; -REINDEX INDEX pg_class_oid_index; -- mapped, non-shared, critical -REINDEX INDEX pg_class_relname_nsp_index; -- mapped, non-shared, non-critical -REINDEX INDEX pg_index_indexrelid_index; -- non-mapped, non-shared, critical -REINDEX INDEX pg_index_indrelid_index; -- non-mapped, non-shared, non-critical -REINDEX INDEX pg_database_oid_index; -- mapped, shared, critical -REINDEX INDEX pg_shdescription_o_c_index; -- mapped, shared, non-critical -ROLLBACK; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frowsecurity.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frowsecurity.sql deleted file mode 100644 index febf3cc4cf..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frowsecurity.sql +++ /dev/null @@ -1,2151 +0,0 @@ --- --- Test of Row-level security feature --- - --- Clean up in case a prior regression run failed - --- Suppress NOTICE messages when users/groups don't exist -SET client_min_messages TO 'warning'; - -DROP USER IF EXISTS regress_rls_alice; -DROP USER IF EXISTS regress_rls_bob; -DROP USER IF EXISTS regress_rls_carol; -DROP USER IF EXISTS regress_rls_dave; -DROP USER IF EXISTS regress_rls_exempt_user; -DROP ROLE IF EXISTS regress_rls_group1; -DROP ROLE IF EXISTS regress_rls_group2; - -DROP SCHEMA IF EXISTS regress_rls_schema CASCADE; - -RESET client_min_messages; - --- initial setup -CREATE USER regress_rls_alice NOLOGIN; -CREATE USER regress_rls_bob NOLOGIN; -CREATE USER regress_rls_carol NOLOGIN; -CREATE USER regress_rls_dave NOLOGIN; -CREATE USER regress_rls_exempt_user BYPASSRLS NOLOGIN; -CREATE ROLE regress_rls_group1 NOLOGIN; -CREATE ROLE regress_rls_group2 NOLOGIN; - -GRANT regress_rls_group1 TO regress_rls_bob; -GRANT regress_rls_group2 TO regress_rls_carol; - -CREATE SCHEMA regress_rls_schema; -GRANT ALL ON SCHEMA regress_rls_schema to public; -SET search_path = regress_rls_schema; - --- setup of malicious function -CREATE OR REPLACE FUNCTION f_leak(text) RETURNS bool - COST 0.0000001 LANGUAGE plpgsql - AS 'BEGIN RAISE NOTICE ''f_leak => %'', $1; RETURN true; END'; -GRANT EXECUTE ON FUNCTION f_leak(text) TO public; - --- BASIC Row-Level Security Scenario - -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE uaccount ( - pguser name primary key, - seclv int -); -GRANT SELECT ON uaccount TO public; -INSERT INTO uaccount VALUES - ('regress_rls_alice', 99), - ('regress_rls_bob', 1), - ('regress_rls_carol', 2), - ('regress_rls_dave', 3); - -CREATE TABLE category ( - cid int primary key, - cname text -); -GRANT ALL ON category TO public; -INSERT INTO category VALUES - (11, 'novel'), - (22, 'science fiction'), - (33, 'technology'), - (44, 'manga'); - -CREATE TABLE document ( - did int primary key, - cid int references category(cid), - dlevel int not null, - dauthor name, - dtitle text -); -GRANT ALL ON document TO public; -INSERT INTO document VALUES - ( 1, 11, 1, 'regress_rls_bob', 'my first novel'), - ( 2, 11, 2, 'regress_rls_bob', 'my second novel'), - ( 3, 22, 2, 'regress_rls_bob', 'my science fiction'), - ( 4, 44, 1, 'regress_rls_bob', 'my first manga'), - ( 5, 44, 2, 'regress_rls_bob', 'my second manga'), - ( 6, 22, 1, 'regress_rls_carol', 'great science fiction'), - ( 7, 33, 2, 'regress_rls_carol', 'great technology book'), - ( 8, 44, 1, 'regress_rls_carol', 'great manga'), - ( 9, 22, 1, 'regress_rls_dave', 'awesome science fiction'), - (10, 33, 2, 'regress_rls_dave', 'awesome technology book'); - -ALTER TABLE document ENABLE ROW LEVEL SECURITY; - --- user's security level must be higher than or equal to document's -CREATE POLICY p1 ON document AS PERMISSIVE - USING (dlevel <= (SELECT seclv FROM uaccount WHERE pguser = current_user)); - --- try to create a policy of bogus type -CREATE POLICY p1 ON document AS UGLY - USING (dlevel <= (SELECT seclv FROM uaccount WHERE pguser = current_user)); - --- but Dave isn't allowed to anything at cid 50 or above --- this is to make sure that we sort the policies by name first --- when applying WITH CHECK, a later INSERT by Dave should fail due --- to p1r first -CREATE POLICY p2r ON document AS RESTRICTIVE TO regress_rls_dave - USING (cid <> 44 AND cid < 50); - --- and Dave isn't allowed to see manga documents -CREATE POLICY p1r ON document AS RESTRICTIVE TO regress_rls_dave - USING (cid <> 44); - -\dp -\d document -SELECT * FROM pg_policies WHERE schemaname = 'regress_rls_schema' AND tablename = 'document' ORDER BY policyname; - --- viewpoint from regress_rls_bob -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO ON; -SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; -SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER BY did; - --- try a sampled version -SELECT * FROM document TABLESAMPLE BERNOULLI(50) REPEATABLE(0) - WHERE f_leak(dtitle) ORDER BY did; - --- viewpoint from regress_rls_carol -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; -SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER BY did; - --- try a sampled version -SELECT * FROM document TABLESAMPLE BERNOULLI(50) REPEATABLE(0) - WHERE f_leak(dtitle) ORDER BY did; - -EXPLAIN (COSTS OFF) SELECT * FROM document WHERE f_leak(dtitle); -EXPLAIN (COSTS OFF) SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle); - --- viewpoint from regress_rls_dave -SET SESSION AUTHORIZATION regress_rls_dave; -SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; -SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER BY did; - -EXPLAIN (COSTS OFF) SELECT * FROM document WHERE f_leak(dtitle); -EXPLAIN (COSTS OFF) SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle); - --- 44 would technically fail for both p2r and p1r, but we should get an error --- back from p1r for this because it sorts first -INSERT INTO document VALUES (100, 44, 1, 'regress_rls_dave', 'testing sorting of policies'); -- fail --- Just to see a p2r error -INSERT INTO document VALUES (100, 55, 1, 'regress_rls_dave', 'testing sorting of policies'); -- fail - --- only owner can change policies -ALTER POLICY p1 ON document USING (true); --fail -DROP POLICY p1 ON document; --fail - -SET SESSION AUTHORIZATION regress_rls_alice; -ALTER POLICY p1 ON document USING (dauthor = current_user); - --- viewpoint from regress_rls_bob again -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; -SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER by did; - --- viewpoint from rls_regres_carol again -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM document WHERE f_leak(dtitle) ORDER BY did; -SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle) ORDER by did; - -EXPLAIN (COSTS OFF) SELECT * FROM document WHERE f_leak(dtitle); -EXPLAIN (COSTS OFF) SELECT * FROM document NATURAL JOIN category WHERE f_leak(dtitle); - --- interaction of FK/PK constraints -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE POLICY p2 ON category - USING (CASE WHEN current_user = 'regress_rls_bob' THEN cid IN (11, 33) - WHEN current_user = 'regress_rls_carol' THEN cid IN (22, 44) - ELSE false END); - -ALTER TABLE category ENABLE ROW LEVEL SECURITY; - --- cannot delete PK referenced by invisible FK -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM document d FULL OUTER JOIN category c on d.cid = c.cid ORDER BY d.did, c.cid; -DELETE FROM category WHERE cid = 33; -- fails with FK violation - --- can insert FK referencing invisible PK -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM document d FULL OUTER JOIN category c on d.cid = c.cid ORDER BY d.did, c.cid; -INSERT INTO document VALUES (11, 33, 1, current_user, 'hoge'); - --- UNIQUE or PRIMARY KEY constraint violation DOES reveal presence of row -SET SESSION AUTHORIZATION regress_rls_bob; -INSERT INTO document VALUES (8, 44, 1, 'regress_rls_bob', 'my third manga'); -- Must fail with unique violation, revealing presence of did we can't see -SELECT * FROM document WHERE did = 8; -- and confirm we can't see it - --- RLS policies are checked before constraints -INSERT INTO document VALUES (8, 44, 1, 'regress_rls_carol', 'my third manga'); -- Should fail with RLS check violation, not duplicate key violation -UPDATE document SET did = 8, dauthor = 'regress_rls_carol' WHERE did = 5; -- Should fail with RLS check violation, not duplicate key violation - --- database superuser does bypass RLS policy when enabled -RESET SESSION AUTHORIZATION; -SET row_security TO ON; -SELECT * FROM document; -SELECT * FROM category; - --- database superuser does bypass RLS policy when disabled -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -SELECT * FROM document; -SELECT * FROM category; - --- database non-superuser with bypass privilege can bypass RLS policy when disabled -SET SESSION AUTHORIZATION regress_rls_exempt_user; -SET row_security TO OFF; -SELECT * FROM document; -SELECT * FROM category; - --- RLS policy does not apply to table owner when RLS enabled. -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security TO ON; -SELECT * FROM document; -SELECT * FROM category; - --- RLS policy does not apply to table owner when RLS disabled. -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security TO OFF; -SELECT * FROM document; -SELECT * FROM category; - --- --- Table inheritance and RLS policy --- -SET SESSION AUTHORIZATION regress_rls_alice; - -SET row_security TO ON; - -CREATE TABLE t1 (id int not null primary key, a int, junk1 text, b text); -ALTER TABLE t1 DROP COLUMN junk1; -- just a disturbing factor -GRANT ALL ON t1 TO public; - -COPY t1 FROM stdin WITH ; -101 1 aba -102 2 bbb -103 3 ccc -104 4 dad -\. - -CREATE TABLE t2 (c float) INHERITS (t1); -GRANT ALL ON t2 TO public; - -COPY t2 FROM stdin; -201 1 abc 1.1 -202 2 bcd 2.2 -203 3 cde 3.3 -204 4 def 4.4 -\. - -CREATE TABLE t3 (id int not null primary key, c text, b text, a int); -ALTER TABLE t3 INHERIT t1; -GRANT ALL ON t3 TO public; - -COPY t3(id, a,b,c) FROM stdin; -301 1 xxx X -302 2 yyy Y -303 3 zzz Z -\. - -CREATE POLICY p1 ON t1 FOR ALL TO PUBLIC USING (a % 2 = 0); -- be even number -CREATE POLICY p2 ON t2 FOR ALL TO PUBLIC USING (a % 2 = 1); -- be odd number - -ALTER TABLE t1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE t2 ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; - -SELECT * FROM t1; -EXPLAIN (COSTS OFF) SELECT * FROM t1; - -SELECT * FROM t1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); - --- reference to system column -SELECT tableoid::regclass, * FROM t1; -EXPLAIN (COSTS OFF) SELECT *, t1 FROM t1; - --- reference to whole-row reference -SELECT *, t1 FROM t1; -EXPLAIN (COSTS OFF) SELECT *, t1 FROM t1; - --- for share/update lock -SELECT * FROM t1 FOR SHARE; -EXPLAIN (COSTS OFF) SELECT * FROM t1 FOR SHARE; - -SELECT * FROM t1 WHERE f_leak(b) FOR SHARE; -EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b) FOR SHARE; - --- union all query -SELECT a, b, tableoid::regclass FROM t2 UNION ALL SELECT a, b, tableoid::regclass FROM t3; -EXPLAIN (COSTS OFF) SELECT a, b, tableoid::regclass FROM t2 UNION ALL SELECT a, b, tableoid::regclass FROM t3; - --- superuser is allowed to bypass RLS checks -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -SELECT * FROM t1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); - --- non-superuser with bypass privilege can bypass RLS policy when disabled -SET SESSION AUTHORIZATION regress_rls_exempt_user; -SET row_security TO OFF; -SELECT * FROM t1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); - --- --- Partitioned Tables --- - -SET SESSION AUTHORIZATION regress_rls_alice; - -CREATE TABLE part_document ( - did int, - cid int, - dlevel int not null, - dauthor name, - dtitle text -) PARTITION BY RANGE (cid); -GRANT ALL ON part_document TO public; - --- Create partitions for document categories -CREATE TABLE part_document_fiction PARTITION OF part_document FOR VALUES FROM (11) to (12); -CREATE TABLE part_document_satire PARTITION OF part_document FOR VALUES FROM (55) to (56); -CREATE TABLE part_document_nonfiction PARTITION OF part_document FOR VALUES FROM (99) to (100); - -GRANT ALL ON part_document_fiction TO public; -GRANT ALL ON part_document_satire TO public; -GRANT ALL ON part_document_nonfiction TO public; - -INSERT INTO part_document VALUES - ( 1, 11, 1, 'regress_rls_bob', 'my first novel'), - ( 2, 11, 2, 'regress_rls_bob', 'my second novel'), - ( 3, 99, 2, 'regress_rls_bob', 'my science textbook'), - ( 4, 55, 1, 'regress_rls_bob', 'my first satire'), - ( 5, 99, 2, 'regress_rls_bob', 'my history book'), - ( 6, 11, 1, 'regress_rls_carol', 'great science fiction'), - ( 7, 99, 2, 'regress_rls_carol', 'great technology book'), - ( 8, 55, 2, 'regress_rls_carol', 'great satire'), - ( 9, 11, 1, 'regress_rls_dave', 'awesome science fiction'), - (10, 99, 2, 'regress_rls_dave', 'awesome technology book'); - -ALTER TABLE part_document ENABLE ROW LEVEL SECURITY; - --- Create policy on parent --- user's security level must be higher than or equal to document's -CREATE POLICY pp1 ON part_document AS PERMISSIVE - USING (dlevel <= (SELECT seclv FROM uaccount WHERE pguser = current_user)); - --- Dave is only allowed to see cid < 55 -CREATE POLICY pp1r ON part_document AS RESTRICTIVE TO regress_rls_dave - USING (cid < 55); - -\d+ part_document -SELECT * FROM pg_policies WHERE schemaname = 'regress_rls_schema' AND tablename like '%part_document%' ORDER BY policyname; - --- viewpoint from regress_rls_bob -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO ON; -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; -EXPLAIN (COSTS OFF) SELECT * FROM part_document WHERE f_leak(dtitle); - --- viewpoint from regress_rls_carol -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; -EXPLAIN (COSTS OFF) SELECT * FROM part_document WHERE f_leak(dtitle); - --- viewpoint from regress_rls_dave -SET SESSION AUTHORIZATION regress_rls_dave; -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; -EXPLAIN (COSTS OFF) SELECT * FROM part_document WHERE f_leak(dtitle); - --- pp1 ERROR -INSERT INTO part_document VALUES (100, 11, 5, 'regress_rls_dave', 'testing pp1'); -- fail --- pp1r ERROR -INSERT INTO part_document VALUES (100, 99, 1, 'regress_rls_dave', 'testing pp1r'); -- fail - --- Show that RLS policy does not apply for direct inserts to children --- This should fail with RLS POLICY pp1r violation. -INSERT INTO part_document VALUES (100, 55, 1, 'regress_rls_dave', 'testing RLS with partitions'); -- fail --- But this should succeed. -INSERT INTO part_document_satire VALUES (100, 55, 1, 'regress_rls_dave', 'testing RLS with partitions'); -- success --- We still cannot see the row using the parent -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; --- But we can if we look directly -SELECT * FROM part_document_satire WHERE f_leak(dtitle) ORDER BY did; - --- Turn on RLS and create policy on child to show RLS is checked before constraints -SET SESSION AUTHORIZATION regress_rls_alice; -ALTER TABLE part_document_satire ENABLE ROW LEVEL SECURITY; -CREATE POLICY pp3 ON part_document_satire AS RESTRICTIVE - USING (cid < 55); --- This should fail with RLS violation now. -SET SESSION AUTHORIZATION regress_rls_dave; -INSERT INTO part_document_satire VALUES (101, 55, 1, 'regress_rls_dave', 'testing RLS with partitions'); -- fail --- And now we cannot see directly into the partition either, due to RLS -SELECT * FROM part_document_satire WHERE f_leak(dtitle) ORDER BY did; --- The parent looks same as before --- viewpoint from regress_rls_dave -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; -EXPLAIN (COSTS OFF) SELECT * FROM part_document WHERE f_leak(dtitle); - --- viewpoint from regress_rls_carol -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; -EXPLAIN (COSTS OFF) SELECT * FROM part_document WHERE f_leak(dtitle); - --- only owner can change policies -ALTER POLICY pp1 ON part_document USING (true); --fail -DROP POLICY pp1 ON part_document; --fail - -SET SESSION AUTHORIZATION regress_rls_alice; -ALTER POLICY pp1 ON part_document USING (dauthor = current_user); - --- viewpoint from regress_rls_bob again -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; - --- viewpoint from rls_regres_carol again -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM part_document WHERE f_leak(dtitle) ORDER BY did; - -EXPLAIN (COSTS OFF) SELECT * FROM part_document WHERE f_leak(dtitle); - --- database superuser does bypass RLS policy when enabled -RESET SESSION AUTHORIZATION; -SET row_security TO ON; -SELECT * FROM part_document ORDER BY did; -SELECT * FROM part_document_satire ORDER by did; - --- database non-superuser with bypass privilege can bypass RLS policy when disabled -SET SESSION AUTHORIZATION regress_rls_exempt_user; -SET row_security TO OFF; -SELECT * FROM part_document ORDER BY did; -SELECT * FROM part_document_satire ORDER by did; - --- RLS policy does not apply to table owner when RLS enabled. -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security TO ON; -SELECT * FROM part_document ORDER by did; -SELECT * FROM part_document_satire ORDER by did; - --- When RLS disabled, other users get ERROR. -SET SESSION AUTHORIZATION regress_rls_dave; -SET row_security TO OFF; -SELECT * FROM part_document ORDER by did; -SELECT * FROM part_document_satire ORDER by did; - --- Check behavior with a policy that uses a SubPlan not an InitPlan. -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security TO ON; -CREATE POLICY pp3 ON part_document AS RESTRICTIVE - USING ((SELECT dlevel <= seclv FROM uaccount WHERE pguser = current_user)); - -SET SESSION AUTHORIZATION regress_rls_carol; -INSERT INTO part_document VALUES (100, 11, 5, 'regress_rls_carol', 'testing pp3'); -- fail - ------ Dependencies ----- -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security TO ON; - -CREATE TABLE dependee (x integer, y integer); - -CREATE TABLE dependent (x integer, y integer); -CREATE POLICY d1 ON dependent FOR ALL - TO PUBLIC - USING (x = (SELECT d.x FROM dependee d WHERE d.y = y)); - -DROP TABLE dependee; -- Should fail without CASCADE due to dependency on row security qual? - -DROP TABLE dependee CASCADE; - -EXPLAIN (COSTS OFF) SELECT * FROM dependent; -- After drop, should be unqualified - ------ RECURSION ---- - --- --- Simple recursion --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE rec1 (x integer, y integer); -CREATE POLICY r1 ON rec1 USING (x = (SELECT r.x FROM rec1 r WHERE y = r.y)); -ALTER TABLE rec1 ENABLE ROW LEVEL SECURITY; -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rec1; -- fail, direct recursion - --- --- Mutual recursion --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE rec2 (a integer, b integer); -ALTER POLICY r1 ON rec1 USING (x = (SELECT a FROM rec2 WHERE b = y)); -CREATE POLICY r2 ON rec2 USING (a = (SELECT x FROM rec1 WHERE y = b)); -ALTER TABLE rec2 ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rec1; -- fail, mutual recursion - --- --- Mutual recursion via views --- -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE VIEW rec1v AS SELECT * FROM rec1; -CREATE VIEW rec2v AS SELECT * FROM rec2; -SET SESSION AUTHORIZATION regress_rls_alice; -ALTER POLICY r1 ON rec1 USING (x = (SELECT a FROM rec2v WHERE b = y)); -ALTER POLICY r2 ON rec2 USING (a = (SELECT x FROM rec1v WHERE y = b)); - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rec1; -- fail, mutual recursion via views - --- --- Mutual recursion via .s.b views --- -SET SESSION AUTHORIZATION regress_rls_bob; - -DROP VIEW rec1v, rec2v CASCADE; - -CREATE VIEW rec1v WITH (security_barrier) AS SELECT * FROM rec1; -CREATE VIEW rec2v WITH (security_barrier) AS SELECT * FROM rec2; -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE POLICY r1 ON rec1 USING (x = (SELECT a FROM rec2v WHERE b = y)); -CREATE POLICY r2 ON rec2 USING (a = (SELECT x FROM rec1v WHERE y = b)); - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rec1; -- fail, mutual recursion via s.b. views - --- --- recursive RLS and VIEWs in policy --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE s1 (a int, b text); -INSERT INTO s1 (SELECT x, md5(x::text) FROM generate_series(-10,10) x); - -CREATE TABLE s2 (x int, y text); -INSERT INTO s2 (SELECT x, md5(x::text) FROM generate_series(-6,6) x); - -GRANT SELECT ON s1, s2 TO regress_rls_bob; - -CREATE POLICY p1 ON s1 USING (a in (select x from s2 where y like '%2f%')); -CREATE POLICY p2 ON s2 USING (x in (select a from s1 where b like '%22%')); -CREATE POLICY p3 ON s1 FOR INSERT WITH CHECK (a = (SELECT a FROM s1)); - -ALTER TABLE s1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE s2 ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE VIEW v2 AS SELECT * FROM s2 WHERE y like '%af%'; -SELECT * FROM s1 WHERE f_leak(b); -- fail (infinite recursion) - -INSERT INTO s1 VALUES (1, 'foo'); -- fail (infinite recursion) - -SET SESSION AUTHORIZATION regress_rls_alice; -DROP POLICY p3 on s1; -ALTER POLICY p2 ON s2 USING (x % 2 = 0); - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM s1 WHERE f_leak(b); -- OK -EXPLAIN (COSTS OFF) SELECT * FROM only s1 WHERE f_leak(b); - -SET SESSION AUTHORIZATION regress_rls_alice; -ALTER POLICY p1 ON s1 USING (a in (select x from v2)); -- using VIEW in RLS policy -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM s1 WHERE f_leak(b); -- OK -EXPLAIN (COSTS OFF) SELECT * FROM s1 WHERE f_leak(b); - -SELECT (SELECT x FROM s1 LIMIT 1) xx, * FROM s2 WHERE y like '%28%'; -EXPLAIN (COSTS OFF) SELECT (SELECT x FROM s1 LIMIT 1) xx, * FROM s2 WHERE y like '%28%'; - -SET SESSION AUTHORIZATION regress_rls_alice; -ALTER POLICY p2 ON s2 USING (x in (select a from s1 where b like '%d2%')); -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM s1 WHERE f_leak(b); -- fail (infinite recursion via view) - --- prepared statement with regress_rls_alice privilege -PREPARE p1(int) AS SELECT * FROM t1 WHERE a <= $1; -EXECUTE p1(2); -EXPLAIN (COSTS OFF) EXECUTE p1(2); - --- superuser is allowed to bypass RLS checks -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -SELECT * FROM t1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM t1 WHERE f_leak(b); - --- plan cache should be invalidated -EXECUTE p1(2); -EXPLAIN (COSTS OFF) EXECUTE p1(2); - -PREPARE p2(int) AS SELECT * FROM t1 WHERE a = $1; -EXECUTE p2(2); -EXPLAIN (COSTS OFF) EXECUTE p2(2); - --- also, case when privilege switch from superuser -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO ON; -EXECUTE p2(2); -EXPLAIN (COSTS OFF) EXECUTE p2(2); - --- --- UPDATE / DELETE and Row-level security --- -SET SESSION AUTHORIZATION regress_rls_bob; -EXPLAIN (COSTS OFF) UPDATE t1 SET b = b || b WHERE f_leak(b); -UPDATE t1 SET b = b || b WHERE f_leak(b); - -EXPLAIN (COSTS OFF) UPDATE only t1 SET b = b || '_updt' WHERE f_leak(b); -UPDATE only t1 SET b = b || '_updt' WHERE f_leak(b); - --- returning clause with system column -UPDATE only t1 SET b = b WHERE f_leak(b) RETURNING tableoid::regclass, *, t1; -UPDATE t1 SET b = b WHERE f_leak(b) RETURNING *; -UPDATE t1 SET b = b WHERE f_leak(b) RETURNING tableoid::regclass, *, t1; - --- updates with from clause -EXPLAIN (COSTS OFF) UPDATE t2 SET b=t2.b FROM t3 -WHERE t2.a = 3 and t3.a = 2 AND f_leak(t2.b) AND f_leak(t3.b); - -UPDATE t2 SET b=t2.b FROM t3 -WHERE t2.a = 3 and t3.a = 2 AND f_leak(t2.b) AND f_leak(t3.b); - -EXPLAIN (COSTS OFF) UPDATE t1 SET b=t1.b FROM t2 -WHERE t1.a = 3 and t2.a = 3 AND f_leak(t1.b) AND f_leak(t2.b); - -UPDATE t1 SET b=t1.b FROM t2 -WHERE t1.a = 3 and t2.a = 3 AND f_leak(t1.b) AND f_leak(t2.b); - -EXPLAIN (COSTS OFF) UPDATE t2 SET b=t2.b FROM t1 -WHERE t1.a = 3 and t2.a = 3 AND f_leak(t1.b) AND f_leak(t2.b); - -UPDATE t2 SET b=t2.b FROM t1 -WHERE t1.a = 3 and t2.a = 3 AND f_leak(t1.b) AND f_leak(t2.b); - --- updates with from clause self join -EXPLAIN (COSTS OFF) UPDATE t2 t2_1 SET b = t2_2.b FROM t2 t2_2 -WHERE t2_1.a = 3 AND t2_2.a = t2_1.a AND t2_2.b = t2_1.b -AND f_leak(t2_1.b) AND f_leak(t2_2.b) RETURNING *, t2_1, t2_2; - -UPDATE t2 t2_1 SET b = t2_2.b FROM t2 t2_2 -WHERE t2_1.a = 3 AND t2_2.a = t2_1.a AND t2_2.b = t2_1.b -AND f_leak(t2_1.b) AND f_leak(t2_2.b) RETURNING *, t2_1, t2_2; - -EXPLAIN (COSTS OFF) UPDATE t1 t1_1 SET b = t1_2.b FROM t1 t1_2 -WHERE t1_1.a = 4 AND t1_2.a = t1_1.a AND t1_2.b = t1_1.b -AND f_leak(t1_1.b) AND f_leak(t1_2.b) RETURNING *, t1_1, t1_2; - -UPDATE t1 t1_1 SET b = t1_2.b FROM t1 t1_2 -WHERE t1_1.a = 4 AND t1_2.a = t1_1.a AND t1_2.b = t1_1.b -AND f_leak(t1_1.b) AND f_leak(t1_2.b) RETURNING *, t1_1, t1_2; - -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -SELECT * FROM t1 ORDER BY a,b; - -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO ON; -EXPLAIN (COSTS OFF) DELETE FROM only t1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) DELETE FROM t1 WHERE f_leak(b); - -DELETE FROM only t1 WHERE f_leak(b) RETURNING tableoid::regclass, *, t1; -DELETE FROM t1 WHERE f_leak(b) RETURNING tableoid::regclass, *, t1; - --- --- S.b. view on top of Row-level security --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE b1 (a int, b text); -INSERT INTO b1 (SELECT x, md5(x::text) FROM generate_series(-10,10) x); - -CREATE POLICY p1 ON b1 USING (a % 2 = 0); -ALTER TABLE b1 ENABLE ROW LEVEL SECURITY; -GRANT ALL ON b1 TO regress_rls_bob; - -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE VIEW bv1 WITH (security_barrier) AS SELECT * FROM b1 WHERE a > 0 WITH CHECK OPTION; -GRANT ALL ON bv1 TO regress_rls_carol; - -SET SESSION AUTHORIZATION regress_rls_carol; - -EXPLAIN (COSTS OFF) SELECT * FROM bv1 WHERE f_leak(b); -SELECT * FROM bv1 WHERE f_leak(b); - -INSERT INTO bv1 VALUES (-1, 'xxx'); -- should fail view WCO -INSERT INTO bv1 VALUES (11, 'xxx'); -- should fail RLS check -INSERT INTO bv1 VALUES (12, 'xxx'); -- ok - -EXPLAIN (COSTS OFF) UPDATE bv1 SET b = 'yyy' WHERE a = 4 AND f_leak(b); -UPDATE bv1 SET b = 'yyy' WHERE a = 4 AND f_leak(b); - -EXPLAIN (COSTS OFF) DELETE FROM bv1 WHERE a = 6 AND f_leak(b); -DELETE FROM bv1 WHERE a = 6 AND f_leak(b); - -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM b1; --- --- INSERT ... ON CONFLICT DO UPDATE and Row-level security --- - -SET SESSION AUTHORIZATION regress_rls_alice; -DROP POLICY p1 ON document; -DROP POLICY p1r ON document; - -CREATE POLICY p1 ON document FOR SELECT USING (true); -CREATE POLICY p2 ON document FOR INSERT WITH CHECK (dauthor = current_user); -CREATE POLICY p3 ON document FOR UPDATE - USING (cid = (SELECT cid from category WHERE cname = 'novel')) - WITH CHECK (dauthor = current_user); - -SET SESSION AUTHORIZATION regress_rls_bob; - --- Exists... -SELECT * FROM document WHERE did = 2; - --- ...so violates actual WITH CHECK OPTION within UPDATE (not INSERT, since --- alternative UPDATE path happens to be taken): -INSERT INTO document VALUES (2, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_carol', 'my first novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle, dauthor = EXCLUDED.dauthor; - --- Violates USING qual for UPDATE policy p3. --- --- UPDATE path is taken, but UPDATE fails purely because *existing* row to be --- updated is not a "novel"/cid 11 (row is not leaked, even though we have --- SELECT privileges sufficient to see the row in this instance): -INSERT INTO document VALUES (33, 22, 1, 'regress_rls_bob', 'okay science fiction'); -- preparation for next statement -INSERT INTO document VALUES (33, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'Some novel, replaces sci-fi') -- takes UPDATE path - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle; --- Fine (we UPDATE, since INSERT WCOs and UPDATE security barrier quals + WCOs --- not violated): -INSERT INTO document VALUES (2, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'my first novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle RETURNING *; --- Fine (we INSERT, so "cid = 33" ("technology") isn't evaluated): -INSERT INTO document VALUES (78, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'some technology novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle, cid = 33 RETURNING *; --- Fine (same query, but we UPDATE, so "cid = 33", ("technology") is not the --- case in respect of *existing* tuple): -INSERT INTO document VALUES (78, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'some technology novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle, cid = 33 RETURNING *; --- Same query a third time, but now fails due to existing tuple finally not --- passing quals: -INSERT INTO document VALUES (78, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'some technology novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle, cid = 33 RETURNING *; --- Don't fail just because INSERT doesn't satisfy WITH CHECK option that --- originated as a barrier/USING() qual from the UPDATE. Note that the UPDATE --- path *isn't* taken, and so UPDATE-related policy does not apply: -INSERT INTO document VALUES (79, (SELECT cid from category WHERE cname = 'technology'), 1, 'regress_rls_bob', 'technology book, can only insert') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle RETURNING *; --- But this time, the same statement fails, because the UPDATE path is taken, --- and updating the row just inserted falls afoul of security barrier qual --- (enforced as WCO) -- what we might have updated target tuple to is --- irrelevant, in fact. -INSERT INTO document VALUES (79, (SELECT cid from category WHERE cname = 'technology'), 1, 'regress_rls_bob', 'technology book, can only insert') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle RETURNING *; - --- Test default USING qual enforced as WCO -SET SESSION AUTHORIZATION regress_rls_alice; -DROP POLICY p1 ON document; -DROP POLICY p2 ON document; -DROP POLICY p3 ON document; - -CREATE POLICY p3_with_default ON document FOR UPDATE - USING (cid = (SELECT cid from category WHERE cname = 'novel')); - -SET SESSION AUTHORIZATION regress_rls_bob; --- Just because WCO-style enforcement of USING quals occurs with --- existing/target tuple does not mean that the implementation can be allowed --- to fail to also enforce this qual against the final tuple appended to --- relation (since in the absence of an explicit WCO, this is also interpreted --- as an UPDATE/ALL WCO in general). --- --- UPDATE path is taken here (fails due to existing tuple). Note that this is --- not reported as a "USING expression", because it's an RLS UPDATE check that originated as --- a USING qual for the purposes of RLS in general, as opposed to an explicit --- USING qual that is ordinarily a security barrier. We leave it up to the --- UPDATE to make this fail: -INSERT INTO document VALUES (79, (SELECT cid from category WHERE cname = 'technology'), 1, 'regress_rls_bob', 'technology book, can only insert') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle RETURNING *; - --- UPDATE path is taken here. Existing tuple passes, since its cid --- corresponds to "novel", but default USING qual is enforced against --- post-UPDATE tuple too (as always when updating with a policy that lacks an --- explicit WCO), and so this fails: -INSERT INTO document VALUES (2, (SELECT cid from category WHERE cname = 'technology'), 1, 'regress_rls_bob', 'my first novel') - ON CONFLICT (did) DO UPDATE SET cid = EXCLUDED.cid, dtitle = EXCLUDED.dtitle RETURNING *; - -SET SESSION AUTHORIZATION regress_rls_alice; -DROP POLICY p3_with_default ON document; - --- --- Test ALL policies with ON CONFLICT DO UPDATE (much the same as existing UPDATE --- tests) --- -CREATE POLICY p3_with_all ON document FOR ALL - USING (cid = (SELECT cid from category WHERE cname = 'novel')) - WITH CHECK (dauthor = current_user); - -SET SESSION AUTHORIZATION regress_rls_bob; - --- Fails, since ALL WCO is enforced in insert path: -INSERT INTO document VALUES (80, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_carol', 'my first novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle, cid = 33; --- Fails, since ALL policy USING qual is enforced (existing, target tuple is in --- violation, since it has the "manga" cid): -INSERT INTO document VALUES (4, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'my first novel') - ON CONFLICT (did) DO UPDATE SET dtitle = EXCLUDED.dtitle; --- Fails, since ALL WCO are enforced: -INSERT INTO document VALUES (1, (SELECT cid from category WHERE cname = 'novel'), 1, 'regress_rls_bob', 'my first novel') - ON CONFLICT (did) DO UPDATE SET dauthor = 'regress_rls_carol'; - --- --- MERGE --- -RESET SESSION AUTHORIZATION; -DROP POLICY p3_with_all ON document; - -ALTER TABLE document ADD COLUMN dnotes text DEFAULT ''; --- all documents are readable -CREATE POLICY p1 ON document FOR SELECT USING (true); --- one may insert documents only authored by them -CREATE POLICY p2 ON document FOR INSERT WITH CHECK (dauthor = current_user); --- one may only update documents in 'novel' category -CREATE POLICY p3 ON document FOR UPDATE - USING (cid = (SELECT cid from category WHERE cname = 'novel')) - WITH CHECK (dauthor = current_user); --- one may only delete documents in 'manga' category -CREATE POLICY p4 ON document FOR DELETE - USING (cid = (SELECT cid from category WHERE cname = 'manga')); - -SELECT * FROM document; - -SET SESSION AUTHORIZATION regress_rls_bob; - --- Fails, since update violates WITH CHECK qual on dauthor -MERGE INTO document d -USING (SELECT 1 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - UPDATE SET dnotes = dnotes || ' notes added by merge1 ', dauthor = 'regress_rls_alice'; - --- Should be OK since USING and WITH CHECK quals pass -MERGE INTO document d -USING (SELECT 1 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - UPDATE SET dnotes = dnotes || ' notes added by merge2 '; - --- Even when dauthor is updated explicitly, but to the existing value -MERGE INTO document d -USING (SELECT 1 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - UPDATE SET dnotes = dnotes || ' notes added by merge3 ', dauthor = 'regress_rls_bob'; - --- There is a MATCH for did = 3, but UPDATE's USING qual does not allow --- updating an item in category 'science fiction' -MERGE INTO document d -USING (SELECT 3 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - UPDATE SET dnotes = dnotes || ' notes added by merge '; - --- The same thing with DELETE action, but fails again because no permissions --- to delete items in 'science fiction' category that did 3 belongs to. -MERGE INTO document d -USING (SELECT 3 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - DELETE; - --- Document with did 4 belongs to 'manga' category which is allowed for --- deletion. But this fails because the UPDATE action is matched first and --- UPDATE policy does not allow updation in the category. -MERGE INTO document d -USING (SELECT 4 as sdid) s -ON did = s.sdid -WHEN MATCHED AND dnotes = '' THEN - UPDATE SET dnotes = dnotes || ' notes added by merge ' -WHEN MATCHED THEN - DELETE; - --- UPDATE action is not matched this time because of the WHEN qual. --- DELETE still fails because role regress_rls_bob does not have SELECT --- privileges on 'manga' category row in the category table. -MERGE INTO document d -USING (SELECT 4 as sdid) s -ON did = s.sdid -WHEN MATCHED AND dnotes <> '' THEN - UPDATE SET dnotes = dnotes || ' notes added by merge ' -WHEN MATCHED THEN - DELETE; - -SELECT * FROM document WHERE did = 4; - --- Switch to regress_rls_carol role and try the DELETE again. It should succeed --- this time -RESET SESSION AUTHORIZATION; -SET SESSION AUTHORIZATION regress_rls_carol; - -MERGE INTO document d -USING (SELECT 4 as sdid) s -ON did = s.sdid -WHEN MATCHED AND dnotes <> '' THEN - UPDATE SET dnotes = dnotes || ' notes added by merge ' -WHEN MATCHED THEN - DELETE; - --- Switch back to regress_rls_bob role -RESET SESSION AUTHORIZATION; -SET SESSION AUTHORIZATION regress_rls_bob; - --- Try INSERT action. This fails because we are trying to insert --- dauthor = regress_rls_dave and INSERT's WITH CHECK does not allow --- that -MERGE INTO document d -USING (SELECT 12 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - DELETE -WHEN NOT MATCHED THEN - INSERT VALUES (12, 11, 1, 'regress_rls_dave', 'another novel'); - --- This should be fine -MERGE INTO document d -USING (SELECT 12 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - DELETE -WHEN NOT MATCHED THEN - INSERT VALUES (12, 11, 1, 'regress_rls_bob', 'another novel'); - --- ok -MERGE INTO document d -USING (SELECT 1 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - UPDATE SET dnotes = dnotes || ' notes added by merge4 ' -WHEN NOT MATCHED THEN - INSERT VALUES (12, 11, 1, 'regress_rls_bob', 'another novel'); - --- drop and create a new SELECT policy which prevents us from reading --- any document except with category 'magna' -RESET SESSION AUTHORIZATION; -DROP POLICY p1 ON document; -CREATE POLICY p1 ON document FOR SELECT - USING (cid = (SELECT cid from category WHERE cname = 'manga')); - -SET SESSION AUTHORIZATION regress_rls_bob; - --- MERGE can no longer see the matching row and hence attempts the --- NOT MATCHED action, which results in unique key violation -MERGE INTO document d -USING (SELECT 1 as sdid) s -ON did = s.sdid -WHEN MATCHED THEN - UPDATE SET dnotes = dnotes || ' notes added by merge5 ' -WHEN NOT MATCHED THEN - INSERT VALUES (12, 11, 1, 'regress_rls_bob', 'another novel'); - -RESET SESSION AUTHORIZATION; --- drop the restrictive SELECT policy so that we can look at the --- final state of the table -DROP POLICY p1 ON document; --- Just check everything went per plan -SELECT * FROM document; - --- --- ROLE/GROUP --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE z1 (a int, b text); -CREATE TABLE z2 (a int, b text); - -GRANT SELECT ON z1,z2 TO regress_rls_group1, regress_rls_group2, - regress_rls_bob, regress_rls_carol; - -INSERT INTO z1 VALUES - (1, 'aba'), - (2, 'bbb'), - (3, 'ccc'), - (4, 'dad'); - -CREATE POLICY p1 ON z1 TO regress_rls_group1 USING (a % 2 = 0); -CREATE POLICY p2 ON z1 TO regress_rls_group2 USING (a % 2 = 1); - -ALTER TABLE z1 ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM z1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); - -PREPARE plancache_test AS SELECT * FROM z1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) EXECUTE plancache_test; - -PREPARE plancache_test2 AS WITH q AS MATERIALIZED (SELECT * FROM z1 WHERE f_leak(b)) SELECT * FROM q,z2; -EXPLAIN (COSTS OFF) EXECUTE plancache_test2; - -PREPARE plancache_test3 AS WITH q AS MATERIALIZED (SELECT * FROM z2) SELECT * FROM q,z1 WHERE f_leak(z1.b); -EXPLAIN (COSTS OFF) EXECUTE plancache_test3; - -SET ROLE regress_rls_group1; -SELECT * FROM z1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); - -EXPLAIN (COSTS OFF) EXECUTE plancache_test; -EXPLAIN (COSTS OFF) EXECUTE plancache_test2; -EXPLAIN (COSTS OFF) EXECUTE plancache_test3; - -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM z1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); - -EXPLAIN (COSTS OFF) EXECUTE plancache_test; -EXPLAIN (COSTS OFF) EXECUTE plancache_test2; -EXPLAIN (COSTS OFF) EXECUTE plancache_test3; - -SET ROLE regress_rls_group2; -SELECT * FROM z1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM z1 WHERE f_leak(b); - -EXPLAIN (COSTS OFF) EXECUTE plancache_test; -EXPLAIN (COSTS OFF) EXECUTE plancache_test2; -EXPLAIN (COSTS OFF) EXECUTE plancache_test3; - --- --- Views should follow policy for view owner. --- --- View and Table owner are the same. -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE VIEW rls_view AS SELECT * FROM z1 WHERE f_leak(b); -GRANT SELECT ON rls_view TO regress_rls_bob; - --- Query as role that is not owner of view or table. Should return all records. -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Query as view/table owner. Should return all records. -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; -DROP VIEW rls_view; - --- View and Table owners are different. -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE VIEW rls_view AS SELECT * FROM z1 WHERE f_leak(b); -GRANT SELECT ON rls_view TO regress_rls_alice; - --- Query as role that is not owner of view but is owner of table. --- Should return records based on view owner policies. -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Query as role that is not owner of table but is owner of view. --- Should return records based on view owner policies. -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Query as role that is not the owner of the table or view without permissions. -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; --fail - permission denied. -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. - --- Query as role that is not the owner of the table or view with permissions. -SET SESSION AUTHORIZATION regress_rls_bob; -GRANT SELECT ON rls_view TO regress_rls_carol; - -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Policy requiring access to another table. -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE z1_blacklist (a int); -INSERT INTO z1_blacklist VALUES (3), (4); -CREATE POLICY p3 ON z1 AS RESTRICTIVE USING (a NOT IN (SELECT a FROM z1_blacklist)); - --- Query as role that is not owner of table but is owner of view without permissions. -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; --fail - permission denied. -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. - --- Query as role that is not the owner of the table or view without permissions. -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; --fail - permission denied. -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. - --- Query as role that is not owner of table but is owner of view with permissions. -SET SESSION AUTHORIZATION regress_rls_alice; -GRANT SELECT ON z1_blacklist TO regress_rls_bob; - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Query as role that is not the owner of the table or view with permissions. -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - -SET SESSION AUTHORIZATION regress_rls_alice; -REVOKE SELECT ON z1_blacklist FROM regress_rls_bob; -DROP POLICY p3 ON z1; - -SET SESSION AUTHORIZATION regress_rls_bob; -DROP VIEW rls_view; - --- --- Security invoker views should follow policy for current user. --- --- View and table owner are the same. -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE VIEW rls_view WITH (security_invoker) AS - SELECT * FROM z1 WHERE f_leak(b); -GRANT SELECT ON rls_view TO regress_rls_bob; -GRANT SELECT ON rls_view TO regress_rls_carol; - --- Query as table owner. Should return all records. -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Queries as other users. --- Should return records based on current user's policies. -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- View and table owners are different. -SET SESSION AUTHORIZATION regress_rls_alice; -DROP VIEW rls_view; - -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE VIEW rls_view WITH (security_invoker) AS - SELECT * FROM z1 WHERE f_leak(b); -GRANT SELECT ON rls_view TO regress_rls_alice; -GRANT SELECT ON rls_view TO regress_rls_carol; - --- Query as table owner. Should return all records. -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Queries as other users. --- Should return records based on current user's policies. -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Policy requiring access to another table. -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE POLICY p3 ON z1 AS RESTRICTIVE USING (a NOT IN (SELECT a FROM z1_blacklist)); - --- Query as role that is not owner of table but is owner of view without permissions. -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; --fail - permission denied. -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. - --- Query as role that is not the owner of the table or view without permissions. -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; --fail - permission denied. -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. - --- Query as role that is not owner of table but is owner of view with permissions. -SET SESSION AUTHORIZATION regress_rls_alice; -GRANT SELECT ON z1_blacklist TO regress_rls_bob; - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - --- Query as role that is not the owner of the table or view without permissions. -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; --fail - permission denied. -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; --fail - permission denied. - --- Query as role that is not the owner of the table or view with permissions. -SET SESSION AUTHORIZATION regress_rls_alice; -GRANT SELECT ON z1_blacklist TO regress_rls_carol; - -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM rls_view; -EXPLAIN (COSTS OFF) SELECT * FROM rls_view; - -SET SESSION AUTHORIZATION regress_rls_bob; -DROP VIEW rls_view; - --- --- Command specific --- -SET SESSION AUTHORIZATION regress_rls_alice; - -CREATE TABLE x1 (a int, b text, c text); -GRANT ALL ON x1 TO PUBLIC; - -INSERT INTO x1 VALUES - (1, 'abc', 'regress_rls_bob'), - (2, 'bcd', 'regress_rls_bob'), - (3, 'cde', 'regress_rls_carol'), - (4, 'def', 'regress_rls_carol'), - (5, 'efg', 'regress_rls_bob'), - (6, 'fgh', 'regress_rls_bob'), - (7, 'fgh', 'regress_rls_carol'), - (8, 'fgh', 'regress_rls_carol'); - -CREATE POLICY p0 ON x1 FOR ALL USING (c = current_user); -CREATE POLICY p1 ON x1 FOR SELECT USING (a % 2 = 0); -CREATE POLICY p2 ON x1 FOR INSERT WITH CHECK (a % 2 = 1); -CREATE POLICY p3 ON x1 FOR UPDATE USING (a % 2 = 0); -CREATE POLICY p4 ON x1 FOR DELETE USING (a < 8); - -ALTER TABLE x1 ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM x1 WHERE f_leak(b) ORDER BY a ASC; -UPDATE x1 SET b = b || '_updt' WHERE f_leak(b) RETURNING *; - -SET SESSION AUTHORIZATION regress_rls_carol; -SELECT * FROM x1 WHERE f_leak(b) ORDER BY a ASC; -UPDATE x1 SET b = b || '_updt' WHERE f_leak(b) RETURNING *; -DELETE FROM x1 WHERE f_leak(b) RETURNING *; - --- --- Duplicate Policy Names --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE y1 (a int, b text); -CREATE TABLE y2 (a int, b text); - -GRANT ALL ON y1, y2 TO regress_rls_bob; - -CREATE POLICY p1 ON y1 FOR ALL USING (a % 2 = 0); -CREATE POLICY p2 ON y1 FOR SELECT USING (a > 2); -CREATE POLICY p1 ON y1 FOR SELECT USING (a % 2 = 1); --fail -CREATE POLICY p1 ON y2 FOR ALL USING (a % 2 = 0); --OK - -ALTER TABLE y1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE y2 ENABLE ROW LEVEL SECURITY; - --- --- Expression structure with SBV --- --- Create view as table owner. RLS should NOT be applied. -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE VIEW rls_sbv WITH (security_barrier) AS - SELECT * FROM y1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM rls_sbv WHERE (a = 1); -DROP VIEW rls_sbv; - --- Create view as role that does not own table. RLS should be applied. -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE VIEW rls_sbv WITH (security_barrier) AS - SELECT * FROM y1 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM rls_sbv WHERE (a = 1); -DROP VIEW rls_sbv; - --- --- Expression structure --- -SET SESSION AUTHORIZATION regress_rls_alice; -INSERT INTO y2 (SELECT x, md5(x::text) FROM generate_series(0,20) x); -CREATE POLICY p2 ON y2 USING (a % 3 = 0); -CREATE POLICY p3 ON y2 USING (a % 4 = 0); - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM y2 WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM y2 WHERE f_leak(b); - --- --- Qual push-down of leaky functions, when not referring to table --- -SELECT * FROM y2 WHERE f_leak('abc'); -EXPLAIN (COSTS OFF) SELECT * FROM y2 WHERE f_leak('abc'); - -CREATE TABLE test_qual_pushdown ( - abc text -); - -INSERT INTO test_qual_pushdown VALUES ('abc'),('def'); - -SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(abc); -EXPLAIN (COSTS OFF) SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(abc); - -SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(b); -EXPLAIN (COSTS OFF) SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(b); - -DROP TABLE test_qual_pushdown; - --- --- Plancache invalidate on user change. --- -RESET SESSION AUTHORIZATION; - -DROP TABLE t1 CASCADE; - -CREATE TABLE t1 (a integer); - -GRANT SELECT ON t1 TO regress_rls_bob, regress_rls_carol; - -CREATE POLICY p1 ON t1 TO regress_rls_bob USING ((a % 2) = 0); -CREATE POLICY p2 ON t1 TO regress_rls_carol USING ((a % 4) = 0); - -ALTER TABLE t1 ENABLE ROW LEVEL SECURITY; - --- Prepare as regress_rls_bob -SET ROLE regress_rls_bob; -PREPARE role_inval AS SELECT * FROM t1; --- Check plan -EXPLAIN (COSTS OFF) EXECUTE role_inval; - --- Change to regress_rls_carol -SET ROLE regress_rls_carol; --- Check plan- should be different -EXPLAIN (COSTS OFF) EXECUTE role_inval; - --- Change back to regress_rls_bob -SET ROLE regress_rls_bob; --- Check plan- should be back to original -EXPLAIN (COSTS OFF) EXECUTE role_inval; - --- --- CTE and RLS --- -RESET SESSION AUTHORIZATION; -DROP TABLE t1 CASCADE; -CREATE TABLE t1 (a integer, b text); -CREATE POLICY p1 ON t1 USING (a % 2 = 0); - -ALTER TABLE t1 ENABLE ROW LEVEL SECURITY; - -GRANT ALL ON t1 TO regress_rls_bob; - -INSERT INTO t1 (SELECT x, md5(x::text) FROM generate_series(0,20) x); - -SET SESSION AUTHORIZATION regress_rls_bob; - -WITH cte1 AS MATERIALIZED (SELECT * FROM t1 WHERE f_leak(b)) SELECT * FROM cte1; -EXPLAIN (COSTS OFF) -WITH cte1 AS MATERIALIZED (SELECT * FROM t1 WHERE f_leak(b)) SELECT * FROM cte1; - -WITH cte1 AS (UPDATE t1 SET a = a + 1 RETURNING *) SELECT * FROM cte1; --fail -WITH cte1 AS (UPDATE t1 SET a = a RETURNING *) SELECT * FROM cte1; --ok - -WITH cte1 AS (INSERT INTO t1 VALUES (21, 'Fail') RETURNING *) SELECT * FROM cte1; --fail -WITH cte1 AS (INSERT INTO t1 VALUES (20, 'Success') RETURNING *) SELECT * FROM cte1; --ok - --- --- Rename Policy --- -RESET SESSION AUTHORIZATION; -ALTER POLICY p1 ON t1 RENAME TO p1; --fail - -SELECT polname, relname - FROM pg_policy pol - JOIN pg_class pc ON (pc.oid = pol.polrelid) - WHERE relname = 't1'; - -ALTER POLICY p1 ON t1 RENAME TO p2; --ok - -SELECT polname, relname - FROM pg_policy pol - JOIN pg_class pc ON (pc.oid = pol.polrelid) - WHERE relname = 't1'; - --- --- Check INSERT SELECT --- -SET SESSION AUTHORIZATION regress_rls_bob; -CREATE TABLE t2 (a integer, b text); -INSERT INTO t2 (SELECT * FROM t1); -EXPLAIN (COSTS OFF) INSERT INTO t2 (SELECT * FROM t1); -SELECT * FROM t2; -EXPLAIN (COSTS OFF) SELECT * FROM t2; -CREATE TABLE t3 AS SELECT * FROM t1; -SELECT * FROM t3; -SELECT * INTO t4 FROM t1; -SELECT * FROM t4; - --- --- RLS with JOIN --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE blog (id integer, author text, post text); -CREATE TABLE comment (blog_id integer, message text); - -GRANT ALL ON blog, comment TO regress_rls_bob; - -CREATE POLICY blog_1 ON blog USING (id % 2 = 0); - -ALTER TABLE blog ENABLE ROW LEVEL SECURITY; - -INSERT INTO blog VALUES - (1, 'alice', 'blog #1'), - (2, 'bob', 'blog #1'), - (3, 'alice', 'blog #2'), - (4, 'alice', 'blog #3'), - (5, 'john', 'blog #1'); - -INSERT INTO comment VALUES - (1, 'cool blog'), - (1, 'fun blog'), - (3, 'crazy blog'), - (5, 'what?'), - (4, 'insane!'), - (2, 'who did it?'); - -SET SESSION AUTHORIZATION regress_rls_bob; --- Check RLS JOIN with Non-RLS. -SELECT id, author, message FROM blog JOIN comment ON id = blog_id; --- Check Non-RLS JOIN with RLS. -SELECT id, author, message FROM comment JOIN blog ON id = blog_id; - -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE POLICY comment_1 ON comment USING (blog_id < 4); - -ALTER TABLE comment ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; --- Check RLS JOIN RLS -SELECT id, author, message FROM blog JOIN comment ON id = blog_id; -SELECT id, author, message FROM comment JOIN blog ON id = blog_id; - -SET SESSION AUTHORIZATION regress_rls_alice; -DROP TABLE blog, comment; - --- --- Default Deny Policy --- -RESET SESSION AUTHORIZATION; -DROP POLICY p2 ON t1; -ALTER TABLE t1 OWNER TO regress_rls_alice; - --- Check that default deny does not apply to superuser. -RESET SESSION AUTHORIZATION; -SELECT * FROM t1; -EXPLAIN (COSTS OFF) SELECT * FROM t1; - --- Check that default deny does not apply to table owner. -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM t1; -EXPLAIN (COSTS OFF) SELECT * FROM t1; - --- Check that default deny applies to non-owner/non-superuser when RLS on. -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO ON; -SELECT * FROM t1; -EXPLAIN (COSTS OFF) SELECT * FROM t1; -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM t1; -EXPLAIN (COSTS OFF) SELECT * FROM t1; - --- --- COPY TO/FROM --- - -RESET SESSION AUTHORIZATION; -DROP TABLE copy_t CASCADE; -CREATE TABLE copy_t (a integer, b text); -CREATE POLICY p1 ON copy_t USING (a % 2 = 0); - -ALTER TABLE copy_t ENABLE ROW LEVEL SECURITY; - -GRANT ALL ON copy_t TO regress_rls_bob, regress_rls_exempt_user; - -INSERT INTO copy_t (SELECT x, md5(x::text) FROM generate_series(0,10) x); - --- Check COPY TO as Superuser/owner. -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; -SET row_security TO ON; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; - --- Check COPY TO as user with permissions. -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO OFF; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - would be affected by RLS -SET row_security TO ON; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok - --- Check COPY TO as user with permissions and BYPASSRLS -SET SESSION AUTHORIZATION regress_rls_exempt_user; -SET row_security TO OFF; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok -SET row_security TO ON; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --ok - --- Check COPY TO as user without permissions. SET row_security TO OFF; -SET SESSION AUTHORIZATION regress_rls_carol; -SET row_security TO OFF; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - would be affected by RLS -SET row_security TO ON; -COPY (SELECT * FROM copy_t ORDER BY a ASC) TO STDOUT WITH DELIMITER ','; --fail - permission denied - --- Check COPY relation TO; keep it just one row to avoid reordering issues -RESET SESSION AUTHORIZATION; -SET row_security TO ON; -CREATE TABLE copy_rel_to (a integer, b text); -CREATE POLICY p1 ON copy_rel_to USING (a % 2 = 0); - -ALTER TABLE copy_rel_to ENABLE ROW LEVEL SECURITY; - -GRANT ALL ON copy_rel_to TO regress_rls_bob, regress_rls_exempt_user; - -INSERT INTO copy_rel_to VALUES (1, md5('1')); - --- Check COPY TO as Superuser/owner. -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; -SET row_security TO ON; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; - --- Check COPY TO as user with permissions. -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO OFF; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; --fail - would be affected by RLS -SET row_security TO ON; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; --ok - --- Check COPY TO as user with permissions and BYPASSRLS -SET SESSION AUTHORIZATION regress_rls_exempt_user; -SET row_security TO OFF; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; --ok -SET row_security TO ON; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; --ok - --- Check COPY TO as user without permissions. SET row_security TO OFF; -SET SESSION AUTHORIZATION regress_rls_carol; -SET row_security TO OFF; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; --fail - permission denied -SET row_security TO ON; -COPY copy_rel_to TO STDOUT WITH DELIMITER ','; --fail - permission denied - --- Check COPY FROM as Superuser/owner. -RESET SESSION AUTHORIZATION; -SET row_security TO OFF; -COPY copy_t FROM STDIN; --ok -1 abc -2 bcd -3 cde -4 def -\. -SET row_security TO ON; -COPY copy_t FROM STDIN; --ok -1 abc -2 bcd -3 cde -4 def -\. - --- Check COPY FROM as user with permissions. -SET SESSION AUTHORIZATION regress_rls_bob; -SET row_security TO OFF; -COPY copy_t FROM STDIN; --fail - would be affected by RLS. -SET row_security TO ON; -COPY copy_t FROM STDIN; --fail - COPY FROM not supported by RLS. - --- Check COPY FROM as user with permissions and BYPASSRLS -SET SESSION AUTHORIZATION regress_rls_exempt_user; -SET row_security TO ON; -COPY copy_t FROM STDIN; --ok -1 abc -2 bcd -3 cde -4 def -\. - --- Check COPY FROM as user without permissions. -SET SESSION AUTHORIZATION regress_rls_carol; -SET row_security TO OFF; -COPY copy_t FROM STDIN; --fail - permission denied. -SET row_security TO ON; -COPY copy_t FROM STDIN; --fail - permission denied. - -RESET SESSION AUTHORIZATION; -DROP TABLE copy_t; -DROP TABLE copy_rel_to CASCADE; - --- Check WHERE CURRENT OF -SET SESSION AUTHORIZATION regress_rls_alice; - -CREATE TABLE current_check (currentid int, payload text, rlsuser text); -GRANT ALL ON current_check TO PUBLIC; - -INSERT INTO current_check VALUES - (1, 'abc', 'regress_rls_bob'), - (2, 'bcd', 'regress_rls_bob'), - (3, 'cde', 'regress_rls_bob'), - (4, 'def', 'regress_rls_bob'); - -CREATE POLICY p1 ON current_check FOR SELECT USING (currentid % 2 = 0); -CREATE POLICY p2 ON current_check FOR DELETE USING (currentid = 4 AND rlsuser = current_user); -CREATE POLICY p3 ON current_check FOR UPDATE USING (currentid = 4) WITH CHECK (rlsuser = current_user); - -ALTER TABLE current_check ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; - --- Can SELECT even rows -SELECT * FROM current_check; - --- Cannot UPDATE row 2 -UPDATE current_check SET payload = payload || '_new' WHERE currentid = 2 RETURNING *; - -BEGIN; - -DECLARE current_check_cursor SCROLL CURSOR FOR SELECT * FROM current_check; --- Returns rows that can be seen according to SELECT policy, like plain SELECT --- above (even rows) -FETCH ABSOLUTE 1 FROM current_check_cursor; --- Still cannot UPDATE row 2 through cursor -UPDATE current_check SET payload = payload || '_new' WHERE CURRENT OF current_check_cursor RETURNING *; --- Can update row 4 through cursor, which is the next visible row -FETCH RELATIVE 1 FROM current_check_cursor; -UPDATE current_check SET payload = payload || '_new' WHERE CURRENT OF current_check_cursor RETURNING *; -SELECT * FROM current_check; --- Plan should be a subquery TID scan -EXPLAIN (COSTS OFF) UPDATE current_check SET payload = payload WHERE CURRENT OF current_check_cursor; --- Similarly can only delete row 4 -FETCH ABSOLUTE 1 FROM current_check_cursor; -DELETE FROM current_check WHERE CURRENT OF current_check_cursor RETURNING *; -FETCH RELATIVE 1 FROM current_check_cursor; -DELETE FROM current_check WHERE CURRENT OF current_check_cursor RETURNING *; -SELECT * FROM current_check; - -COMMIT; - --- --- check pg_stats view filtering --- -SET row_security TO ON; -SET SESSION AUTHORIZATION regress_rls_alice; -ANALYZE current_check; --- Stats visible -SELECT row_security_active('current_check'); -SELECT attname, most_common_vals FROM pg_stats - WHERE tablename = 'current_check' - ORDER BY 1; - -SET SESSION AUTHORIZATION regress_rls_bob; --- Stats not visible -SELECT row_security_active('current_check'); -SELECT attname, most_common_vals FROM pg_stats - WHERE tablename = 'current_check' - ORDER BY 1; - --- --- Collation support --- -BEGIN; -CREATE TABLE coll_t (c) AS VALUES ('bar'::text); -CREATE POLICY coll_p ON coll_t USING (c < ('foo'::text COLLATE "C")); -ALTER TABLE coll_t ENABLE ROW LEVEL SECURITY; -GRANT SELECT ON coll_t TO regress_rls_alice; -SELECT (string_to_array(polqual, ':'))[7] AS inputcollid FROM pg_policy WHERE polrelid = 'coll_t'::regclass; -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM coll_t; -ROLLBACK; - --- --- Shared Object Dependencies --- -RESET SESSION AUTHORIZATION; -BEGIN; -CREATE ROLE regress_rls_eve; -CREATE ROLE regress_rls_frank; -CREATE TABLE tbl1 (c) AS VALUES ('bar'::text); -GRANT SELECT ON TABLE tbl1 TO regress_rls_eve; -CREATE POLICY P ON tbl1 TO regress_rls_eve, regress_rls_frank USING (true); -SELECT refclassid::regclass, deptype - FROM pg_depend - WHERE classid = 'pg_policy'::regclass - AND refobjid = 'tbl1'::regclass; -SELECT refclassid::regclass, deptype - FROM pg_shdepend - WHERE classid = 'pg_policy'::regclass - AND refobjid IN ('regress_rls_eve'::regrole, 'regress_rls_frank'::regrole); - -SAVEPOINT q; -DROP ROLE regress_rls_eve; --fails due to dependency on POLICY p -ROLLBACK TO q; - -ALTER POLICY p ON tbl1 TO regress_rls_frank USING (true); -SAVEPOINT q; -DROP ROLE regress_rls_eve; --fails due to dependency on GRANT SELECT -ROLLBACK TO q; - -REVOKE ALL ON TABLE tbl1 FROM regress_rls_eve; -SAVEPOINT q; -DROP ROLE regress_rls_eve; --succeeds -ROLLBACK TO q; - -SAVEPOINT q; -DROP ROLE regress_rls_frank; --fails due to dependency on POLICY p -ROLLBACK TO q; - -DROP POLICY p ON tbl1; -SAVEPOINT q; -DROP ROLE regress_rls_frank; -- succeeds -ROLLBACK TO q; - -ROLLBACK; -- cleanup - --- --- Converting table to view --- -BEGIN; -CREATE TABLE t (c int); -CREATE POLICY p ON t USING (c % 2 = 1); -ALTER TABLE t ENABLE ROW LEVEL SECURITY; - -SAVEPOINT q; -CREATE RULE "_RETURN" AS ON SELECT TO t DO INSTEAD - SELECT * FROM generate_series(1,5) t0(c); -- fails due to row-level security enabled -ROLLBACK TO q; - -ALTER TABLE t DISABLE ROW LEVEL SECURITY; -SAVEPOINT q; -CREATE RULE "_RETURN" AS ON SELECT TO t DO INSTEAD - SELECT * FROM generate_series(1,5) t0(c); -- fails due to policy p on t -ROLLBACK TO q; - -DROP POLICY p ON t; -CREATE RULE "_RETURN" AS ON SELECT TO t DO INSTEAD - SELECT * FROM generate_series(1,5) t0(c); -- succeeds -ROLLBACK; - --- --- Policy expression handling --- -BEGIN; -CREATE TABLE t (c) AS VALUES ('bar'::text); -CREATE POLICY p ON t USING (max(c)); -- fails: aggregate functions are not allowed in policy expressions -ROLLBACK; - --- --- Non-target relations are only subject to SELECT policies --- -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE r1 (a int); -CREATE TABLE r2 (a int); -INSERT INTO r1 VALUES (10), (20); -INSERT INTO r2 VALUES (10), (20); - -GRANT ALL ON r1, r2 TO regress_rls_bob; - -CREATE POLICY p1 ON r1 USING (true); -ALTER TABLE r1 ENABLE ROW LEVEL SECURITY; - -CREATE POLICY p1 ON r2 FOR SELECT USING (true); -CREATE POLICY p2 ON r2 FOR INSERT WITH CHECK (false); -CREATE POLICY p3 ON r2 FOR UPDATE USING (false); -CREATE POLICY p4 ON r2 FOR DELETE USING (false); -ALTER TABLE r2 ENABLE ROW LEVEL SECURITY; - -SET SESSION AUTHORIZATION regress_rls_bob; -SELECT * FROM r1; -SELECT * FROM r2; - --- r2 is read-only -INSERT INTO r2 VALUES (2); -- Not allowed -UPDATE r2 SET a = 2 RETURNING *; -- Updates nothing -DELETE FROM r2 RETURNING *; -- Deletes nothing - --- r2 can be used as a non-target relation in DML -INSERT INTO r1 SELECT a + 1 FROM r2 RETURNING *; -- OK -UPDATE r1 SET a = r2.a + 2 FROM r2 WHERE r1.a = r2.a RETURNING *; -- OK -DELETE FROM r1 USING r2 WHERE r1.a = r2.a + 2 RETURNING *; -- OK -SELECT * FROM r1; -SELECT * FROM r2; - -SET SESSION AUTHORIZATION regress_rls_alice; -DROP TABLE r1; -DROP TABLE r2; - --- --- FORCE ROW LEVEL SECURITY applies RLS to owners too --- -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security = on; -CREATE TABLE r1 (a int); -INSERT INTO r1 VALUES (10), (20); - -CREATE POLICY p1 ON r1 USING (false); -ALTER TABLE r1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r1 FORCE ROW LEVEL SECURITY; - --- No error, but no rows -TABLE r1; - --- RLS error -INSERT INTO r1 VALUES (1); - --- No error (unable to see any rows to update) -UPDATE r1 SET a = 1; -TABLE r1; - --- No error (unable to see any rows to delete) -DELETE FROM r1; -TABLE r1; - -SET row_security = off; --- these all fail, would be affected by RLS -TABLE r1; -UPDATE r1 SET a = 1; -DELETE FROM r1; - -DROP TABLE r1; - --- --- FORCE ROW LEVEL SECURITY does not break RI --- -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security = on; -CREATE TABLE r1 (a int PRIMARY KEY); -CREATE TABLE r2 (a int REFERENCES r1); -INSERT INTO r1 VALUES (10), (20); -INSERT INTO r2 VALUES (10), (20); - --- Create policies on r2 which prevent the --- owner from seeing any rows, but RI should --- still see them. -CREATE POLICY p1 ON r2 USING (false); -ALTER TABLE r2 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r2 FORCE ROW LEVEL SECURITY; - --- Errors due to rows in r2 -DELETE FROM r1; - --- Reset r2 to no-RLS -DROP POLICY p1 ON r2; -ALTER TABLE r2 NO FORCE ROW LEVEL SECURITY; -ALTER TABLE r2 DISABLE ROW LEVEL SECURITY; - --- clean out r2 for INSERT test below -DELETE FROM r2; - --- Change r1 to not allow rows to be seen -CREATE POLICY p1 ON r1 USING (false); -ALTER TABLE r1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r1 FORCE ROW LEVEL SECURITY; - --- No rows seen -TABLE r1; - --- No error, RI still sees that row exists in r1 -INSERT INTO r2 VALUES (10); - -DROP TABLE r2; -DROP TABLE r1; - --- Ensure cascaded DELETE works -CREATE TABLE r1 (a int PRIMARY KEY); -CREATE TABLE r2 (a int REFERENCES r1 ON DELETE CASCADE); -INSERT INTO r1 VALUES (10), (20); -INSERT INTO r2 VALUES (10), (20); - --- Create policies on r2 which prevent the --- owner from seeing any rows, but RI should --- still see them. -CREATE POLICY p1 ON r2 USING (false); -ALTER TABLE r2 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r2 FORCE ROW LEVEL SECURITY; - --- Deletes all records from both -DELETE FROM r1; - --- Remove FORCE from r2 -ALTER TABLE r2 NO FORCE ROW LEVEL SECURITY; - --- As owner, we now bypass RLS --- verify no rows in r2 now -TABLE r2; - -DROP TABLE r2; -DROP TABLE r1; - --- Ensure cascaded UPDATE works -CREATE TABLE r1 (a int PRIMARY KEY); -CREATE TABLE r2 (a int REFERENCES r1 ON UPDATE CASCADE); -INSERT INTO r1 VALUES (10), (20); -INSERT INTO r2 VALUES (10), (20); - --- Create policies on r2 which prevent the --- owner from seeing any rows, but RI should --- still see them. -CREATE POLICY p1 ON r2 USING (false); -ALTER TABLE r2 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r2 FORCE ROW LEVEL SECURITY; - --- Updates records in both -UPDATE r1 SET a = a+5; - --- Remove FORCE from r2 -ALTER TABLE r2 NO FORCE ROW LEVEL SECURITY; - --- As owner, we now bypass RLS --- verify records in r2 updated -TABLE r2; - -DROP TABLE r2; -DROP TABLE r1; - --- --- Test INSERT+RETURNING applies SELECT policies as --- WithCheckOptions (meaning an error is thrown) --- -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security = on; -CREATE TABLE r1 (a int); - -CREATE POLICY p1 ON r1 FOR SELECT USING (false); -CREATE POLICY p2 ON r1 FOR INSERT WITH CHECK (true); -ALTER TABLE r1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r1 FORCE ROW LEVEL SECURITY; - --- Works fine -INSERT INTO r1 VALUES (10), (20); - --- No error, but no rows -TABLE r1; - -SET row_security = off; --- fail, would be affected by RLS -TABLE r1; - -SET row_security = on; - --- Error -INSERT INTO r1 VALUES (10), (20) RETURNING *; - -DROP TABLE r1; - --- --- Test UPDATE+RETURNING applies SELECT policies as --- WithCheckOptions (meaning an error is thrown) --- -SET SESSION AUTHORIZATION regress_rls_alice; -SET row_security = on; -CREATE TABLE r1 (a int PRIMARY KEY); - -CREATE POLICY p1 ON r1 FOR SELECT USING (a < 20); -CREATE POLICY p2 ON r1 FOR UPDATE USING (a < 20) WITH CHECK (true); -CREATE POLICY p3 ON r1 FOR INSERT WITH CHECK (true); -INSERT INTO r1 VALUES (10); -ALTER TABLE r1 ENABLE ROW LEVEL SECURITY; -ALTER TABLE r1 FORCE ROW LEVEL SECURITY; - --- Works fine -UPDATE r1 SET a = 30; - --- Show updated rows -ALTER TABLE r1 NO FORCE ROW LEVEL SECURITY; -TABLE r1; --- reset value in r1 for test with RETURNING -UPDATE r1 SET a = 10; - --- Verify row reset -TABLE r1; - -ALTER TABLE r1 FORCE ROW LEVEL SECURITY; - --- Error -UPDATE r1 SET a = 30 RETURNING *; - --- UPDATE path of INSERT ... ON CONFLICT DO UPDATE should also error out -INSERT INTO r1 VALUES (10) - ON CONFLICT (a) DO UPDATE SET a = 30 RETURNING *; - --- Should still error out without RETURNING (use of arbiter always requires --- SELECT permissions) -INSERT INTO r1 VALUES (10) - ON CONFLICT (a) DO UPDATE SET a = 30; -INSERT INTO r1 VALUES (10) - ON CONFLICT ON CONSTRAINT r1_pkey DO UPDATE SET a = 30; - -DROP TABLE r1; - --- Check dependency handling -RESET SESSION AUTHORIZATION; -CREATE TABLE dep1 (c1 int); -CREATE TABLE dep2 (c1 int); - -CREATE POLICY dep_p1 ON dep1 TO regress_rls_bob USING (c1 > (select max(dep2.c1) from dep2)); -ALTER POLICY dep_p1 ON dep1 TO regress_rls_bob,regress_rls_carol; - --- Should return one -SELECT count(*) = 1 FROM pg_depend - WHERE objid = (SELECT oid FROM pg_policy WHERE polname = 'dep_p1') - AND refobjid = (SELECT oid FROM pg_class WHERE relname = 'dep2'); - -ALTER POLICY dep_p1 ON dep1 USING (true); - --- Should return one -SELECT count(*) = 1 FROM pg_shdepend - WHERE objid = (SELECT oid FROM pg_policy WHERE polname = 'dep_p1') - AND refobjid = (SELECT oid FROM pg_authid WHERE rolname = 'regress_rls_bob'); - --- Should return one -SELECT count(*) = 1 FROM pg_shdepend - WHERE objid = (SELECT oid FROM pg_policy WHERE polname = 'dep_p1') - AND refobjid = (SELECT oid FROM pg_authid WHERE rolname = 'regress_rls_carol'); - --- Should return zero -SELECT count(*) = 0 FROM pg_depend - WHERE objid = (SELECT oid FROM pg_policy WHERE polname = 'dep_p1') - AND refobjid = (SELECT oid FROM pg_class WHERE relname = 'dep2'); - --- DROP OWNED BY testing -RESET SESSION AUTHORIZATION; - -CREATE ROLE regress_rls_dob_role1; -CREATE ROLE regress_rls_dob_role2; - -CREATE TABLE dob_t1 (c1 int); -CREATE TABLE dob_t2 (c1 int) PARTITION BY RANGE (c1); - -CREATE POLICY p1 ON dob_t1 TO regress_rls_dob_role1 USING (true); -DROP OWNED BY regress_rls_dob_role1; -DROP POLICY p1 ON dob_t1; -- should fail, already gone - -CREATE POLICY p1 ON dob_t1 TO regress_rls_dob_role1,regress_rls_dob_role2 USING (true); -DROP OWNED BY regress_rls_dob_role1; -DROP POLICY p1 ON dob_t1; -- should succeed - --- same cases with duplicate polroles entries -CREATE POLICY p1 ON dob_t1 TO regress_rls_dob_role1,regress_rls_dob_role1 USING (true); -DROP OWNED BY regress_rls_dob_role1; -DROP POLICY p1 ON dob_t1; -- should fail, already gone - -CREATE POLICY p1 ON dob_t1 TO regress_rls_dob_role1,regress_rls_dob_role1,regress_rls_dob_role2 USING (true); -DROP OWNED BY regress_rls_dob_role1; -DROP POLICY p1 ON dob_t1; -- should succeed - --- partitioned target -CREATE POLICY p1 ON dob_t2 TO regress_rls_dob_role1,regress_rls_dob_role2 USING (true); -DROP OWNED BY regress_rls_dob_role1; -DROP POLICY p1 ON dob_t2; -- should succeed - -DROP USER regress_rls_dob_role1; -DROP USER regress_rls_dob_role2; - --- Bug #15708: view + table with RLS should check policies as view owner -CREATE TABLE ref_tbl (a int); -INSERT INTO ref_tbl VALUES (1); - -CREATE TABLE rls_tbl (a int); -INSERT INTO rls_tbl VALUES (10); -ALTER TABLE rls_tbl ENABLE ROW LEVEL SECURITY; -CREATE POLICY p1 ON rls_tbl USING (EXISTS (SELECT 1 FROM ref_tbl)); - -GRANT SELECT ON ref_tbl TO regress_rls_bob; -GRANT SELECT ON rls_tbl TO regress_rls_bob; - -CREATE VIEW rls_view AS SELECT * FROM rls_tbl; -ALTER VIEW rls_view OWNER TO regress_rls_bob; -GRANT SELECT ON rls_view TO regress_rls_alice; - -SET SESSION AUTHORIZATION regress_rls_alice; -SELECT * FROM ref_tbl; -- Permission denied -SELECT * FROM rls_tbl; -- Permission denied -SELECT * FROM rls_view; -- OK -RESET SESSION AUTHORIZATION; - -DROP VIEW rls_view; -DROP TABLE rls_tbl; -DROP TABLE ref_tbl; - --- Leaky operator test -CREATE TABLE rls_tbl (a int); -INSERT INTO rls_tbl SELECT x/10 FROM generate_series(1, 100) x; -ANALYZE rls_tbl; - -ALTER TABLE rls_tbl ENABLE ROW LEVEL SECURITY; -GRANT SELECT ON rls_tbl TO regress_rls_alice; - -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE FUNCTION op_leak(int, int) RETURNS bool - AS 'BEGIN RAISE NOTICE ''op_leak => %, %'', $1, $2; RETURN $1 < $2; END' - LANGUAGE plpgsql; -CREATE OPERATOR <<< (procedure = op_leak, leftarg = int, rightarg = int, - restrict = scalarltsel); -SELECT * FROM rls_tbl WHERE a <<< 1000; -DROP OPERATOR <<< (int, int); -DROP FUNCTION op_leak(int, int); -RESET SESSION AUTHORIZATION; -DROP TABLE rls_tbl; - --- Bug #16006: whole-row Vars in a policy don't play nice with sub-selects -SET SESSION AUTHORIZATION regress_rls_alice; -CREATE TABLE rls_tbl (a int, b int, c int); -CREATE POLICY p1 ON rls_tbl USING (rls_tbl >= ROW(1,1,1)); - -ALTER TABLE rls_tbl ENABLE ROW LEVEL SECURITY; -ALTER TABLE rls_tbl FORCE ROW LEVEL SECURITY; - -INSERT INTO rls_tbl SELECT 10, 20, 30; -EXPLAIN (VERBOSE, COSTS OFF) -INSERT INTO rls_tbl - SELECT * FROM (SELECT b, c FROM rls_tbl ORDER BY a) ss; -INSERT INTO rls_tbl - SELECT * FROM (SELECT b, c FROM rls_tbl ORDER BY a) ss; -SELECT * FROM rls_tbl; - -DROP TABLE rls_tbl; -RESET SESSION AUTHORIZATION; - --- --- Clean up objects --- -RESET SESSION AUTHORIZATION; - -DROP SCHEMA regress_rls_schema CASCADE; - -DROP USER regress_rls_alice; -DROP USER regress_rls_bob; -DROP USER regress_rls_carol; -DROP USER regress_rls_dave; -DROP USER regress_rls_exempt_user; -DROP ROLE regress_rls_group1; -DROP ROLE regress_rls_group2; - --- Arrange to have a few policies left over, for testing --- pg_dump/pg_restore -CREATE SCHEMA regress_rls_schema; -CREATE TABLE rls_tbl (c1 int); -ALTER TABLE rls_tbl ENABLE ROW LEVEL SECURITY; -CREATE POLICY p1 ON rls_tbl USING (c1 > 5); -CREATE POLICY p2 ON rls_tbl FOR SELECT USING (c1 <= 3); -CREATE POLICY p3 ON rls_tbl FOR UPDATE USING (c1 <= 3) WITH CHECK (c1 > 5); -CREATE POLICY p4 ON rls_tbl FOR DELETE USING (c1 <= 3); - -CREATE TABLE rls_tbl_force (c1 int); -ALTER TABLE rls_tbl_force ENABLE ROW LEVEL SECURITY; -ALTER TABLE rls_tbl_force FORCE ROW LEVEL SECURITY; -CREATE POLICY p1 ON rls_tbl_force USING (c1 = 5) WITH CHECK (c1 < 5); -CREATE POLICY p2 ON rls_tbl_force FOR SELECT USING (c1 = 8); -CREATE POLICY p3 ON rls_tbl_force FOR UPDATE USING (c1 = 8) WITH CHECK (c1 >= 5); -CREATE POLICY p4 ON rls_tbl_force FOR DELETE USING (c1 = 8); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frowtypes.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frowtypes.sql deleted file mode 100644 index ad5b7e128f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Frowtypes.sql +++ /dev/null @@ -1,506 +0,0 @@ --- --- ROWTYPES --- - --- Make both a standalone composite type and a table rowtype - -create type complex as (r float8, i float8); - -create temp table fullname (first text, last text); - --- Nested composite - -create type quad as (c1 complex, c2 complex); - --- Some simple tests of I/O conversions and row construction - -select (1.1,2.2)::complex, row((3.3,4.4),(5.5,null))::quad; - -select row('Joe', 'Blow')::fullname, '(Joe,Blow)'::fullname; - -select '(Joe,von Blow)'::fullname, '(Joe,d''Blow)'::fullname; - -select '(Joe,"von""Blow")'::fullname, E'(Joe,d\\\\Blow)'::fullname; - -select '(Joe,"Blow,Jr")'::fullname; - -select '(Joe,)'::fullname; -- ok, null 2nd column -select '(Joe)'::fullname; -- bad -select '(Joe,,)'::fullname; -- bad -select '[]'::fullname; -- bad -select ' (Joe,Blow) '::fullname; -- ok, extra whitespace -select '(Joe,Blow) /'::fullname; -- bad - -create temp table quadtable(f1 int, q quad); - -insert into quadtable values (1, ((3.3,4.4),(5.5,6.6))); -insert into quadtable values (2, ((null,4.4),(5.5,6.6))); - -select * from quadtable; - -select f1, q.c1 from quadtable; -- fails, q is a table reference - -select f1, (q).c1, (qq.q).c1.i from quadtable qq; - -create temp table people (fn fullname, bd date); - -insert into people values ('(Joe,Blow)', '1984-01-10'); - -select * from people; - --- at the moment this will not work due to ALTER TABLE inadequacy: -alter table fullname add column suffix text default ''; - --- but this should work: -alter table fullname add column suffix text default null; - -select * from people; - --- test insertion/updating of subfields -update people set fn.suffix = 'Jr'; - -select * from people; - -insert into quadtable (f1, q.c1.r, q.c2.i) values(44,55,66); - -update quadtable set q.c1.r = 12 where f1 = 2; - -update quadtable set q.c1 = 12; -- error, type mismatch - -select * from quadtable; - --- The object here is to ensure that toasted references inside --- composite values don't cause problems. The large f1 value will --- be toasted inside pp, it must still work after being copied to people. - -create temp table pp (f1 text); -insert into pp values (repeat('abcdefghijkl', 100000)); - -insert into people select ('Jim', f1, null)::fullname, current_date from pp; - -select (fn).first, substr((fn).last, 1, 20), length((fn).last) from people; - --- Test row comparison semantics. Prior to PG 8.2 we did this in a totally --- non-spec-compliant way. - -select ROW(1,2) < ROW(1,3) as true; -select ROW(1,2) < ROW(1,1) as false; -select ROW(1,2) < ROW(1,NULL) as null; -select ROW(1,2,3) < ROW(1,3,NULL) as true; -- the NULL is not examined -select ROW(11,'ABC') < ROW(11,'DEF') as true; -select ROW(11,'ABC') > ROW(11,'DEF') as false; -select ROW(12,'ABC') > ROW(11,'DEF') as true; - --- = and <> have different NULL-behavior than < etc -select ROW(1,2,3) < ROW(1,NULL,4) as null; -select ROW(1,2,3) = ROW(1,NULL,4) as false; -select ROW(1,2,3) <> ROW(1,NULL,4) as true; - --- We allow operators beyond the six standard ones, if they have btree --- operator classes. -select ROW('ABC','DEF') ~<=~ ROW('DEF','ABC') as true; -select ROW('ABC','DEF') ~>=~ ROW('DEF','ABC') as false; -select ROW('ABC','DEF') ~~ ROW('DEF','ABC') as fail; - --- Comparisons of ROW() expressions can cope with some type mismatches -select ROW(1,2) = ROW(1,2::int8); -select ROW(1,2) in (ROW(3,4), ROW(1,2)); -select ROW(1,2) in (ROW(3,4), ROW(1,2::int8)); - --- Check row comparison with a subselect -select unique1, unique2 from tenk1 -where (unique1, unique2) < any (select ten, ten from tenk1 where hundred < 3) - and unique1 <= 20 -order by 1; - --- Also check row comparison with an indexable condition -explain (costs off) -select thousand, tenthous from tenk1 -where (thousand, tenthous) >= (997, 5000) -order by thousand, tenthous; - -select thousand, tenthous from tenk1 -where (thousand, tenthous) >= (997, 5000) -order by thousand, tenthous; - -explain (costs off) -select thousand, tenthous, four from tenk1 -where (thousand, tenthous, four) > (998, 5000, 3) -order by thousand, tenthous; - -select thousand, tenthous, four from tenk1 -where (thousand, tenthous, four) > (998, 5000, 3) -order by thousand, tenthous; - -explain (costs off) -select thousand, tenthous from tenk1 -where (998, 5000) < (thousand, tenthous) -order by thousand, tenthous; - -select thousand, tenthous from tenk1 -where (998, 5000) < (thousand, tenthous) -order by thousand, tenthous; - -explain (costs off) -select thousand, hundred from tenk1 -where (998, 5000) < (thousand, hundred) -order by thousand, hundred; - -select thousand, hundred from tenk1 -where (998, 5000) < (thousand, hundred) -order by thousand, hundred; - --- Test case for bug #14010: indexed row comparisons fail with nulls -create temp table test_table (a text, b text); -insert into test_table values ('a', 'b'); -insert into test_table select 'a', null from generate_series(1,1000); -insert into test_table values ('b', 'a'); -create index on test_table (a,b); -set enable_sort = off; - -explain (costs off) -select a,b from test_table where (a,b) > ('a','a') order by a,b; - -select a,b from test_table where (a,b) > ('a','a') order by a,b; - -reset enable_sort; - --- Check row comparisons with IN -select * from int8_tbl i8 where i8 in (row(123,456)); -- fail, type mismatch - -explain (costs off) -select * from int8_tbl i8 -where i8 in (row(123,456)::int8_tbl, '(4567890123456789,123)'); - -select * from int8_tbl i8 -where i8 in (row(123,456)::int8_tbl, '(4567890123456789,123)'); - --- Check ability to select columns from an anonymous rowtype -select (row(1, 2.0)).f1; -select (row(1, 2.0)).f2; -select (row(1, 2.0)).nosuch; -- fail -select (row(1, 2.0)).*; -select (r).f1 from (select row(1, 2.0) as r) ss; -select (r).f3 from (select row(1, 2.0) as r) ss; -- fail -select (r).* from (select row(1, 2.0) as r) ss; - --- Check some corner cases involving empty rowtypes -select ROW(); -select ROW() IS NULL; -select ROW() = ROW(); - --- Check ability to create arrays of anonymous rowtypes -select array[ row(1,2), row(3,4), row(5,6) ]; - --- Check ability to compare an anonymous row to elements of an array -select row(1,1.1) = any (array[ row(7,7.7), row(1,1.1), row(0,0.0) ]); -select row(1,1.1) = any (array[ row(7,7.7), row(1,1.0), row(0,0.0) ]); - --- Check behavior with a non-comparable rowtype -create type cantcompare as (p point, r float8); -create temp table cc (f1 cantcompare); -insert into cc values('("(1,2)",3)'); -insert into cc values('("(4,5)",6)'); -select * from cc order by f1; -- fail, but should complain about cantcompare - --- --- Tests for record_{eq,cmp} --- - -create type testtype1 as (a int, b int); - --- all true -select row(1, 2)::testtype1 < row(1, 3)::testtype1; -select row(1, 2)::testtype1 <= row(1, 3)::testtype1; -select row(1, 2)::testtype1 = row(1, 2)::testtype1; -select row(1, 2)::testtype1 <> row(1, 3)::testtype1; -select row(1, 3)::testtype1 >= row(1, 2)::testtype1; -select row(1, 3)::testtype1 > row(1, 2)::testtype1; - --- all false -select row(1, -2)::testtype1 < row(1, -3)::testtype1; -select row(1, -2)::testtype1 <= row(1, -3)::testtype1; -select row(1, -2)::testtype1 = row(1, -3)::testtype1; -select row(1, -2)::testtype1 <> row(1, -2)::testtype1; -select row(1, -3)::testtype1 >= row(1, -2)::testtype1; -select row(1, -3)::testtype1 > row(1, -2)::testtype1; - --- true, but see *< below -select row(1, -2)::testtype1 < row(1, 3)::testtype1; - --- mismatches -create type testtype3 as (a int, b text); -select row(1, 2)::testtype1 < row(1, 'abc')::testtype3; -select row(1, 2)::testtype1 <> row(1, 'abc')::testtype3; -create type testtype5 as (a int); -select row(1, 2)::testtype1 < row(1)::testtype5; -select row(1, 2)::testtype1 <> row(1)::testtype5; - --- non-comparable types -create type testtype6 as (a int, b point); -select row(1, '(1,2)')::testtype6 < row(1, '(1,3)')::testtype6; -select row(1, '(1,2)')::testtype6 <> row(1, '(1,3)')::testtype6; - -drop type testtype1, testtype3, testtype5, testtype6; - --- --- Tests for record_image_{eq,cmp} --- - -create type testtype1 as (a int, b int); - --- all true -select row(1, 2)::testtype1 *< row(1, 3)::testtype1; -select row(1, 2)::testtype1 *<= row(1, 3)::testtype1; -select row(1, 2)::testtype1 *= row(1, 2)::testtype1; -select row(1, 2)::testtype1 *<> row(1, 3)::testtype1; -select row(1, 3)::testtype1 *>= row(1, 2)::testtype1; -select row(1, 3)::testtype1 *> row(1, 2)::testtype1; - --- all false -select row(1, -2)::testtype1 *< row(1, -3)::testtype1; -select row(1, -2)::testtype1 *<= row(1, -3)::testtype1; -select row(1, -2)::testtype1 *= row(1, -3)::testtype1; -select row(1, -2)::testtype1 *<> row(1, -2)::testtype1; -select row(1, -3)::testtype1 *>= row(1, -2)::testtype1; -select row(1, -3)::testtype1 *> row(1, -2)::testtype1; - --- This returns the "wrong" order because record_image_cmp works on --- unsigned datums without knowing about the actual data type. -select row(1, -2)::testtype1 *< row(1, 3)::testtype1; - --- other types -create type testtype2 as (a smallint, b bool); -- byval different sizes -select row(1, true)::testtype2 *< row(2, true)::testtype2; -select row(-2, true)::testtype2 *< row(-1, true)::testtype2; -select row(0, false)::testtype2 *< row(0, true)::testtype2; -select row(0, false)::testtype2 *<> row(0, true)::testtype2; - -create type testtype3 as (a int, b text); -- variable length -select row(1, 'abc')::testtype3 *< row(1, 'abd')::testtype3; -select row(1, 'abc')::testtype3 *< row(1, 'abcd')::testtype3; -select row(1, 'abc')::testtype3 *> row(1, 'abd')::testtype3; -select row(1, 'abc')::testtype3 *<> row(1, 'abd')::testtype3; - -create type testtype4 as (a int, b point); -- by ref, fixed length -select row(1, '(1,2)')::testtype4 *< row(1, '(1,3)')::testtype4; -select row(1, '(1,2)')::testtype4 *<> row(1, '(1,3)')::testtype4; - --- mismatches -select row(1, 2)::testtype1 *< row(1, 'abc')::testtype3; -select row(1, 2)::testtype1 *<> row(1, 'abc')::testtype3; -create type testtype5 as (a int); -select row(1, 2)::testtype1 *< row(1)::testtype5; -select row(1, 2)::testtype1 *<> row(1)::testtype5; - --- non-comparable types -create type testtype6 as (a int, b point); -select row(1, '(1,2)')::testtype6 *< row(1, '(1,3)')::testtype6; -select row(1, '(1,2)')::testtype6 *>= row(1, '(1,3)')::testtype6; -select row(1, '(1,2)')::testtype6 *<> row(1, '(1,3)')::testtype6; - --- anonymous rowtypes in coldeflists -select q.a, q.b = row(2), q.c = array[row(3)], q.d = row(row(4)) from - unnest(array[row(1, row(2), array[row(3)], row(row(4))), - row(2, row(3), array[row(4)], row(row(5)))]) - as q(a int, b record, c record[], d record); - -drop type testtype1, testtype2, testtype3, testtype4, testtype5, testtype6; - - --- --- Test case derived from bug #5716: check multiple uses of a rowtype result --- - -BEGIN; - -CREATE TABLE price ( - id SERIAL PRIMARY KEY, - active BOOLEAN NOT NULL, - price NUMERIC -); - -CREATE TYPE price_input AS ( - id INTEGER, - price NUMERIC -); - -CREATE TYPE price_key AS ( - id INTEGER -); - -CREATE FUNCTION price_key_from_table(price) RETURNS price_key AS $$ - SELECT $1.id -$$ LANGUAGE SQL; - -CREATE FUNCTION price_key_from_input(price_input) RETURNS price_key AS $$ - SELECT $1.id -$$ LANGUAGE SQL; - -insert into price values (1,false,42), (10,false,100), (11,true,17.99); - -UPDATE price - SET active = true, price = input_prices.price - FROM unnest(ARRAY[(10, 123.00), (11, 99.99)]::price_input[]) input_prices - WHERE price_key_from_table(price.*) = price_key_from_input(input_prices.*); - -select * from price; - -rollback; - --- --- Test case derived from bug #9085: check * qualification of composite --- parameters for SQL functions --- - -create temp table compos (f1 int, f2 text); - -create function fcompos1(v compos) returns void as $$ -insert into compos values (v); -- fail -$$ language sql; - -create function fcompos1(v compos) returns void as $$ -insert into compos values (v.*); -$$ language sql; - -create function fcompos2(v compos) returns void as $$ -select fcompos1(v); -$$ language sql; - -create function fcompos3(v compos) returns void as $$ -select fcompos1(fcompos3.v.*); -$$ language sql; - -select fcompos1(row(1,'one')); -select fcompos2(row(2,'two')); -select fcompos3(row(3,'three')); -select * from compos; - --- --- We allow I/O conversion casts from composite types to strings to be --- invoked via cast syntax, but not functional syntax. This is because --- the latter is too prone to be invoked unintentionally. --- -select cast (fullname as text) from fullname; -select fullname::text from fullname; -select text(fullname) from fullname; -- error -select fullname.text from fullname; -- error --- same, but RECORD instead of named composite type: -select cast (row('Jim', 'Beam') as text); -select (row('Jim', 'Beam'))::text; -select text(row('Jim', 'Beam')); -- error -select (row('Jim', 'Beam')).text; -- error - --- --- Check the equivalence of functional and column notation --- -insert into fullname values ('Joe', 'Blow'); - -select f.last from fullname f; -select last(f) from fullname f; - -create function longname(fullname) returns text language sql -as $$select $1.first || ' ' || $1.last$$; - -select f.longname from fullname f; -select longname(f) from fullname f; - --- Starting in v11, the notational form does matter if there's ambiguity -alter table fullname add column longname text; - -select f.longname from fullname f; -select longname(f) from fullname f; - --- --- Test that composite values are seen to have the correct column names --- (bug #11210 and other reports) --- - -select row_to_json(i) from int8_tbl i; --- since "i" is of type "int8_tbl", attaching aliases doesn't change anything: -select row_to_json(i) from int8_tbl i(x,y); - --- in these examples, we'll report the exposed column names of the subselect: -select row_to_json(ss) from - (select q1, q2 from int8_tbl) as ss; -select row_to_json(ss) from - (select q1, q2 from int8_tbl offset 0) as ss; -select row_to_json(ss) from - (select q1 as a, q2 as b from int8_tbl) as ss; -select row_to_json(ss) from - (select q1 as a, q2 as b from int8_tbl offset 0) as ss; -select row_to_json(ss) from - (select q1 as a, q2 as b from int8_tbl) as ss(x,y); -select row_to_json(ss) from - (select q1 as a, q2 as b from int8_tbl offset 0) as ss(x,y); - -explain (costs off) -select row_to_json(q) from - (select thousand, tenthous from tenk1 - where thousand = 42 and tenthous < 2000 offset 0) q; -select row_to_json(q) from - (select thousand, tenthous from tenk1 - where thousand = 42 and tenthous < 2000 offset 0) q; -select row_to_json(q) from - (select thousand as x, tenthous as y from tenk1 - where thousand = 42 and tenthous < 2000 offset 0) q; -select row_to_json(q) from - (select thousand as x, tenthous as y from tenk1 - where thousand = 42 and tenthous < 2000 offset 0) q(a,b); - -create temp table tt1 as select * from int8_tbl limit 2; -create temp table tt2 () inherits(tt1); -insert into tt2 values(0,0); -select row_to_json(r) from (select q2,q1 from tt1 offset 0) r; - --- check no-op rowtype conversions -create temp table tt3 () inherits(tt2); -insert into tt3 values(33,44); -select row_to_json(tt3::tt2::tt1) from tt3; - --- --- IS [NOT] NULL should not recurse into nested composites (bug #14235) --- - -explain (verbose, costs off) -select r, r is null as isnull, r is not null as isnotnull -from (values (1,row(1,2)), (1,row(null,null)), (1,null), - (null,row(1,2)), (null,row(null,null)), (null,null) ) r(a,b); - -select r, r is null as isnull, r is not null as isnotnull -from (values (1,row(1,2)), (1,row(null,null)), (1,null), - (null,row(1,2)), (null,row(null,null)), (null,null) ) r(a,b); - -explain (verbose, costs off) -with r(a,b) as materialized - (values (1,row(1,2)), (1,row(null,null)), (1,null), - (null,row(1,2)), (null,row(null,null)), (null,null) ) -select r, r is null as isnull, r is not null as isnotnull from r; - -with r(a,b) as materialized - (values (1,row(1,2)), (1,row(null,null)), (1,null), - (null,row(1,2)), (null,row(null,null)), (null,null) ) -select r, r is null as isnull, r is not null as isnotnull from r; - - --- --- Tests for component access / FieldSelect --- -CREATE TABLE compositetable(a text, b text); -INSERT INTO compositetable(a, b) VALUES('fa', 'fb'); - --- composite type columns can't directly be accessed (error) -SELECT d.a FROM (SELECT compositetable AS d FROM compositetable) s; --- but can be accessed with proper parens -SELECT (d).a, (d).b FROM (SELECT compositetable AS d FROM compositetable) s; --- system columns can't be accessed in composite types (error) -SELECT (d).ctid FROM (SELECT compositetable AS d FROM compositetable) s; - --- accessing non-existing column in NULL datum errors out -SELECT (NULL::compositetable).nonexistent; --- existing column in a NULL composite yield NULL -SELECT (NULL::compositetable).a; --- oids can't be accessed in composite types (error) -SELECT (NULL::compositetable).oid; - -DROP TABLE compositetable; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsecurity_label.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsecurity_label.sql deleted file mode 100644 index 98e6a5f211..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsecurity_label.sql +++ /dev/null @@ -1,45 +0,0 @@ --- --- Test for facilities of security label --- - --- initial setups -SET client_min_messages TO 'warning'; - -DROP ROLE IF EXISTS regress_seclabel_user1; -DROP ROLE IF EXISTS regress_seclabel_user2; - -RESET client_min_messages; - -CREATE USER regress_seclabel_user1 WITH CREATEROLE; -CREATE USER regress_seclabel_user2; - -CREATE TABLE seclabel_tbl1 (a int, b text); -CREATE TABLE seclabel_tbl2 (x int, y text); -CREATE VIEW seclabel_view1 AS SELECT * FROM seclabel_tbl2; -CREATE FUNCTION seclabel_four() RETURNS integer AS $$SELECT 4$$ language sql; -CREATE DOMAIN seclabel_domain AS text; - -ALTER TABLE seclabel_tbl1 OWNER TO regress_seclabel_user1; -ALTER TABLE seclabel_tbl2 OWNER TO regress_seclabel_user2; - --- --- Test of SECURITY LABEL statement without a plugin --- -SECURITY LABEL ON TABLE seclabel_tbl1 IS 'classified'; -- fail -SECURITY LABEL FOR 'dummy' ON TABLE seclabel_tbl1 IS 'classified'; -- fail -SECURITY LABEL ON TABLE seclabel_tbl1 IS '...invalid label...'; -- fail -SECURITY LABEL ON TABLE seclabel_tbl3 IS 'unclassified'; -- fail - -SECURITY LABEL ON ROLE regress_seclabel_user1 IS 'classified'; -- fail -SECURITY LABEL FOR 'dummy' ON ROLE regress_seclabel_user1 IS 'classified'; -- fail -SECURITY LABEL ON ROLE regress_seclabel_user1 IS '...invalid label...'; -- fail -SECURITY LABEL ON ROLE regress_seclabel_user3 IS 'unclassified'; -- fail - --- clean up objects -DROP FUNCTION seclabel_four(); -DROP DOMAIN seclabel_domain; -DROP VIEW seclabel_view1; -DROP TABLE seclabel_tbl1; -DROP TABLE seclabel_tbl2; -DROP USER regress_seclabel_user1; -DROP USER regress_seclabel_user2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_distinct.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_distinct.sql deleted file mode 100644 index f27ff714f8..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_distinct.sql +++ /dev/null @@ -1,176 +0,0 @@ --- --- SELECT_DISTINCT --- - --- --- awk '{print $3;}' onek.data | sort -n | uniq --- -SELECT DISTINCT two FROM onek ORDER BY 1; - --- --- awk '{print $5;}' onek.data | sort -n | uniq --- -SELECT DISTINCT ten FROM onek ORDER BY 1; - --- --- awk '{print $16;}' onek.data | sort -d | uniq --- -SELECT DISTINCT string4 FROM onek ORDER BY 1; - --- --- awk '{print $3,$16,$5;}' onek.data | sort -d | uniq | --- sort +0n -1 +1d -2 +2n -3 --- -SELECT DISTINCT two, string4, ten - FROM onek - ORDER BY two using <, string4 using <, ten using <; - --- --- awk '{print $2;}' person.data | --- awk '{if(NF!=1){print $2;}else{print;}}' - emp.data | --- awk '{if(NF!=1){print $2;}else{print;}}' - student.data | --- awk 'BEGIN{FS=" ";}{if(NF!=1){print $5;}else{print;}}' - stud_emp.data | --- sort -n -r | uniq --- -SELECT DISTINCT p.age FROM person* p ORDER BY age using >; - --- --- Check mentioning same column more than once --- - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT count(*) FROM - (SELECT DISTINCT two, four, two FROM tenk1) ss; - -SELECT count(*) FROM - (SELECT DISTINCT two, four, two FROM tenk1) ss; - --- --- Compare results between plans using sorting and plans using hash --- aggregation. Force spilling in both cases by setting work_mem low. --- - -SET work_mem='64kB'; - --- Produce results with sorting. - -SET enable_hashagg=FALSE; - -SET jit_above_cost=0; - -EXPLAIN (costs off) -SELECT DISTINCT g%1000 FROM generate_series(0,9999) g; - -CREATE TABLE distinct_group_1 AS -SELECT DISTINCT g%1000 FROM generate_series(0,9999) g; - -SET jit_above_cost TO DEFAULT; - -CREATE TABLE distinct_group_2 AS -SELECT DISTINCT (g%1000)::text FROM generate_series(0,9999) g; - -SET enable_hashagg=TRUE; - --- Produce results with hash aggregation. - -SET enable_sort=FALSE; - -SET jit_above_cost=0; - -EXPLAIN (costs off) -SELECT DISTINCT g%1000 FROM generate_series(0,9999) g; - -CREATE TABLE distinct_hash_1 AS -SELECT DISTINCT g%1000 FROM generate_series(0,9999) g; - -SET jit_above_cost TO DEFAULT; - -CREATE TABLE distinct_hash_2 AS -SELECT DISTINCT (g%1000)::text FROM generate_series(0,9999) g; - -SET enable_sort=TRUE; - -SET work_mem TO DEFAULT; - --- Compare results - -(SELECT * FROM distinct_hash_1 EXCEPT SELECT * FROM distinct_group_1) - UNION ALL -(SELECT * FROM distinct_group_1 EXCEPT SELECT * FROM distinct_hash_1); - -(SELECT * FROM distinct_hash_1 EXCEPT SELECT * FROM distinct_group_1) - UNION ALL -(SELECT * FROM distinct_group_1 EXCEPT SELECT * FROM distinct_hash_1); - -DROP TABLE distinct_hash_1; -DROP TABLE distinct_hash_2; -DROP TABLE distinct_group_1; -DROP TABLE distinct_group_2; - --- Test parallel DISTINCT -SET parallel_tuple_cost=0; -SET parallel_setup_cost=0; -SET min_parallel_table_scan_size=0; -SET max_parallel_workers_per_gather=2; - --- Ensure we get a parallel plan -EXPLAIN (costs off) -SELECT DISTINCT four FROM tenk1; - --- Ensure the parallel plan produces the correct results -SELECT DISTINCT four FROM tenk1; - -CREATE OR REPLACE FUNCTION distinct_func(a INT) RETURNS INT AS $$ - BEGIN - RETURN a; - END; -$$ LANGUAGE plpgsql PARALLEL UNSAFE; - --- Ensure we don't do parallel distinct with a parallel unsafe function -EXPLAIN (COSTS OFF) -SELECT DISTINCT distinct_func(1) FROM tenk1; - --- make the function parallel safe -CREATE OR REPLACE FUNCTION distinct_func(a INT) RETURNS INT AS $$ - BEGIN - RETURN a; - END; -$$ LANGUAGE plpgsql PARALLEL SAFE; - --- Ensure we do parallel distinct now that the function is parallel safe -EXPLAIN (COSTS OFF) -SELECT DISTINCT distinct_func(1) FROM tenk1; - -RESET max_parallel_workers_per_gather; -RESET min_parallel_table_scan_size; -RESET parallel_setup_cost; -RESET parallel_tuple_cost; - --- --- Also, some tests of IS DISTINCT FROM, which doesn't quite deserve its --- very own regression file. --- - -CREATE TEMP TABLE disttable (f1 integer); -INSERT INTO DISTTABLE VALUES(1); -INSERT INTO DISTTABLE VALUES(2); -INSERT INTO DISTTABLE VALUES(3); -INSERT INTO DISTTABLE VALUES(NULL); - --- basic cases -SELECT f1, f1 IS DISTINCT FROM 2 as "not 2" FROM disttable; -SELECT f1, f1 IS DISTINCT FROM NULL as "not null" FROM disttable; -SELECT f1, f1 IS DISTINCT FROM f1 as "false" FROM disttable; -SELECT f1, f1 IS DISTINCT FROM f1+1 as "not null" FROM disttable; - --- check that optimizer constant-folds it properly -SELECT 1 IS DISTINCT FROM 2 as "yes"; -SELECT 2 IS DISTINCT FROM 2 as "no"; -SELECT 2 IS DISTINCT FROM null as "yes"; -SELECT null IS DISTINCT FROM null as "no"; - --- negated form -SELECT 1 IS NOT DISTINCT FROM 2 as "no"; -SELECT 2 IS NOT DISTINCT FROM 2 as "yes"; -SELECT 2 IS NOT DISTINCT FROM null as "no"; -SELECT null IS NOT DISTINCT FROM null as "yes"; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_into.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_into.sql deleted file mode 100644 index 689c448cc2..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_into.sql +++ /dev/null @@ -1,138 +0,0 @@ --- --- SELECT_INTO --- - -SELECT * - INTO TABLE sitmp1 - FROM onek - WHERE onek.unique1 < 2; - -DROP TABLE sitmp1; - -SELECT * - INTO TABLE sitmp1 - FROM onek2 - WHERE onek2.unique1 < 2; - -DROP TABLE sitmp1; - --- --- SELECT INTO and INSERT permission, if owner is not allowed to insert. --- -CREATE SCHEMA selinto_schema; -CREATE USER regress_selinto_user; -ALTER DEFAULT PRIVILEGES FOR ROLE regress_selinto_user - REVOKE INSERT ON TABLES FROM regress_selinto_user; -GRANT ALL ON SCHEMA selinto_schema TO public; - -SET SESSION AUTHORIZATION regress_selinto_user; --- WITH DATA, passes. -CREATE TABLE selinto_schema.tbl_withdata1 (a) - AS SELECT generate_series(1,3) WITH DATA; -INSERT INTO selinto_schema.tbl_withdata1 VALUES (4); -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE selinto_schema.tbl_withdata2 (a) AS - SELECT generate_series(1,3) WITH DATA; --- WITH NO DATA, passes. -CREATE TABLE selinto_schema.tbl_nodata1 (a) AS - SELECT generate_series(1,3) WITH NO DATA; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE selinto_schema.tbl_nodata2 (a) AS - SELECT generate_series(1,3) WITH NO DATA; --- EXECUTE and WITH DATA, passes. -PREPARE data_sel AS SELECT generate_series(1,3); -CREATE TABLE selinto_schema.tbl_withdata3 (a) AS - EXECUTE data_sel WITH DATA; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE selinto_schema.tbl_withdata4 (a) AS - EXECUTE data_sel WITH DATA; --- EXECUTE and WITH NO DATA, passes. -CREATE TABLE selinto_schema.tbl_nodata3 (a) AS - EXECUTE data_sel WITH NO DATA; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE selinto_schema.tbl_nodata4 (a) AS - EXECUTE data_sel WITH NO DATA; -RESET SESSION AUTHORIZATION; - -ALTER DEFAULT PRIVILEGES FOR ROLE regress_selinto_user - GRANT INSERT ON TABLES TO regress_selinto_user; - -SET SESSION AUTHORIZATION regress_selinto_user; -RESET SESSION AUTHORIZATION; - -DEALLOCATE data_sel; -DROP SCHEMA selinto_schema CASCADE; -DROP USER regress_selinto_user; - --- Tests for WITH NO DATA and column name consistency -CREATE TABLE ctas_base (i int, j int); -INSERT INTO ctas_base VALUES (1, 2); -CREATE TABLE ctas_nodata (ii, jj, kk) AS SELECT i, j FROM ctas_base; -- Error -CREATE TABLE ctas_nodata (ii, jj, kk) AS SELECT i, j FROM ctas_base WITH NO DATA; -- Error -CREATE TABLE ctas_nodata (ii, jj) AS SELECT i, j FROM ctas_base; -- OK -CREATE TABLE ctas_nodata_2 (ii, jj) AS SELECT i, j FROM ctas_base WITH NO DATA; -- OK -CREATE TABLE ctas_nodata_3 (ii) AS SELECT i, j FROM ctas_base; -- OK -CREATE TABLE ctas_nodata_4 (ii) AS SELECT i, j FROM ctas_base WITH NO DATA; -- OK -SELECT * FROM ctas_nodata; -SELECT * FROM ctas_nodata_2; -SELECT * FROM ctas_nodata_3; -SELECT * FROM ctas_nodata_4; -DROP TABLE ctas_base; -DROP TABLE ctas_nodata; -DROP TABLE ctas_nodata_2; -DROP TABLE ctas_nodata_3; -DROP TABLE ctas_nodata_4; - --- --- CREATE TABLE AS/SELECT INTO as last command in a SQL function --- have been known to cause problems --- -CREATE FUNCTION make_table() RETURNS VOID -AS $$ - CREATE TABLE created_table AS SELECT * FROM int8_tbl; -$$ LANGUAGE SQL; - -SELECT make_table(); - -SELECT * FROM created_table; - --- Try EXPLAIN ANALYZE SELECT INTO and EXPLAIN ANALYZE CREATE TABLE AS --- WITH NO DATA, but hide the outputs since they won't be stable. -DO $$ -BEGIN - EXECUTE 'EXPLAIN ANALYZE SELECT * INTO TABLE easi FROM int8_tbl'; - EXECUTE 'EXPLAIN ANALYZE CREATE TABLE easi2 AS SELECT * FROM int8_tbl WITH NO DATA'; -END$$; - -DROP TABLE created_table; -DROP TABLE easi, easi2; - --- --- Disallowed uses of SELECT ... INTO. All should fail --- -DECLARE foo CURSOR FOR SELECT 1 INTO int4_tbl; -COPY (SELECT 1 INTO frak UNION SELECT 2) TO 'blob'; -SELECT * FROM (SELECT 1 INTO f) bar; -CREATE VIEW foo AS SELECT 1 INTO int4_tbl; -INSERT INTO int4_tbl SELECT 1 INTO f; - --- Test CREATE TABLE AS ... IF NOT EXISTS -CREATE TABLE ctas_ine_tbl AS SELECT 1; -CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0; -- error -CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0; -- ok -CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- error -CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- ok -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0; -- error -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0; -- ok -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- error -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS SELECT 1 / 0 WITH NO DATA; -- ok -PREPARE ctas_ine_query AS SELECT 1 / 0; -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE ctas_ine_tbl AS EXECUTE ctas_ine_query; -- error -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) - CREATE TABLE IF NOT EXISTS ctas_ine_tbl AS EXECUTE ctas_ine_query; -- ok -DROP TABLE ctas_ine_tbl; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_parallel.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_parallel.sql deleted file mode 100644 index f924731248..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_parallel.sql +++ /dev/null @@ -1,458 +0,0 @@ --- --- PARALLEL --- - -create function sp_parallel_restricted(int) returns int as - $$begin return $1; end$$ language plpgsql parallel restricted; - -begin; - --- encourage use of parallel plans -set parallel_setup_cost=0; -set parallel_tuple_cost=0; -set min_parallel_table_scan_size=0; -set max_parallel_workers_per_gather=4; - --- Parallel Append with partial-subplans -explain (costs off) - select round(avg(aa)), sum(aa) from a_star; -select round(avg(aa)), sum(aa) from a_star a1; - --- Parallel Append with both partial and non-partial subplans -alter table c_star set (parallel_workers = 0); -alter table d_star set (parallel_workers = 0); -explain (costs off) - select round(avg(aa)), sum(aa) from a_star; -select round(avg(aa)), sum(aa) from a_star a2; - --- Parallel Append with only non-partial subplans -alter table a_star set (parallel_workers = 0); -alter table b_star set (parallel_workers = 0); -alter table e_star set (parallel_workers = 0); -alter table f_star set (parallel_workers = 0); -explain (costs off) - select round(avg(aa)), sum(aa) from a_star; -select round(avg(aa)), sum(aa) from a_star a3; - --- Disable Parallel Append -alter table a_star reset (parallel_workers); -alter table b_star reset (parallel_workers); -alter table c_star reset (parallel_workers); -alter table d_star reset (parallel_workers); -alter table e_star reset (parallel_workers); -alter table f_star reset (parallel_workers); -set enable_parallel_append to off; -explain (costs off) - select round(avg(aa)), sum(aa) from a_star; -select round(avg(aa)), sum(aa) from a_star a4; -reset enable_parallel_append; - --- Parallel Append that runs serially -create function sp_test_func() returns setof text as -$$ select 'foo'::varchar union all select 'bar'::varchar $$ -language sql stable; -select sp_test_func() order by 1; - --- Parallel Append is not to be used when the subpath depends on the outer param -create table part_pa_test(a int, b int) partition by range(a); -create table part_pa_test_p1 partition of part_pa_test for values from (minvalue) to (0); -create table part_pa_test_p2 partition of part_pa_test for values from (0) to (maxvalue); -explain (costs off) - select (select max((select pa1.b from part_pa_test pa1 where pa1.a = pa2.a))) - from part_pa_test pa2; -drop table part_pa_test; - --- test with leader participation disabled -set parallel_leader_participation = off; -explain (costs off) - select count(*) from tenk1 where stringu1 = 'GRAAAA'; -select count(*) from tenk1 where stringu1 = 'GRAAAA'; - --- test with leader participation disabled, but no workers available (so --- the leader will have to run the plan despite the setting) -set max_parallel_workers = 0; -explain (costs off) - select count(*) from tenk1 where stringu1 = 'GRAAAA'; -select count(*) from tenk1 where stringu1 = 'GRAAAA'; - -reset max_parallel_workers; -reset parallel_leader_participation; - --- test that parallel_restricted function doesn't run in worker -alter table tenk1 set (parallel_workers = 4); -explain (verbose, costs off) -select sp_parallel_restricted(unique1) from tenk1 - where stringu1 = 'GRAAAA' order by 1; - --- test parallel plan when group by expression is in target list. -explain (costs off) - select length(stringu1) from tenk1 group by length(stringu1); -select length(stringu1) from tenk1 group by length(stringu1); - -explain (costs off) - select stringu1, count(*) from tenk1 group by stringu1 order by stringu1; - --- test that parallel plan for aggregates is not selected when --- target list contains parallel restricted clause. -explain (costs off) - select sum(sp_parallel_restricted(unique1)) from tenk1 - group by(sp_parallel_restricted(unique1)); - --- test prepared statement -prepare tenk1_count(integer) As select count((unique1)) from tenk1 where hundred > $1; -explain (costs off) execute tenk1_count(1); -execute tenk1_count(1); -deallocate tenk1_count; - --- test parallel plans for queries containing un-correlated subplans. -alter table tenk2 set (parallel_workers = 0); -explain (costs off) - select count(*) from tenk1 where (two, four) not in - (select hundred, thousand from tenk2 where thousand > 100); -select count(*) from tenk1 where (two, four) not in - (select hundred, thousand from tenk2 where thousand > 100); --- this is not parallel-safe due to use of random() within SubLink's testexpr: -explain (costs off) - select * from tenk1 where (unique1 + random())::integer not in - (select ten from tenk2); -alter table tenk2 reset (parallel_workers); - --- test parallel plan for a query containing initplan. -set enable_indexscan = off; -set enable_indexonlyscan = off; -set enable_bitmapscan = off; -alter table tenk2 set (parallel_workers = 2); - -explain (costs off) - select count(*) from tenk1 - where tenk1.unique1 = (Select max(tenk2.unique1) from tenk2); -select count(*) from tenk1 - where tenk1.unique1 = (Select max(tenk2.unique1) from tenk2); - -reset enable_indexscan; -reset enable_indexonlyscan; -reset enable_bitmapscan; -alter table tenk2 reset (parallel_workers); - --- test parallel index scans. -set enable_seqscan to off; -set enable_bitmapscan to off; - -explain (costs off) - select count((unique1)) from tenk1 where hundred > 1; -select count((unique1)) from tenk1 where hundred > 1; - --- test parallel index-only scans. -explain (costs off) - select count(*) from tenk1 where thousand > 95; -select count(*) from tenk1 where thousand > 95; - --- test rescan cases too -set enable_material = false; - -explain (costs off) -select * from - (select count(unique1) from tenk1 where hundred > 10) ss - right join (values (1),(2),(3)) v(x) on true; -select * from - (select count(unique1) from tenk1 where hundred > 10) ss - right join (values (1),(2),(3)) v(x) on true; - -explain (costs off) -select * from - (select count(*) from tenk1 where thousand > 99) ss - right join (values (1),(2),(3)) v(x) on true; -select * from - (select count(*) from tenk1 where thousand > 99) ss - right join (values (1),(2),(3)) v(x) on true; - --- test rescans for a Limit node with a parallel node beneath it. -reset enable_seqscan; -set enable_indexonlyscan to off; -set enable_indexscan to off; -alter table tenk1 set (parallel_workers = 0); -alter table tenk2 set (parallel_workers = 1); -explain (costs off) -select count(*) from tenk1 - left join (select tenk2.unique1 from tenk2 order by 1 limit 1000) ss - on tenk1.unique1 < ss.unique1 + 1 - where tenk1.unique1 < 2; -select count(*) from tenk1 - left join (select tenk2.unique1 from tenk2 order by 1 limit 1000) ss - on tenk1.unique1 < ss.unique1 + 1 - where tenk1.unique1 < 2; ---reset the value of workers for each table as it was before this test. -alter table tenk1 set (parallel_workers = 4); -alter table tenk2 reset (parallel_workers); - -reset enable_material; -reset enable_bitmapscan; -reset enable_indexonlyscan; -reset enable_indexscan; - --- test parallel bitmap heap scan. -set enable_seqscan to off; -set enable_indexscan to off; -set enable_hashjoin to off; -set enable_mergejoin to off; -set enable_material to off; --- test prefetching, if the platform allows it -DO $$ -BEGIN - SET effective_io_concurrency = 50; -EXCEPTION WHEN invalid_parameter_value THEN -END $$; -set work_mem='64kB'; --set small work mem to force lossy pages -explain (costs off) - select count(*) from tenk1, tenk2 where tenk1.hundred > 1 and tenk2.thousand=0; -select count(*) from tenk1, tenk2 where tenk1.hundred > 1 and tenk2.thousand=0; - -create table bmscantest (a int, t text); -insert into bmscantest select r, 'fooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo' FROM generate_series(1,100000) r; -create index i_bmtest ON bmscantest(a); -select count(*) from bmscantest where a>1; - --- test accumulation of stats for parallel nodes -reset enable_seqscan; -alter table tenk2 set (parallel_workers = 0); -explain (analyze, timing off, summary off, costs off) - select count(*) from tenk1, tenk2 where tenk1.hundred > 1 - and tenk2.thousand=0; -alter table tenk2 reset (parallel_workers); - -reset work_mem; -create function explain_parallel_sort_stats() returns setof text -language plpgsql as -$$ -declare ln text; -begin - for ln in - explain (analyze, timing off, summary off, costs off) - select * from - (select ten from tenk1 where ten < 100 order by ten) ss - right join (values (1),(2),(3)) v(x) on true - loop - ln := regexp_replace(ln, 'Memory: \S*', 'Memory: xxx'); - return next ln; - end loop; -end; -$$; -select * from explain_parallel_sort_stats(); - -reset enable_indexscan; -reset enable_hashjoin; -reset enable_mergejoin; -reset enable_material; -reset effective_io_concurrency; -drop table bmscantest; -drop function explain_parallel_sort_stats(); - --- test parallel merge join path. -set enable_hashjoin to off; -set enable_nestloop to off; - -explain (costs off) - select count(*) from tenk1, tenk2 where tenk1.unique1 = tenk2.unique1; -select count(*) from tenk1, tenk2 where tenk1.unique1 = tenk2.unique1; - -reset enable_hashjoin; -reset enable_nestloop; - --- test gather merge -set enable_hashagg = false; - -explain (costs off) - select count(*) from tenk1 group by twenty; - -select count(*) from tenk1 group by twenty; - ---test expressions in targetlist are pushed down for gather merge -create function sp_simple_func(var1 integer) returns integer -as $$ -begin - return var1 + 10; -end; -$$ language plpgsql PARALLEL SAFE; - -explain (costs off, verbose) - select ten, sp_simple_func(ten) from tenk1 where ten < 100 order by ten; - -drop function sp_simple_func(integer); - --- test handling of SRFs in targetlist (bug in 10.0) - -explain (costs off) - select count(*), generate_series(1,2) from tenk1 group by twenty; - -select count(*), generate_series(1,2) from tenk1 group by twenty; - --- test gather merge with parallel leader participation disabled -set parallel_leader_participation = off; - -explain (costs off) - select count(*) from tenk1 group by twenty; - -select count(*) from tenk1 group by twenty; - -reset parallel_leader_participation; - ---test rescan behavior of gather merge -set enable_material = false; - -explain (costs off) -select * from - (select string4, count(unique2) - from tenk1 group by string4 order by string4) ss - right join (values (1),(2),(3)) v(x) on true; - -select * from - (select string4, count(unique2) - from tenk1 group by string4 order by string4) ss - right join (values (1),(2),(3)) v(x) on true; - -reset enable_material; - -reset enable_hashagg; - --- check parallelized int8 aggregate (bug #14897) -explain (costs off) -select avg(unique1::int8) from tenk1; - -select avg(unique1::int8) from tenk1; - --- gather merge test with a LIMIT -explain (costs off) - select fivethous from tenk1 order by fivethous limit 4; - -select fivethous from tenk1 order by fivethous limit 4; - --- gather merge test with 0 worker -set max_parallel_workers = 0; -explain (costs off) - select string4 from tenk1 order by string4 limit 5; -select string4 from tenk1 order by string4 limit 5; - --- gather merge test with 0 workers, with parallel leader --- participation disabled (the leader will have to run the plan --- despite the setting) -set parallel_leader_participation = off; -explain (costs off) - select string4 from tenk1 order by string4 limit 5; -select string4 from tenk1 order by string4 limit 5; - -reset parallel_leader_participation; -reset max_parallel_workers; - -SAVEPOINT settings; -SET LOCAL force_parallel_mode = 1; -explain (costs off) - select stringu1::int2 from tenk1 where unique1 = 1; -ROLLBACK TO SAVEPOINT settings; - --- exercise record typmod remapping between backends -CREATE FUNCTION make_record(n int) - RETURNS RECORD LANGUAGE plpgsql PARALLEL SAFE AS -$$ -BEGIN - RETURN CASE n - WHEN 1 THEN ROW(1) - WHEN 2 THEN ROW(1, 2) - WHEN 3 THEN ROW(1, 2, 3) - WHEN 4 THEN ROW(1, 2, 3, 4) - ELSE ROW(1, 2, 3, 4, 5) - END; -END; -$$; -SAVEPOINT settings; -SET LOCAL force_parallel_mode = 1; -SELECT make_record(x) FROM (SELECT generate_series(1, 5) x) ss ORDER BY x; -ROLLBACK TO SAVEPOINT settings; -DROP function make_record(n int); - --- test the sanity of parallel query after the active role is dropped. -drop role if exists regress_parallel_worker; -create role regress_parallel_worker; -set role regress_parallel_worker; -reset session authorization; -drop role regress_parallel_worker; -set force_parallel_mode = 1; -select count(*) from tenk1; -reset force_parallel_mode; -reset role; - --- Window function calculation can't be pushed to workers. -explain (costs off, verbose) - select count(*) from tenk1 a where (unique1, two) in - (select unique1, row_number() over() from tenk1 b); - - --- LIMIT/OFFSET within sub-selects can't be pushed to workers. -explain (costs off) - select * from tenk1 a where two in - (select two from tenk1 b where stringu1 like '%AAAA' limit 3); - --- to increase the parallel query test coverage -SAVEPOINT settings; -SET LOCAL force_parallel_mode = 1; -EXPLAIN (analyze, timing off, summary off, costs off) SELECT * FROM tenk1; -ROLLBACK TO SAVEPOINT settings; - --- provoke error in worker --- (make the error message long enough to require multiple bufferloads) -SAVEPOINT settings; -SET LOCAL force_parallel_mode = 1; -select (stringu1 || repeat('abcd', 5000))::int2 from tenk1 where unique1 = 1; -ROLLBACK TO SAVEPOINT settings; - --- test interaction with set-returning functions -SAVEPOINT settings; - --- multiple subqueries under a single Gather node --- must set parallel_setup_cost > 0 to discourage multiple Gather nodes -SET LOCAL parallel_setup_cost = 10; -EXPLAIN (COSTS OFF) -SELECT unique1 FROM tenk1 WHERE fivethous = tenthous + 1 -UNION ALL -SELECT unique1 FROM tenk1 WHERE fivethous = tenthous + 1; -ROLLBACK TO SAVEPOINT settings; - --- can't use multiple subqueries under a single Gather node due to initPlans -EXPLAIN (COSTS OFF) -SELECT unique1 FROM tenk1 WHERE fivethous = - (SELECT unique1 FROM tenk1 WHERE fivethous = 1 LIMIT 1) -UNION ALL -SELECT unique1 FROM tenk1 WHERE fivethous = - (SELECT unique2 FROM tenk1 WHERE fivethous = 1 LIMIT 1) -ORDER BY 1; - --- test interaction with SRFs -SELECT * FROM information_schema.foreign_data_wrapper_options -ORDER BY 1, 2, 3; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT generate_series(1, two), array(select generate_series(1, two)) - FROM tenk1 ORDER BY tenthous; - --- test passing expanded-value representations to workers -CREATE FUNCTION make_some_array(int,int) returns int[] as -$$declare x int[]; - begin - x[1] := $1; - x[2] := $2; - return x; - end$$ language plpgsql parallel safe; -CREATE TABLE fooarr(f1 text, f2 int[], f3 text); -INSERT INTO fooarr VALUES('1', ARRAY[1,2], 'one'); - -PREPARE pstmt(text, int[]) AS SELECT * FROM fooarr WHERE f1 = $1 AND f2 = $2; -EXPLAIN (COSTS OFF) EXECUTE pstmt('1', make_some_array(1,2)); -EXECUTE pstmt('1', make_some_array(1,2)); -DEALLOCATE pstmt; - --- test interaction between subquery and partial_paths -CREATE VIEW tenk1_vw_sec WITH (security_barrier) AS SELECT * FROM tenk1; -EXPLAIN (COSTS OFF) -SELECT 1 FROM tenk1_vw_sec - WHERE (SELECT sum(f1) FROM int4_tbl WHERE f1 < unique1) < 100; - -rollback; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_views.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_views.sql deleted file mode 100644 index e742f13699..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fselect_views.sql +++ /dev/null @@ -1,155 +0,0 @@ --- --- SELECT_VIEWS --- test the views defined in CREATE_VIEWS --- - -SELECT * FROM street; - -SELECT name, #thepath FROM iexit ORDER BY name COLLATE "C", 2; - -SELECT * FROM toyemp WHERE name = 'sharon'; - --- --- Test for Leaky view scenario --- -CREATE ROLE regress_alice; - -CREATE FUNCTION f_leak (text) - RETURNS bool LANGUAGE 'plpgsql' COST 0.0000001 - AS 'BEGIN RAISE NOTICE ''f_leak => %'', $1; RETURN true; END'; - -CREATE TABLE customer ( - cid int primary key, - name text not null, - tel text, - passwd text -); - -CREATE TABLE credit_card ( - cid int references customer(cid), - cnum text, - climit int -); - -CREATE TABLE credit_usage ( - cid int references customer(cid), - ymd date, - usage int -); - -INSERT INTO customer - VALUES (101, 'regress_alice', '+81-12-3456-7890', 'passwd123'), - (102, 'regress_bob', '+01-234-567-8901', 'beafsteak'), - (103, 'regress_eve', '+49-8765-43210', 'hamburger'); -INSERT INTO credit_card - VALUES (101, '1111-2222-3333-4444', 4000), - (102, '5555-6666-7777-8888', 3000), - (103, '9801-2345-6789-0123', 2000); -INSERT INTO credit_usage - VALUES (101, '2011-09-15', 120), - (101, '2011-10-05', 90), - (101, '2011-10-18', 110), - (101, '2011-10-21', 200), - (101, '2011-11-10', 80), - (102, '2011-09-22', 300), - (102, '2011-10-12', 120), - (102, '2011-10-28', 200), - (103, '2011-10-15', 480); - -CREATE VIEW my_property_normal AS - SELECT * FROM customer WHERE name = current_user; -CREATE VIEW my_property_secure WITH (security_barrier) AS - SELECT * FROM customer WHERE name = current_user; - -CREATE VIEW my_credit_card_normal AS - SELECT * FROM customer l NATURAL JOIN credit_card r - WHERE l.name = current_user; -CREATE VIEW my_credit_card_secure WITH (security_barrier) AS - SELECT * FROM customer l NATURAL JOIN credit_card r - WHERE l.name = current_user; - -CREATE VIEW my_credit_card_usage_normal AS - SELECT * FROM my_credit_card_secure l NATURAL JOIN credit_usage r; -CREATE VIEW my_credit_card_usage_secure WITH (security_barrier) AS - SELECT * FROM my_credit_card_secure l NATURAL JOIN credit_usage r; - -GRANT SELECT ON my_property_normal TO public; -GRANT SELECT ON my_property_secure TO public; -GRANT SELECT ON my_credit_card_normal TO public; -GRANT SELECT ON my_credit_card_secure TO public; -GRANT SELECT ON my_credit_card_usage_normal TO public; -GRANT SELECT ON my_credit_card_usage_secure TO public; - --- --- Run leaky view scenarios --- -SET SESSION AUTHORIZATION regress_alice; - --- --- scenario: if a qualifier with tiny-cost is given, it shall be launched --- prior to the security policy of the view. --- -SELECT * FROM my_property_normal WHERE f_leak(passwd); -EXPLAIN (COSTS OFF) SELECT * FROM my_property_normal WHERE f_leak(passwd); - -SELECT * FROM my_property_secure WHERE f_leak(passwd); -EXPLAIN (COSTS OFF) SELECT * FROM my_property_secure WHERE f_leak(passwd); - --- --- scenario: qualifiers can be pushed down if they contain leaky functions, --- provided they aren't passed data from inside the view. --- -SELECT * FROM my_property_normal v - WHERE f_leak('passwd') AND f_leak(passwd); -EXPLAIN (COSTS OFF) SELECT * FROM my_property_normal v - WHERE f_leak('passwd') AND f_leak(passwd); - -SELECT * FROM my_property_secure v - WHERE f_leak('passwd') AND f_leak(passwd); -EXPLAIN (COSTS OFF) SELECT * FROM my_property_secure v - WHERE f_leak('passwd') AND f_leak(passwd); - --- --- scenario: if a qualifier references only one-side of a particular join- --- tree, it shall be distributed to the most deep scan plan as --- possible as we can. --- -SELECT * FROM my_credit_card_normal WHERE f_leak(cnum); -EXPLAIN (COSTS OFF) SELECT * FROM my_credit_card_normal WHERE f_leak(cnum); - -SELECT * FROM my_credit_card_secure WHERE f_leak(cnum); -EXPLAIN (COSTS OFF) SELECT * FROM my_credit_card_secure WHERE f_leak(cnum); - --- --- scenario: an external qualifier can be pushed-down by in-front-of the --- views with "security_barrier" attribute, except for operators --- implemented with leakproof functions. --- -SELECT * FROM my_credit_card_usage_normal - WHERE f_leak(cnum) AND ymd >= '2011-10-01' AND ymd < '2011-11-01'; -EXPLAIN (COSTS OFF) SELECT * FROM my_credit_card_usage_normal - WHERE f_leak(cnum) AND ymd >= '2011-10-01' AND ymd < '2011-11-01'; - -SELECT * FROM my_credit_card_usage_secure - WHERE f_leak(cnum) AND ymd >= '2011-10-01' AND ymd < '2011-11-01'; -EXPLAIN (COSTS OFF) SELECT * FROM my_credit_card_usage_secure - WHERE f_leak(cnum) AND ymd >= '2011-10-01' AND ymd < '2011-11-01'; - --- --- Test for the case when security_barrier gets changed between rewriter --- and planner stage. --- -PREPARE p1 AS SELECT * FROM my_property_normal WHERE f_leak(passwd); -PREPARE p2 AS SELECT * FROM my_property_secure WHERE f_leak(passwd); -EXECUTE p1; -EXECUTE p2; -RESET SESSION AUTHORIZATION; -ALTER VIEW my_property_normal SET (security_barrier=true); -ALTER VIEW my_property_secure SET (security_barrier=false); -SET SESSION AUTHORIZATION regress_alice; -EXECUTE p1; -- To be perform as a view with security-barrier -EXECUTE p2; -- To be perform as a view without security-barrier - --- Cleanup. -RESET SESSION AUTHORIZATION; -DROP ROLE regress_alice; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsequence.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsequence.sql deleted file mode 100644 index 674f5f1f66..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsequence.sql +++ /dev/null @@ -1,416 +0,0 @@ --- --- CREATE SEQUENCE --- - --- various error cases -CREATE SEQUENCE sequence_testx INCREMENT BY 0; -CREATE SEQUENCE sequence_testx INCREMENT BY -1 MINVALUE 20; -CREATE SEQUENCE sequence_testx INCREMENT BY 1 MAXVALUE -20; -CREATE SEQUENCE sequence_testx INCREMENT BY -1 START 10; -CREATE SEQUENCE sequence_testx INCREMENT BY 1 START -10; -CREATE SEQUENCE sequence_testx CACHE 0; - --- OWNED BY errors -CREATE SEQUENCE sequence_testx OWNED BY nobody; -- nonsense word -CREATE SEQUENCE sequence_testx OWNED BY pg_class_oid_index.oid; -- not a table -CREATE SEQUENCE sequence_testx OWNED BY pg_class.relname; -- not same schema -CREATE TABLE sequence_test_table (a int); -CREATE SEQUENCE sequence_testx OWNED BY sequence_test_table.b; -- wrong column -DROP TABLE sequence_test_table; - --- sequence data types -CREATE SEQUENCE sequence_test5 AS integer; -CREATE SEQUENCE sequence_test6 AS smallint; -CREATE SEQUENCE sequence_test7 AS bigint; -CREATE SEQUENCE sequence_test8 AS integer MAXVALUE 100000; -CREATE SEQUENCE sequence_test9 AS integer INCREMENT BY -1; -CREATE SEQUENCE sequence_test10 AS integer MINVALUE -100000 START 1; -CREATE SEQUENCE sequence_test11 AS smallint; -CREATE SEQUENCE sequence_test12 AS smallint INCREMENT -1; -CREATE SEQUENCE sequence_test13 AS smallint MINVALUE -32768; -CREATE SEQUENCE sequence_test14 AS smallint MAXVALUE 32767 INCREMENT -1; -CREATE SEQUENCE sequence_testx AS text; -CREATE SEQUENCE sequence_testx AS nosuchtype; - -CREATE SEQUENCE sequence_testx AS smallint MAXVALUE 100000; -CREATE SEQUENCE sequence_testx AS smallint MINVALUE -100000; - -ALTER SEQUENCE sequence_test5 AS smallint; -- success, max will be adjusted -ALTER SEQUENCE sequence_test8 AS smallint; -- fail, max has to be adjusted -ALTER SEQUENCE sequence_test8 AS smallint MAXVALUE 20000; -- ok now -ALTER SEQUENCE sequence_test9 AS smallint; -- success, min will be adjusted -ALTER SEQUENCE sequence_test10 AS smallint; -- fail, min has to be adjusted -ALTER SEQUENCE sequence_test10 AS smallint MINVALUE -20000; -- ok now - -ALTER SEQUENCE sequence_test11 AS int; -- max will be adjusted -ALTER SEQUENCE sequence_test12 AS int; -- min will be adjusted -ALTER SEQUENCE sequence_test13 AS int; -- min and max will be adjusted -ALTER SEQUENCE sequence_test14 AS int; -- min and max will be adjusted - ---- ---- test creation of SERIAL column ---- - -CREATE TABLE serialTest1 (f1 text, f2 serial); - -INSERT INTO serialTest1 VALUES ('foo'); -INSERT INTO serialTest1 VALUES ('bar'); -INSERT INTO serialTest1 VALUES ('force', 100); -INSERT INTO serialTest1 VALUES ('wrong', NULL); - -SELECT * FROM serialTest1; - -SELECT pg_get_serial_sequence('serialTest1', 'f2'); - --- test smallserial / bigserial -CREATE TABLE serialTest2 (f1 text, f2 serial, f3 smallserial, f4 serial2, - f5 bigserial, f6 serial8); - -INSERT INTO serialTest2 (f1) - VALUES ('test_defaults'); - -INSERT INTO serialTest2 (f1, f2, f3, f4, f5, f6) - VALUES ('test_max_vals', 2147483647, 32767, 32767, 9223372036854775807, - 9223372036854775807), - ('test_min_vals', -2147483648, -32768, -32768, -9223372036854775808, - -9223372036854775808); - --- All these INSERTs should fail: -INSERT INTO serialTest2 (f1, f3) - VALUES ('bogus', -32769); - -INSERT INTO serialTest2 (f1, f4) - VALUES ('bogus', -32769); - -INSERT INTO serialTest2 (f1, f3) - VALUES ('bogus', 32768); - -INSERT INTO serialTest2 (f1, f4) - VALUES ('bogus', 32768); - -INSERT INTO serialTest2 (f1, f5) - VALUES ('bogus', -9223372036854775809); - -INSERT INTO serialTest2 (f1, f6) - VALUES ('bogus', -9223372036854775809); - -INSERT INTO serialTest2 (f1, f5) - VALUES ('bogus', 9223372036854775808); - -INSERT INTO serialTest2 (f1, f6) - VALUES ('bogus', 9223372036854775808); - -SELECT * FROM serialTest2 ORDER BY f2 ASC; - -SELECT nextval('serialTest2_f2_seq'); -SELECT nextval('serialTest2_f3_seq'); -SELECT nextval('serialTest2_f4_seq'); -SELECT nextval('serialTest2_f5_seq'); -SELECT nextval('serialTest2_f6_seq'); - --- basic sequence operations using both text and oid references -CREATE SEQUENCE sequence_test; -CREATE SEQUENCE IF NOT EXISTS sequence_test; - -SELECT nextval('sequence_test'::text); -SELECT nextval('sequence_test'::regclass); -SELECT currval('sequence_test'::text); -SELECT currval('sequence_test'::regclass); -SELECT setval('sequence_test'::text, 32); -SELECT nextval('sequence_test'::regclass); -SELECT setval('sequence_test'::text, 99, false); -SELECT nextval('sequence_test'::regclass); -SELECT setval('sequence_test'::regclass, 32); -SELECT nextval('sequence_test'::text); -SELECT setval('sequence_test'::regclass, 99, false); -SELECT nextval('sequence_test'::text); -DISCARD SEQUENCES; -SELECT currval('sequence_test'::regclass); - -DROP SEQUENCE sequence_test; - --- renaming sequences -CREATE SEQUENCE foo_seq; -ALTER TABLE foo_seq RENAME TO foo_seq_new; -SELECT * FROM foo_seq_new; -SELECT nextval('foo_seq_new'); -SELECT nextval('foo_seq_new'); --- log_cnt can be higher if there is a checkpoint just at the right --- time, so just test for the expected range -SELECT last_value, log_cnt IN (31, 32) AS log_cnt_ok, is_called FROM foo_seq_new; -DROP SEQUENCE foo_seq_new; - --- renaming serial sequences -ALTER TABLE serialtest1_f2_seq RENAME TO serialtest1_f2_foo; -INSERT INTO serialTest1 VALUES ('more'); -SELECT * FROM serialTest1; - --- --- Check dependencies of serial and ordinary sequences --- -CREATE TEMP SEQUENCE myseq2; -CREATE TEMP SEQUENCE myseq3; -CREATE TEMP TABLE t1 ( - f1 serial, - f2 int DEFAULT nextval('myseq2'), - f3 int DEFAULT nextval('myseq3'::text) -); --- Both drops should fail, but with different error messages: -DROP SEQUENCE t1_f1_seq; -DROP SEQUENCE myseq2; --- This however will work: -DROP SEQUENCE myseq3; -DROP TABLE t1; --- Fails because no longer existent: -DROP SEQUENCE t1_f1_seq; --- Now OK: -DROP SEQUENCE myseq2; - --- --- Alter sequence --- - -ALTER SEQUENCE IF EXISTS sequence_test2 RESTART WITH 24 - INCREMENT BY 4 MAXVALUE 36 MINVALUE 5 CYCLE; - -ALTER SEQUENCE serialTest1 CYCLE; -- error, not a sequence - -CREATE SEQUENCE sequence_test2 START WITH 32; -CREATE SEQUENCE sequence_test4 INCREMENT BY -1; - -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test4'); - -ALTER SEQUENCE sequence_test2 RESTART; -SELECT nextval('sequence_test2'); - -ALTER SEQUENCE sequence_test2 RESTART WITH 0; -- error -ALTER SEQUENCE sequence_test4 RESTART WITH 40; -- error - --- test CYCLE and NO CYCLE -ALTER SEQUENCE sequence_test2 RESTART WITH 24 - INCREMENT BY 4 MAXVALUE 36 MINVALUE 5 CYCLE; -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -- cycled - -ALTER SEQUENCE sequence_test2 RESTART WITH 24 - NO CYCLE; -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -- error - -ALTER SEQUENCE sequence_test2 RESTART WITH -24 START WITH -24 - INCREMENT BY -4 MINVALUE -36 MAXVALUE -5 CYCLE; -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -- cycled - -ALTER SEQUENCE sequence_test2 RESTART WITH -24 - NO CYCLE; -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -SELECT nextval('sequence_test2'); -- error - --- reset -ALTER SEQUENCE IF EXISTS sequence_test2 RESTART WITH 32 START WITH 32 - INCREMENT BY 4 MAXVALUE 36 MINVALUE 5 CYCLE; - -SELECT setval('sequence_test2', -100); -- error -SELECT setval('sequence_test2', 100); -- error -SELECT setval('sequence_test2', 5); - -CREATE SEQUENCE sequence_test3; -- not read from, to test is_called - - --- Information schema -SELECT * FROM information_schema.sequences - WHERE sequence_name ~ ANY(ARRAY['sequence_test', 'serialtest']) - ORDER BY sequence_name ASC; - -SELECT schemaname, sequencename, start_value, min_value, max_value, increment_by, cycle, cache_size, last_value -FROM pg_sequences -WHERE sequencename ~ ANY(ARRAY['sequence_test', 'serialtest']) - ORDER BY sequencename ASC; - - -SELECT * FROM pg_sequence_parameters('sequence_test4'::regclass); - - -\d sequence_test4 -\d serialtest2_f2_seq - - --- Test comments -COMMENT ON SEQUENCE asdf IS 'won''t work'; -COMMENT ON SEQUENCE sequence_test2 IS 'will work'; -COMMENT ON SEQUENCE sequence_test2 IS NULL; - --- Test lastval() -CREATE SEQUENCE seq; -SELECT nextval('seq'); -SELECT lastval(); -SELECT setval('seq', 99); -SELECT lastval(); -DISCARD SEQUENCES; -SELECT lastval(); - -CREATE SEQUENCE seq2; -SELECT nextval('seq2'); -SELECT lastval(); - -DROP SEQUENCE seq2; --- should fail -SELECT lastval(); - --- unlogged sequences --- (more tests in src/test/recovery/) -CREATE UNLOGGED SEQUENCE sequence_test_unlogged; -ALTER SEQUENCE sequence_test_unlogged SET LOGGED; -\d sequence_test_unlogged -ALTER SEQUENCE sequence_test_unlogged SET UNLOGGED; -\d sequence_test_unlogged -DROP SEQUENCE sequence_test_unlogged; - --- Test sequences in read-only transactions -CREATE TEMPORARY SEQUENCE sequence_test_temp1; -START TRANSACTION READ ONLY; -SELECT nextval('sequence_test_temp1'); -- ok -SELECT nextval('sequence_test2'); -- error -ROLLBACK; -START TRANSACTION READ ONLY; -SELECT setval('sequence_test_temp1', 1); -- ok -SELECT setval('sequence_test2', 1); -- error -ROLLBACK; - --- privileges tests - -CREATE USER regress_seq_user; - --- nextval -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT SELECT ON seq3 TO regress_seq_user; -SELECT nextval('seq3'); -ROLLBACK; - -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT UPDATE ON seq3 TO regress_seq_user; -SELECT nextval('seq3'); -ROLLBACK; - -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT USAGE ON seq3 TO regress_seq_user; -SELECT nextval('seq3'); -ROLLBACK; - --- currval -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -SELECT nextval('seq3'); -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT SELECT ON seq3 TO regress_seq_user; -SELECT currval('seq3'); -ROLLBACK; - -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -SELECT nextval('seq3'); -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT UPDATE ON seq3 TO regress_seq_user; -SELECT currval('seq3'); -ROLLBACK; - -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -SELECT nextval('seq3'); -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT USAGE ON seq3 TO regress_seq_user; -SELECT currval('seq3'); -ROLLBACK; - --- lastval -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -SELECT nextval('seq3'); -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT SELECT ON seq3 TO regress_seq_user; -SELECT lastval(); -ROLLBACK; - -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -SELECT nextval('seq3'); -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT UPDATE ON seq3 TO regress_seq_user; -SELECT lastval(); -ROLLBACK; - -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -SELECT nextval('seq3'); -REVOKE ALL ON seq3 FROM regress_seq_user; -GRANT USAGE ON seq3 TO regress_seq_user; -SELECT lastval(); -ROLLBACK; - --- setval -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -CREATE SEQUENCE seq3; -REVOKE ALL ON seq3 FROM regress_seq_user; -SAVEPOINT save; -SELECT setval('seq3', 5); -ROLLBACK TO save; -GRANT UPDATE ON seq3 TO regress_seq_user; -SELECT setval('seq3', 5); -SELECT nextval('seq3'); -ROLLBACK; - --- ALTER SEQUENCE -BEGIN; -SET LOCAL SESSION AUTHORIZATION regress_seq_user; -ALTER SEQUENCE sequence_test2 START WITH 1; -ROLLBACK; - --- Sequences should get wiped out as well: -DROP TABLE serialTest1, serialTest2; - --- Make sure sequences are gone: -SELECT * FROM information_schema.sequences WHERE sequence_name IN - ('sequence_test2', 'serialtest2_f2_seq', 'serialtest2_f3_seq', - 'serialtest2_f4_seq', 'serialtest2_f5_seq', 'serialtest2_f6_seq') - ORDER BY sequence_name ASC; - -DROP USER regress_seq_user; -DROP SEQUENCE seq; - --- cache tests -CREATE SEQUENCE test_seq1 CACHE 10; -SELECT nextval('test_seq1'); -SELECT nextval('test_seq1'); -SELECT nextval('test_seq1'); - -DROP SEQUENCE test_seq1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fstats.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fstats.sql deleted file mode 100644 index 096f00ce8b..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fstats.sql +++ /dev/null @@ -1,399 +0,0 @@ --- --- Test cumulative stats system --- --- Must be run after tenk2 has been created (by create_table), --- populated (by create_misc) and indexed (by create_index). --- - --- conditio sine qua non -SHOW track_counts; -- must be on - --- ensure that both seqscan and indexscan plans are allowed -SET enable_seqscan TO on; -SET enable_indexscan TO on; --- for the moment, we don't want index-only scans here -SET enable_indexonlyscan TO off; --- not enabled by default, but we want to test it... -SET track_functions TO 'all'; - --- save counters -BEGIN; -SET LOCAL stats_fetch_consistency = snapshot; -CREATE TABLE prevstats AS -SELECT t.seq_scan, t.seq_tup_read, t.idx_scan, t.idx_tup_fetch, - (b.heap_blks_read + b.heap_blks_hit) AS heap_blks, - (b.idx_blks_read + b.idx_blks_hit) AS idx_blks, - pg_stat_get_snapshot_timestamp() as snap_ts - FROM pg_catalog.pg_stat_user_tables AS t, - pg_catalog.pg_statio_user_tables AS b - WHERE t.relname='tenk2' AND b.relname='tenk2'; -COMMIT; - --- test effects of TRUNCATE on n_live_tup/n_dead_tup counters -CREATE TABLE trunc_stats_test(id serial); -CREATE TABLE trunc_stats_test1(id serial, stuff text); -CREATE TABLE trunc_stats_test2(id serial); -CREATE TABLE trunc_stats_test3(id serial, stuff text); -CREATE TABLE trunc_stats_test4(id serial); - --- check that n_live_tup is reset to 0 after truncate -INSERT INTO trunc_stats_test DEFAULT VALUES; -INSERT INTO trunc_stats_test DEFAULT VALUES; -INSERT INTO trunc_stats_test DEFAULT VALUES; -TRUNCATE trunc_stats_test; - --- test involving a truncate in a transaction; 4 ins but only 1 live -INSERT INTO trunc_stats_test1 DEFAULT VALUES; -INSERT INTO trunc_stats_test1 DEFAULT VALUES; -INSERT INTO trunc_stats_test1 DEFAULT VALUES; -UPDATE trunc_stats_test1 SET id = id + 10 WHERE id IN (1, 2); -DELETE FROM trunc_stats_test1 WHERE id = 3; - -BEGIN; -UPDATE trunc_stats_test1 SET id = id + 100; -TRUNCATE trunc_stats_test1; -INSERT INTO trunc_stats_test1 DEFAULT VALUES; -COMMIT; - --- use a savepoint: 1 insert, 1 live -BEGIN; -INSERT INTO trunc_stats_test2 DEFAULT VALUES; -INSERT INTO trunc_stats_test2 DEFAULT VALUES; -SAVEPOINT p1; -INSERT INTO trunc_stats_test2 DEFAULT VALUES; -TRUNCATE trunc_stats_test2; -INSERT INTO trunc_stats_test2 DEFAULT VALUES; -RELEASE SAVEPOINT p1; -COMMIT; - --- rollback a savepoint: this should count 4 inserts and have 2 --- live tuples after commit (and 2 dead ones due to aborted subxact) -BEGIN; -INSERT INTO trunc_stats_test3 DEFAULT VALUES; -INSERT INTO trunc_stats_test3 DEFAULT VALUES; -SAVEPOINT p1; -INSERT INTO trunc_stats_test3 DEFAULT VALUES; -INSERT INTO trunc_stats_test3 DEFAULT VALUES; -TRUNCATE trunc_stats_test3; -INSERT INTO trunc_stats_test3 DEFAULT VALUES; -ROLLBACK TO SAVEPOINT p1; -COMMIT; - --- rollback a truncate: this should count 2 inserts and produce 2 dead tuples -BEGIN; -INSERT INTO trunc_stats_test4 DEFAULT VALUES; -INSERT INTO trunc_stats_test4 DEFAULT VALUES; -TRUNCATE trunc_stats_test4; -INSERT INTO trunc_stats_test4 DEFAULT VALUES; -ROLLBACK; - --- do a seqscan -SELECT count(*) FROM tenk2; --- do an indexscan --- make sure it is not a bitmap scan, which might skip fetching heap tuples -SET enable_bitmapscan TO off; -SELECT count(*) FROM tenk2 WHERE unique1 = 1; -RESET enable_bitmapscan; - --- ensure pending stats are flushed -SELECT pg_stat_force_next_flush(); - --- check effects -BEGIN; -SET LOCAL stats_fetch_consistency = snapshot; - -SELECT relname, n_tup_ins, n_tup_upd, n_tup_del, n_live_tup, n_dead_tup - FROM pg_stat_user_tables - WHERE relname like 'trunc_stats_test%' order by relname; - -SELECT st.seq_scan >= pr.seq_scan + 1, - st.seq_tup_read >= pr.seq_tup_read + cl.reltuples, - st.idx_scan >= pr.idx_scan + 1, - st.idx_tup_fetch >= pr.idx_tup_fetch + 1 - FROM pg_stat_user_tables AS st, pg_class AS cl, prevstats AS pr - WHERE st.relname='tenk2' AND cl.relname='tenk2'; - -SELECT st.heap_blks_read + st.heap_blks_hit >= pr.heap_blks + cl.relpages, - st.idx_blks_read + st.idx_blks_hit >= pr.idx_blks + 1 - FROM pg_statio_user_tables AS st, pg_class AS cl, prevstats AS pr - WHERE st.relname='tenk2' AND cl.relname='tenk2'; - -SELECT pr.snap_ts < pg_stat_get_snapshot_timestamp() as snapshot_newer -FROM prevstats AS pr; - -COMMIT; - ----- --- Basic tests for track_functions ---- -CREATE FUNCTION stats_test_func1() RETURNS VOID LANGUAGE plpgsql AS $$BEGIN END;$$; -SELECT 'stats_test_func1()'::regprocedure::oid AS stats_test_func1_oid \gset -CREATE FUNCTION stats_test_func2() RETURNS VOID LANGUAGE plpgsql AS $$BEGIN END;$$; -SELECT 'stats_test_func2()'::regprocedure::oid AS stats_test_func2_oid \gset - --- test that stats are accumulated -BEGIN; -SET LOCAL stats_fetch_consistency = none; -SELECT pg_stat_get_function_calls(:stats_test_func1_oid); -SELECT pg_stat_get_xact_function_calls(:stats_test_func1_oid); -SELECT stats_test_func1(); -SELECT pg_stat_get_xact_function_calls(:stats_test_func1_oid); -SELECT stats_test_func1(); -SELECT pg_stat_get_xact_function_calls(:stats_test_func1_oid); -SELECT pg_stat_get_function_calls(:stats_test_func1_oid); -COMMIT; - --- Verify that function stats are not transactional - --- rolled back savepoint in committing transaction -BEGIN; -SELECT stats_test_func2(); -SAVEPOINT foo; -SELECT stats_test_func2(); -ROLLBACK TO SAVEPOINT foo; -SELECT pg_stat_get_xact_function_calls(:stats_test_func2_oid); -SELECT stats_test_func2(); -COMMIT; - --- rolled back transaction -BEGIN; -SELECT stats_test_func2(); -ROLLBACK; - -SELECT pg_stat_force_next_flush(); - --- check collected stats -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func1_oid; -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func2_oid; - - --- check that a rolled back drop function stats leaves stats alive -BEGIN; -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func1_oid; -DROP FUNCTION stats_test_func1(); --- shouldn't be visible via view -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func1_oid; --- but still via oid access -SELECT pg_stat_get_function_calls(:stats_test_func1_oid); -ROLLBACK; -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func1_oid; -SELECT pg_stat_get_function_calls(:stats_test_func1_oid); - - --- check that function dropped in main transaction leaves no stats behind -BEGIN; -DROP FUNCTION stats_test_func1(); -COMMIT; -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func1_oid; -SELECT pg_stat_get_function_calls(:stats_test_func1_oid); - --- check that function dropped in a subtransaction leaves no stats behind -BEGIN; -SELECT stats_test_func2(); -SAVEPOINT a; -SELECT stats_test_func2(); -SAVEPOINT b; -DROP FUNCTION stats_test_func2(); -COMMIT; -SELECT funcname, calls FROM pg_stat_user_functions WHERE funcid = :stats_test_func2_oid; -SELECT pg_stat_get_function_calls(:stats_test_func2_oid); - - --- Check that stats for relations are dropped. For that we need to access stats --- by oid after the DROP TABLE. Save oids. -CREATE TABLE drop_stats_test(); -INSERT INTO drop_stats_test DEFAULT VALUES; -SELECT 'drop_stats_test'::regclass::oid AS drop_stats_test_oid \gset - -CREATE TABLE drop_stats_test_xact(); -INSERT INTO drop_stats_test_xact DEFAULT VALUES; -SELECT 'drop_stats_test_xact'::regclass::oid AS drop_stats_test_xact_oid \gset - -CREATE TABLE drop_stats_test_subxact(); -INSERT INTO drop_stats_test_subxact DEFAULT VALUES; -SELECT 'drop_stats_test_subxact'::regclass::oid AS drop_stats_test_subxact_oid \gset - -SELECT pg_stat_force_next_flush(); - -SELECT pg_stat_get_live_tuples(:drop_stats_test_oid); -DROP TABLE drop_stats_test; -SELECT pg_stat_get_live_tuples(:drop_stats_test_oid); -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_oid); - --- check that rollback protects against having stats dropped and that local --- modifications don't pose a problem -SELECT pg_stat_get_live_tuples(:drop_stats_test_xact_oid); -SELECT pg_stat_get_tuples_inserted(:drop_stats_test_xact_oid); -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_xact_oid); -BEGIN; -INSERT INTO drop_stats_test_xact DEFAULT VALUES; -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_xact_oid); -DROP TABLE drop_stats_test_xact; -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_xact_oid); -ROLLBACK; -SELECT pg_stat_force_next_flush(); -SELECT pg_stat_get_live_tuples(:drop_stats_test_xact_oid); -SELECT pg_stat_get_tuples_inserted(:drop_stats_test_xact_oid); - --- transactional drop -SELECT pg_stat_get_live_tuples(:drop_stats_test_xact_oid); -SELECT pg_stat_get_tuples_inserted(:drop_stats_test_xact_oid); -BEGIN; -INSERT INTO drop_stats_test_xact DEFAULT VALUES; -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_xact_oid); -DROP TABLE drop_stats_test_xact; -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_xact_oid); -COMMIT; -SELECT pg_stat_force_next_flush(); -SELECT pg_stat_get_live_tuples(:drop_stats_test_xact_oid); -SELECT pg_stat_get_tuples_inserted(:drop_stats_test_xact_oid); - --- savepoint rollback (2 levels) -SELECT pg_stat_get_live_tuples(:drop_stats_test_subxact_oid); -BEGIN; -INSERT INTO drop_stats_test_subxact DEFAULT VALUES; -SAVEPOINT sp1; -INSERT INTO drop_stats_test_subxact DEFAULT VALUES; -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_subxact_oid); -SAVEPOINT sp2; -DROP TABLE drop_stats_test_subxact; -ROLLBACK TO SAVEPOINT sp2; -SELECT pg_stat_get_xact_tuples_inserted(:drop_stats_test_subxact_oid); -COMMIT; -SELECT pg_stat_force_next_flush(); -SELECT pg_stat_get_live_tuples(:drop_stats_test_subxact_oid); - --- savepoint rolback (1 level) -SELECT pg_stat_get_live_tuples(:drop_stats_test_subxact_oid); -BEGIN; -SAVEPOINT sp1; -DROP TABLE drop_stats_test_subxact; -SAVEPOINT sp2; -ROLLBACK TO SAVEPOINT sp1; -COMMIT; -SELECT pg_stat_get_live_tuples(:drop_stats_test_subxact_oid); - --- and now actually drop -SELECT pg_stat_get_live_tuples(:drop_stats_test_subxact_oid); -BEGIN; -SAVEPOINT sp1; -DROP TABLE drop_stats_test_subxact; -SAVEPOINT sp2; -RELEASE SAVEPOINT sp1; -COMMIT; -SELECT pg_stat_get_live_tuples(:drop_stats_test_subxact_oid); - -DROP TABLE trunc_stats_test, trunc_stats_test1, trunc_stats_test2, trunc_stats_test3, trunc_stats_test4; -DROP TABLE prevstats; - - ------ --- Test that various stats views are being properly populated ------ - --- Test that sessions is incremented when a new session is started in pg_stat_database -SELECT sessions AS db_stat_sessions FROM pg_stat_database WHERE datname = (SELECT current_database()) \gset -\c -SELECT sessions > :db_stat_sessions FROM pg_stat_database WHERE datname = (SELECT current_database()); - --- Test pg_stat_bgwriter checkpointer-related stats, together with pg_stat_wal -SELECT checkpoints_req AS rqst_ckpts_before FROM pg_stat_bgwriter \gset - --- Test pg_stat_wal -SELECT wal_bytes AS wal_bytes_before FROM pg_stat_wal \gset - -CREATE TABLE test_stats_temp AS SELECT 17; -DROP TABLE test_stats_temp; - --- Checkpoint twice: The checkpointer reports stats after reporting completion --- of the checkpoint. But after a second checkpoint we'll see at least the --- results of the first. -CHECKPOINT; -CHECKPOINT; - -SELECT checkpoints_req > :rqst_ckpts_before FROM pg_stat_bgwriter; -SELECT wal_bytes > :wal_bytes_before FROM pg_stat_wal; - - ------ --- Test that resetting stats works for reset timestamp ------ - --- Test that reset_slru with a specified SLRU works. -SELECT stats_reset AS slru_commit_ts_reset_ts FROM pg_stat_slru WHERE name = 'CommitTs' \gset -SELECT stats_reset AS slru_notify_reset_ts FROM pg_stat_slru WHERE name = 'Notify' \gset -SELECT pg_stat_reset_slru('CommitTs'); -SELECT stats_reset > :'slru_commit_ts_reset_ts'::timestamptz FROM pg_stat_slru WHERE name = 'CommitTs'; -SELECT stats_reset AS slru_commit_ts_reset_ts FROM pg_stat_slru WHERE name = 'CommitTs' \gset - --- Test that multiple SLRUs are reset when no specific SLRU provided to reset function -SELECT pg_stat_reset_slru(NULL); -SELECT stats_reset > :'slru_commit_ts_reset_ts'::timestamptz FROM pg_stat_slru WHERE name = 'CommitTs'; -SELECT stats_reset > :'slru_notify_reset_ts'::timestamptz FROM pg_stat_slru WHERE name = 'Notify'; - --- Test that reset_shared with archiver specified as the stats type works -SELECT stats_reset AS archiver_reset_ts FROM pg_stat_archiver \gset -SELECT pg_stat_reset_shared('archiver'); -SELECT stats_reset > :'archiver_reset_ts'::timestamptz FROM pg_stat_archiver; -SELECT stats_reset AS archiver_reset_ts FROM pg_stat_archiver \gset - --- Test that reset_shared with bgwriter specified as the stats type works -SELECT stats_reset AS bgwriter_reset_ts FROM pg_stat_bgwriter \gset -SELECT pg_stat_reset_shared('bgwriter'); -SELECT stats_reset > :'bgwriter_reset_ts'::timestamptz FROM pg_stat_bgwriter; -SELECT stats_reset AS bgwriter_reset_ts FROM pg_stat_bgwriter \gset - --- Test that reset_shared with wal specified as the stats type works -SELECT stats_reset AS wal_reset_ts FROM pg_stat_wal \gset -SELECT pg_stat_reset_shared('wal'); -SELECT stats_reset > :'wal_reset_ts'::timestamptz FROM pg_stat_wal; -SELECT stats_reset AS wal_reset_ts FROM pg_stat_wal \gset - --- Test that reset_shared with no specified stats type doesn't reset anything -SELECT pg_stat_reset_shared(NULL); -SELECT stats_reset = :'archiver_reset_ts'::timestamptz FROM pg_stat_archiver; -SELECT stats_reset = :'bgwriter_reset_ts'::timestamptz FROM pg_stat_bgwriter; -SELECT stats_reset = :'wal_reset_ts'::timestamptz FROM pg_stat_wal; - --- Test that reset works for pg_stat_database - --- Since pg_stat_database stats_reset starts out as NULL, reset it once first so we have something to compare it to -SELECT pg_stat_reset(); -SELECT stats_reset AS db_reset_ts FROM pg_stat_database WHERE datname = (SELECT current_database()) \gset -SELECT pg_stat_reset(); -SELECT stats_reset > :'db_reset_ts'::timestamptz FROM pg_stat_database WHERE datname = (SELECT current_database()); - - ----- --- pg_stat_get_snapshot_timestamp behavior ----- -BEGIN; -SET LOCAL stats_fetch_consistency = snapshot; --- no snapshot yet, return NULL -SELECT pg_stat_get_snapshot_timestamp(); --- any attempt at accessing stats will build snapshot -SELECT pg_stat_get_function_calls(0); -SELECT pg_stat_get_snapshot_timestamp() >= NOW(); --- shows NULL again after clearing -SELECT pg_stat_clear_snapshot(); -SELECT pg_stat_get_snapshot_timestamp(); -COMMIT; - ----- --- pg_stat_have_stats behavior ----- --- fixed-numbered stats exist -SELECT pg_stat_have_stats('bgwriter', 0, 0); --- unknown stats kinds error out -SELECT pg_stat_have_stats('zaphod', 0, 0); --- db stats have objoid 0 -SELECT pg_stat_have_stats('database', (SELECT oid FROM pg_database WHERE datname = current_database()), 1); -SELECT pg_stat_have_stats('database', (SELECT oid FROM pg_database WHERE datname = current_database()), 0); - - --- ensure that stats accessors handle NULL input correctly -SELECT pg_stat_get_replication_slot(NULL); -SELECT pg_stat_get_subscription_stats(NULL); - - --- End of Stats Test diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fstats_ext.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fstats_ext.sql deleted file mode 100644 index 6b954c9e50..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fstats_ext.sql +++ /dev/null @@ -1,1639 +0,0 @@ --- Generic extended statistics support - --- --- Note: tables for which we check estimated row counts should be created --- with autovacuum_enabled = off, so that we don't have unstable results --- from auto-analyze happening when we didn't expect it. --- - --- check the number of estimated/actual rows in the top node -create function check_estimated_rows(text) returns table (estimated int, actual int) -language plpgsql as -$$ -declare - ln text; - tmp text[]; - first_row bool := true; -begin - for ln in - execute format('explain analyze %s', $1) - loop - if first_row then - first_row := false; - tmp := regexp_match(ln, 'rows=(\d*) .* rows=(\d*)'); - return query select tmp[1]::int, tmp[2]::int; - end if; - end loop; -end; -$$; - --- Verify failures -CREATE TABLE ext_stats_test (x text, y int, z int); -CREATE STATISTICS tst; -CREATE STATISTICS tst ON a, b; -CREATE STATISTICS tst FROM sometab; -CREATE STATISTICS tst ON a, b FROM nonexistent; -CREATE STATISTICS tst ON a, b FROM ext_stats_test; -CREATE STATISTICS tst ON x, x, y FROM ext_stats_test; -CREATE STATISTICS tst ON x, x, y, x, x, y, x, x, y FROM ext_stats_test; -CREATE STATISTICS tst ON x, x, y, x, x, (x || 'x'), (y + 1), (x || 'x'), (x || 'x'), (y + 1) FROM ext_stats_test; -CREATE STATISTICS tst ON (x || 'x'), (x || 'x'), (y + 1), (x || 'x'), (x || 'x'), (y + 1), (x || 'x'), (x || 'x'), (y + 1) FROM ext_stats_test; -CREATE STATISTICS tst ON (x || 'x'), (x || 'x'), y FROM ext_stats_test; -CREATE STATISTICS tst (unrecognized) ON x, y FROM ext_stats_test; --- incorrect expressions -CREATE STATISTICS tst ON (y) FROM ext_stats_test; -- single column reference -CREATE STATISTICS tst ON y + z FROM ext_stats_test; -- missing parentheses -CREATE STATISTICS tst ON (x, y) FROM ext_stats_test; -- tuple expression -DROP TABLE ext_stats_test; - --- Ensure stats are dropped sanely, and test IF NOT EXISTS while at it -CREATE TABLE ab1 (a INTEGER, b INTEGER, c INTEGER); -CREATE STATISTICS IF NOT EXISTS ab1_a_b_stats ON a, b FROM ab1; -COMMENT ON STATISTICS ab1_a_b_stats IS 'new comment'; -CREATE ROLE regress_stats_ext; -SET SESSION AUTHORIZATION regress_stats_ext; -COMMENT ON STATISTICS ab1_a_b_stats IS 'changed comment'; -DROP STATISTICS ab1_a_b_stats; -ALTER STATISTICS ab1_a_b_stats RENAME TO ab1_a_b_stats_new; -RESET SESSION AUTHORIZATION; -DROP ROLE regress_stats_ext; - -CREATE STATISTICS IF NOT EXISTS ab1_a_b_stats ON a, b FROM ab1; -DROP STATISTICS ab1_a_b_stats; - -CREATE SCHEMA regress_schema_2; -CREATE STATISTICS regress_schema_2.ab1_a_b_stats ON a, b FROM ab1; - --- Let's also verify the pg_get_statisticsobjdef output looks sane. -SELECT pg_get_statisticsobjdef(oid) FROM pg_statistic_ext WHERE stxname = 'ab1_a_b_stats'; - -DROP STATISTICS regress_schema_2.ab1_a_b_stats; - --- Ensure statistics are dropped when columns are -CREATE STATISTICS ab1_b_c_stats ON b, c FROM ab1; -CREATE STATISTICS ab1_a_b_c_stats ON a, b, c FROM ab1; -CREATE STATISTICS ab1_b_a_stats ON b, a FROM ab1; -ALTER TABLE ab1 DROP COLUMN a; -\d ab1 --- Ensure statistics are dropped when table is -SELECT stxname FROM pg_statistic_ext WHERE stxname LIKE 'ab1%'; -DROP TABLE ab1; -SELECT stxname FROM pg_statistic_ext WHERE stxname LIKE 'ab1%'; - --- Ensure things work sanely with SET STATISTICS 0 -CREATE TABLE ab1 (a INTEGER, b INTEGER); -ALTER TABLE ab1 ALTER a SET STATISTICS 0; -INSERT INTO ab1 SELECT a, a%23 FROM generate_series(1, 1000) a; -CREATE STATISTICS ab1_a_b_stats ON a, b FROM ab1; -ANALYZE ab1; -ALTER TABLE ab1 ALTER a SET STATISTICS -1; --- setting statistics target 0 skips the statistics, without printing any message, so check catalog -ALTER STATISTICS ab1_a_b_stats SET STATISTICS 0; -\d ab1 -ANALYZE ab1; -SELECT stxname, stxdndistinct, stxddependencies, stxdmcv, stxdinherit - FROM pg_statistic_ext s LEFT JOIN pg_statistic_ext_data d ON (d.stxoid = s.oid) - WHERE s.stxname = 'ab1_a_b_stats'; -ALTER STATISTICS ab1_a_b_stats SET STATISTICS -1; -\d+ ab1 --- partial analyze doesn't build stats either -ANALYZE ab1 (a); -ANALYZE ab1; -DROP TABLE ab1; -ALTER STATISTICS ab1_a_b_stats SET STATISTICS 0; -ALTER STATISTICS IF EXISTS ab1_a_b_stats SET STATISTICS 0; - --- Ensure we can build statistics for tables with inheritance. -CREATE TABLE ab1 (a INTEGER, b INTEGER); -CREATE TABLE ab1c () INHERITS (ab1); -INSERT INTO ab1 VALUES (1,1); -CREATE STATISTICS ab1_a_b_stats ON a, b FROM ab1; -ANALYZE ab1; -DROP TABLE ab1 CASCADE; - --- Tests for stats with inheritance -CREATE TABLE stxdinh(a int, b int); -CREATE TABLE stxdinh1() INHERITS(stxdinh); -CREATE TABLE stxdinh2() INHERITS(stxdinh); -INSERT INTO stxdinh SELECT mod(a,50), mod(a,100) FROM generate_series(0, 1999) a; -INSERT INTO stxdinh1 SELECT mod(a,100), mod(a,100) FROM generate_series(0, 999) a; -INSERT INTO stxdinh2 SELECT mod(a,100), mod(a,100) FROM generate_series(0, 999) a; -VACUUM ANALYZE stxdinh, stxdinh1, stxdinh2; --- Ensure non-inherited stats are not applied to inherited query --- Without stats object, it looks like this -SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinh* GROUP BY 1, 2'); -SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinh* WHERE a = 0 AND b = 0'); -CREATE STATISTICS stxdinh ON a, b FROM stxdinh; -VACUUM ANALYZE stxdinh, stxdinh1, stxdinh2; --- See if the extended stats affect the estimates -SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinh* GROUP BY 1, 2'); --- Dependencies are applied at individual relations (within append), so --- this estimate changes a bit because we improve estimates for the parent -SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinh* WHERE a = 0 AND b = 0'); --- Ensure correct (non-inherited) stats are applied to inherited query -SELECT * FROM check_estimated_rows('SELECT a, b FROM ONLY stxdinh GROUP BY 1, 2'); -SELECT * FROM check_estimated_rows('SELECT a, b FROM ONLY stxdinh WHERE a = 0 AND b = 0'); -DROP TABLE stxdinh, stxdinh1, stxdinh2; - --- Ensure inherited stats ARE applied to inherited query in partitioned table -CREATE TABLE stxdinp(i int, a int, b int) PARTITION BY RANGE (i); -CREATE TABLE stxdinp1 PARTITION OF stxdinp FOR VALUES FROM (1) TO (100); -INSERT INTO stxdinp SELECT 1, a/100, a/100 FROM generate_series(1, 999) a; -CREATE STATISTICS stxdinp ON a, b FROM stxdinp; -VACUUM ANALYZE stxdinp; -- partitions are processed recursively -SELECT 1 FROM pg_statistic_ext WHERE stxrelid = 'stxdinp'::regclass; -SELECT * FROM check_estimated_rows('SELECT a, b FROM stxdinp GROUP BY 1, 2'); -DROP TABLE stxdinp; - --- basic test for statistics on expressions -CREATE TABLE ab1 (a INTEGER, b INTEGER, c TIMESTAMP, d TIMESTAMPTZ); - --- expression stats may be built on a single expression column -CREATE STATISTICS ab1_exprstat_1 ON (a+b) FROM ab1; - --- with a single expression, we only enable expression statistics -CREATE STATISTICS ab1_exprstat_2 ON (a+b) FROM ab1; -SELECT stxkind FROM pg_statistic_ext WHERE stxname = 'ab1_exprstat_2'; - --- adding anything to the expression builds all statistics kinds -CREATE STATISTICS ab1_exprstat_3 ON (a+b), a FROM ab1; -SELECT stxkind FROM pg_statistic_ext WHERE stxname = 'ab1_exprstat_3'; - --- date_trunc on timestamptz is not immutable, but that should not matter -CREATE STATISTICS ab1_exprstat_4 ON date_trunc('day', d) FROM ab1; - --- date_trunc on timestamp is immutable -CREATE STATISTICS ab1_exprstat_5 ON date_trunc('day', c) FROM ab1; - --- insert some data and run analyze, to test that these cases build properly -INSERT INTO ab1 -SELECT - generate_series(1,10), - generate_series(1,10), - generate_series('2020-10-01'::timestamp, '2020-10-10'::timestamp, interval '1 day'), - generate_series('2020-10-01'::timestamptz, '2020-10-10'::timestamptz, interval '1 day'); -ANALYZE ab1; -DROP TABLE ab1; - --- Verify supported object types for extended statistics -CREATE schema tststats; - -CREATE TABLE tststats.t (a int, b int, c text); -CREATE INDEX ti ON tststats.t (a, b); -CREATE SEQUENCE tststats.s; -CREATE VIEW tststats.v AS SELECT * FROM tststats.t; -CREATE MATERIALIZED VIEW tststats.mv AS SELECT * FROM tststats.t; -CREATE TYPE tststats.ty AS (a int, b int, c text); -CREATE FOREIGN DATA WRAPPER extstats_dummy_fdw; -CREATE SERVER extstats_dummy_srv FOREIGN DATA WRAPPER extstats_dummy_fdw; -CREATE FOREIGN TABLE tststats.f (a int, b int, c text) SERVER extstats_dummy_srv; -CREATE TABLE tststats.pt (a int, b int, c text) PARTITION BY RANGE (a, b); -CREATE TABLE tststats.pt1 PARTITION OF tststats.pt FOR VALUES FROM (-10, -10) TO (10, 10); - -CREATE STATISTICS tststats.s1 ON a, b FROM tststats.t; -CREATE STATISTICS tststats.s2 ON a, b FROM tststats.ti; -CREATE STATISTICS tststats.s3 ON a, b FROM tststats.s; -CREATE STATISTICS tststats.s4 ON a, b FROM tststats.v; -CREATE STATISTICS tststats.s5 ON a, b FROM tststats.mv; -CREATE STATISTICS tststats.s6 ON a, b FROM tststats.ty; -CREATE STATISTICS tststats.s7 ON a, b FROM tststats.f; -CREATE STATISTICS tststats.s8 ON a, b FROM tststats.pt; -CREATE STATISTICS tststats.s9 ON a, b FROM tststats.pt1; -DO $$ -DECLARE - relname text := reltoastrelid::regclass FROM pg_class WHERE oid = 'tststats.t'::regclass; -BEGIN - EXECUTE 'CREATE STATISTICS tststats.s10 ON a, b FROM ' || relname; -EXCEPTION WHEN wrong_object_type THEN - RAISE NOTICE 'stats on toast table not created'; -END; -$$; - -DROP SCHEMA tststats CASCADE; -DROP FOREIGN DATA WRAPPER extstats_dummy_fdw CASCADE; - --- n-distinct tests -CREATE TABLE ndistinct ( - filler1 TEXT, - filler2 NUMERIC, - a INT, - b INT, - filler3 DATE, - c INT, - d INT -) -WITH (autovacuum_enabled = off); - --- over-estimates when using only per-column statistics -INSERT INTO ndistinct (a, b, c, filler1) - SELECT i/100, i/100, i/100, cash_words((i/100)::money) - FROM generate_series(1,1000) s(i); - -ANALYZE ndistinct; - --- Group Aggregate, due to over-estimate of the number of groups -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY b, c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (a+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100), (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (a+1), (b+100)'); - --- correct command -CREATE STATISTICS s10 ON a, b, c FROM ndistinct; - -ANALYZE ndistinct; - -SELECT s.stxkind, d.stxdndistinct - FROM pg_statistic_ext s, pg_statistic_ext_data d - WHERE s.stxrelid = 'ndistinct'::regclass - AND d.stxoid = s.oid; - --- minor improvement, make sure the ctid does not break the matching -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY ctid, a, b'); - --- Hash Aggregate, thanks to estimates improved by the statistic -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY b, c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c'); - --- partial improvement (match on attributes) -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (a+1)'); - --- expressions - no improvement -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100), (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (a+1), (b+100)'); - --- last two plans keep using Group Aggregate, because 'd' is not covered --- by the statistic and while it's NULL-only we assume 200 values for it -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY b, c, d'); - -TRUNCATE TABLE ndistinct; - --- under-estimates when using only per-column statistics -INSERT INTO ndistinct (a, b, c, filler1) - SELECT mod(i,13), mod(i,17), mod(i,19), - cash_words(mod(i,23)::int::money) - FROM generate_series(1,1000) s(i); - -ANALYZE ndistinct; - -SELECT s.stxkind, d.stxdndistinct - FROM pg_statistic_ext s, pg_statistic_ext_data d - WHERE s.stxrelid = 'ndistinct'::regclass - AND d.stxoid = s.oid; - --- correct estimates -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (a+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100), (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (a+1), (b+100)'); - -DROP STATISTICS s10; - -SELECT s.stxkind, d.stxdndistinct - FROM pg_statistic_ext s, pg_statistic_ext_data d - WHERE s.stxrelid = 'ndistinct'::regclass - AND d.stxoid = s.oid; - --- dropping the statistics results in under-estimates -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY b, c, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, d'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (a+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100), (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (a+1), (b+100)'); - --- ndistinct estimates with statistics on expressions -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100), (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (a+1), (b+100)'); - -CREATE STATISTICS s10 (ndistinct) ON (a+1), (b+100), (2*c) FROM ndistinct; - -ANALYZE ndistinct; - -SELECT s.stxkind, d.stxdndistinct - FROM pg_statistic_ext s, pg_statistic_ext_data d - WHERE s.stxrelid = 'ndistinct'::regclass - AND d.stxoid = s.oid; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a+1), (b+100), (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (a+1), (b+100)'); - -DROP STATISTICS s10; - --- a mix of attributes and expressions -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (2*c)'); - -CREATE STATISTICS s10 (ndistinct) ON a, b, (2*c) FROM ndistinct; - -ANALYZE ndistinct; - -SELECT s.stxkind, d.stxdndistinct - FROM pg_statistic_ext s, pg_statistic_ext_data d - WHERE s.stxrelid = 'ndistinct'::regclass - AND d.stxoid = s.oid; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (2*c)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (2*c)'); - -DROP STATISTICS s10; - --- combination of multiple ndistinct statistics, with/without expressions -TRUNCATE ndistinct; - --- two mostly independent groups of columns -INSERT INTO ndistinct (a, b, c, d) - SELECT mod(i,3), mod(i,9), mod(i,5), mod(i,20) - FROM generate_series(1,1000) s(i); - -ANALYZE ndistinct; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1), c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (c*10)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1), c, (d - 1)'); - --- basic statistics on both attributes (no expressions) -CREATE STATISTICS s11 (ndistinct) ON a, b FROM ndistinct; - -CREATE STATISTICS s12 (ndistinct) ON c, d FROM ndistinct; - -ANALYZE ndistinct; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1), c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (c*10)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1), c, (d - 1)'); - - --- replace the second statistics by statistics on expressions - -DROP STATISTICS s12; - -CREATE STATISTICS s12 (ndistinct) ON (c * 10), (d - 1) FROM ndistinct; - -ANALYZE ndistinct; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1), c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (c*10)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1), c, (d - 1)'); - - --- replace the second statistics by statistics on both attributes and expressions - -DROP STATISTICS s12; - -CREATE STATISTICS s12 (ndistinct) ON c, d, (c * 10), (d - 1) FROM ndistinct; - -ANALYZE ndistinct; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1), c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (c*10)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1), c, (d - 1)'); - - --- replace the other statistics by statistics on both attributes and expressions - -DROP STATISTICS s11; - -CREATE STATISTICS s11 (ndistinct) ON a, b, (a*5), (b+1) FROM ndistinct; - -ANALYZE ndistinct; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1), c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (c*10)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1), c, (d - 1)'); - - --- replace statistics by somewhat overlapping ones (this expected to get worse estimate --- because the first statistics shall be applied to 3 columns, and the second one can't --- be really applied) - -DROP STATISTICS s11; -DROP STATISTICS s12; - -CREATE STATISTICS s11 (ndistinct) ON a, b, (a*5), (b+1) FROM ndistinct; -CREATE STATISTICS s12 (ndistinct) ON a, (b+1), (c * 10) FROM ndistinct; - -ANALYZE ndistinct; - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), b'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY (a*5), (b+1), c'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, b, (c*10)'); - -SELECT * FROM check_estimated_rows('SELECT COUNT(*) FROM ndistinct GROUP BY a, (b+1), c, (d - 1)'); - -DROP STATISTICS s11; -DROP STATISTICS s12; - --- functional dependencies tests -CREATE TABLE functional_dependencies ( - filler1 TEXT, - filler2 NUMERIC, - a INT, - b TEXT, - filler3 DATE, - c INT, - d TEXT -) -WITH (autovacuum_enabled = off); - -CREATE INDEX fdeps_ab_idx ON functional_dependencies (a, b); -CREATE INDEX fdeps_abc_idx ON functional_dependencies (a, b, c); - --- random data (no functional dependencies) -INSERT INTO functional_dependencies (a, b, c, filler1) - SELECT mod(i, 5), mod(i, 7), mod(i, 11), i FROM generate_series(1,1000) s(i); - -ANALYZE functional_dependencies; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'' AND c = 1'); - --- create statistics -CREATE STATISTICS func_deps_stat (dependencies) ON a, b, c FROM functional_dependencies; - -ANALYZE functional_dependencies; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'' AND c = 1'); - --- a => b, a => c, b => c -TRUNCATE functional_dependencies; -DROP STATISTICS func_deps_stat; - --- now do the same thing, but with expressions -INSERT INTO functional_dependencies (a, b, c, filler1) - SELECT i, i, i, i FROM generate_series(1,5000) s(i); - -ANALYZE functional_dependencies; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE mod(a, 11) = 1 AND mod(b::int, 13) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE mod(a, 11) = 1 AND mod(b::int, 13) = 1 AND mod(c, 7) = 1'); - --- create statistics -CREATE STATISTICS func_deps_stat (dependencies) ON (mod(a,11)), (mod(b::int, 13)), (mod(c, 7)) FROM functional_dependencies; - -ANALYZE functional_dependencies; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE mod(a, 11) = 1 AND mod(b::int, 13) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE mod(a, 11) = 1 AND mod(b::int, 13) = 1 AND mod(c, 7) = 1'); - --- a => b, a => c, b => c -TRUNCATE functional_dependencies; -DROP STATISTICS func_deps_stat; - -INSERT INTO functional_dependencies (a, b, c, filler1) - SELECT mod(i,100), mod(i,50), mod(i,25), i FROM generate_series(1,5000) s(i); - -ANALYZE functional_dependencies; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'' AND c = 1'); - --- IN -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 51, 52) AND b IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 51, 52) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 26, 51, 76) AND b IN (''1'', ''26'') AND c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 26, 51, 76) AND b IN (''1'', ''26'') AND c IN (1)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 26, 27, 51, 52, 76, 77) AND b IN (''1'', ''2'', ''26'', ''27'') AND c IN (1, 2)'); - --- OR clauses referencing the same attribute -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 51) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 51) AND (b = ''1'' OR b = ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 2 OR a = 51 OR a = 52) AND (b = ''1'' OR b = ''2'')'); - --- OR clauses referencing different attributes -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR b = ''1'') AND b = ''1'''); - --- ANY -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 51]) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 51]) AND b = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 26, 51, 76]) AND b = ANY (ARRAY[''1'', ''26'']) AND c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 26, 51, 76]) AND b = ANY (ARRAY[''1'', ''26'']) AND c = ANY (ARRAY[1])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 2, 26, 27, 51, 52, 76, 77]) AND b = ANY (ARRAY[''1'', ''2'', ''26'', ''27'']) AND c = ANY (ARRAY[1, 2])'); - --- ANY with inequalities should not benefit from functional dependencies -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a < ANY (ARRAY[1, 51]) AND b > ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a >= ANY (ARRAY[1, 51]) AND b <= ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a <= ANY (ARRAY[1, 2, 51, 52]) AND b >= ANY (ARRAY[''1'', ''2''])'); - --- ALL (should not benefit from functional dependencies) -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ALL (ARRAY[''1''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ALL (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 51, 52) AND b = ALL (ARRAY[''1'', ''2''])'); - --- create statistics -CREATE STATISTICS func_deps_stat (dependencies) ON a, b, c FROM functional_dependencies; - -ANALYZE functional_dependencies; - --- print the detected dependencies -SELECT dependencies FROM pg_stats_ext WHERE statistics_name = 'func_deps_stat'; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'' AND c = 1'); - --- IN -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 51, 52) AND b IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 51, 52) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 26, 51, 76) AND b IN (''1'', ''26'') AND c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 26, 51, 76) AND b IN (''1'', ''26'') AND c IN (1)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 26, 27, 51, 52, 76, 77) AND b IN (''1'', ''2'', ''26'', ''27'') AND c IN (1, 2)'); - --- OR clauses referencing the same attribute -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 51) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 51) AND (b = ''1'' OR b = ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR a = 2 OR a = 51 OR a = 52) AND (b = ''1'' OR b = ''2'')'); - --- OR clauses referencing different attributes are incompatible -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a = 1 OR b = ''1'') AND b = ''1'''); - --- ANY -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 51]) AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 51]) AND b = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 26, 51, 76]) AND b = ANY (ARRAY[''1'', ''26'']) AND c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 26, 51, 76]) AND b = ANY (ARRAY[''1'', ''26'']) AND c = ANY (ARRAY[1])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = ANY (ARRAY[1, 2, 26, 27, 51, 52, 76, 77]) AND b = ANY (ARRAY[''1'', ''2'', ''26'', ''27'']) AND c = ANY (ARRAY[1, 2])'); - --- ANY with inequalities should not benefit from functional dependencies -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a < ANY (ARRAY[1, 51]) AND b > ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a >= ANY (ARRAY[1, 51]) AND b <= ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a <= ANY (ARRAY[1, 2, 51, 52]) AND b >= ANY (ARRAY[''1'', ''2''])'); - --- ALL (should not benefit from functional dependencies) -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ALL (ARRAY[''1''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ALL (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 2, 51, 52) AND b = ALL (ARRAY[''1'', ''2''])'); - --- changing the type of column c causes all its stats to be dropped, reverting --- to default estimates without any statistics, i.e. 0.5% selectivity for each --- condition -ALTER TABLE functional_dependencies ALTER COLUMN c TYPE numeric; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'' AND c = 1'); - -ANALYZE functional_dependencies; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a = 1 AND b = ''1'' AND c = 1'); - -DROP STATISTICS func_deps_stat; - --- now try functional dependencies with expressions - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = 2 AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = 2 AND upper(b) = ''1'' AND (c + 1) = 2'); - --- IN -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 52, 102, 152) AND upper(b) IN (''1'', ''26'') AND (c + 1) = 2'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 52, 102, 152) AND upper(b) IN (''1'', ''26'') AND (c + 1) IN (2)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 52, 54, 102, 104, 152, 154) AND upper(b) IN (''1'', ''2'', ''26'', ''27'') AND (c + 1) IN (2, 3)'); - --- OR clauses referencing the same attribute -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR (a * 2) = 102) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR (a * 2) = 102) AND (upper(b) = ''1'' OR upper(b) = ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR (a * 2) = 4 OR (a * 2) = 102 OR (a * 2) = 104) AND (upper(b) = ''1'' OR upper(b) = ''2'')'); - --- OR clauses referencing different attributes -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR upper(b) = ''1'') AND upper(b) = ''1'''); - --- ANY -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 102]) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 102]) AND upper(b) = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 4, 102, 104]) AND upper(b) = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 52, 102, 152]) AND upper(b) = ANY (ARRAY[''1'', ''26'']) AND (c + 1) = 2'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 52, 102, 152]) AND upper(b) = ANY (ARRAY[''1'', ''26'']) AND (c + 1) = ANY (ARRAY[2])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 4, 52, 54, 102, 104, 152, 154]) AND upper(b) = ANY (ARRAY[''1'', ''2'', ''26'', ''27'']) AND (c + 1) = ANY (ARRAY[2, 3])'); - --- ANY with inequalities should not benefit from functional dependencies --- the estimates however improve thanks to having expression statistics -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) < ANY (ARRAY[2, 102]) AND upper(b) > ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) >= ANY (ARRAY[2, 102]) AND upper(b) <= ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) <= ANY (ARRAY[2, 4, 102, 104]) AND upper(b) >= ANY (ARRAY[''1'', ''2''])'); - --- ALL (should not benefit from functional dependencies) -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ALL (ARRAY[''1''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ALL (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) = ALL (ARRAY[''1'', ''2''])'); - --- create statistics on expressions -CREATE STATISTICS func_deps_stat (dependencies) ON (a * 2), upper(b), (c + 1) FROM functional_dependencies; - -ANALYZE functional_dependencies; - --- print the detected dependencies -SELECT dependencies FROM pg_stats_ext WHERE statistics_name = 'func_deps_stat'; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = 2 AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = 2 AND upper(b) = ''1'' AND (c + 1) = 2'); - --- IN -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) IN (''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 52, 102, 152) AND upper(b) IN (''1'', ''26'') AND (c + 1) = 2'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 52, 102, 152) AND upper(b) IN (''1'', ''26'') AND (c + 1) IN (2)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 52, 54, 102, 104, 152, 154) AND upper(b) IN (''1'', ''2'', ''26'', ''27'') AND (c + 1) IN (2, 3)'); - --- OR clauses referencing the same attribute -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR (a * 2) = 102) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR (a * 2) = 102) AND (upper(b) = ''1'' OR upper(b) = ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR (a * 2) = 4 OR (a * 2) = 102 OR (a * 2) = 104) AND (upper(b) = ''1'' OR upper(b) = ''2'')'); - --- OR clauses referencing different attributes -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE ((a * 2) = 2 OR upper(b) = ''1'') AND upper(b) = ''1'''); - --- ANY -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 102]) AND upper(b) = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 102]) AND upper(b) = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 4, 102, 104]) AND upper(b) = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 52, 102, 152]) AND upper(b) = ANY (ARRAY[''1'', ''26'']) AND (c + 1) = 2'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 52, 102, 152]) AND upper(b) = ANY (ARRAY[''1'', ''26'']) AND (c + 1) = ANY (ARRAY[2])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) = ANY (ARRAY[2, 4, 52, 54, 102, 104, 152, 154]) AND upper(b) = ANY (ARRAY[''1'', ''2'', ''26'', ''27'']) AND (c + 1) = ANY (ARRAY[2, 3])'); - --- ANY with inequalities should not benefit from functional dependencies --- the estimates however improve thanks to having expression statistics -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) < ANY (ARRAY[2, 102]) AND upper(b) > ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) >= ANY (ARRAY[2, 102]) AND upper(b) <= ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) <= ANY (ARRAY[2, 4, 102, 104]) AND upper(b) >= ANY (ARRAY[''1'', ''2''])'); - --- ALL (should not benefit from functional dependencies) -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ALL (ARRAY[''1''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 102) AND upper(b) = ALL (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE (a * 2) IN (2, 4, 102, 104) AND upper(b) = ALL (ARRAY[''1'', ''2''])'); - --- check the ability to use multiple functional dependencies -CREATE TABLE functional_dependencies_multi ( - a INTEGER, - b INTEGER, - c INTEGER, - d INTEGER -) -WITH (autovacuum_enabled = off); - -INSERT INTO functional_dependencies_multi (a, b, c, d) - SELECT - mod(i,7), - mod(i,7), - mod(i,11), - mod(i,11) - FROM generate_series(1,5000) s(i); - -ANALYZE functional_dependencies_multi; - --- estimates without any functional dependencies -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE a = 0 AND b = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE 0 = a AND 0 = b'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE a = 0 AND b = 0 AND c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE 0 = a AND b = 0 AND 0 = c AND d = 0'); - --- create separate functional dependencies -CREATE STATISTICS functional_dependencies_multi_1 (dependencies) ON a, b FROM functional_dependencies_multi; -CREATE STATISTICS functional_dependencies_multi_2 (dependencies) ON c, d FROM functional_dependencies_multi; - -ANALYZE functional_dependencies_multi; - -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE a = 0 AND b = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE 0 = a AND 0 = b'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE a = 0 AND b = 0 AND c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies_multi WHERE 0 = a AND b = 0 AND 0 = c AND d = 0'); - -DROP TABLE functional_dependencies_multi; - --- MCV lists -CREATE TABLE mcv_lists ( - filler1 TEXT, - filler2 NUMERIC, - a INT, - b VARCHAR, - filler3 DATE, - c INT, - d TEXT -) -WITH (autovacuum_enabled = off); - --- random data (no MCV list) -INSERT INTO mcv_lists (a, b, c, filler1) - SELECT mod(i,37), mod(i,41), mod(i,43), mod(i,47) FROM generate_series(1,5000) s(i); - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'' AND c = 1'); - --- create statistics -CREATE STATISTICS mcv_lists_stats (mcv) ON a, b, c FROM mcv_lists; - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'' AND c = 1'); - -TRUNCATE mcv_lists; -DROP STATISTICS mcv_lists_stats; - --- random data (no MCV list), but with expression -INSERT INTO mcv_lists (a, b, c, filler1) - SELECT i, i, i, i FROM generate_series(1,1000) s(i); - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,7) = 1 AND mod(b::int,11) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,7) = 1 AND mod(b::int,11) = 1 AND mod(c,13) = 1'); - --- create statistics -CREATE STATISTICS mcv_lists_stats (mcv) ON (mod(a,7)), (mod(b::int,11)), (mod(c,13)) FROM mcv_lists; - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,7) = 1 AND mod(b::int,11) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,7) = 1 AND mod(b::int,11) = 1 AND mod(c,13) = 1'); - --- 100 distinct combinations, all in the MCV list -TRUNCATE mcv_lists; -DROP STATISTICS mcv_lists_stats; - -INSERT INTO mcv_lists (a, b, c, filler1) - SELECT mod(i,100), mod(i,50), mod(i,25), i FROM generate_series(1,5000) s(i); - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 = a AND ''1'' = b'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 1 AND b < ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 > a AND ''1'' > b'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= 0 AND b <= ''0'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 0 >= a AND ''0'' >= b'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'' AND c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 5 AND b < ''1'' AND c < 5'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 5 AND ''1'' > b AND 5 > c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= 4 AND b <= ''0'' AND c <= 4'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 4 >= a AND ''0'' >= b AND 4 >= c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1 OR d IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (1, 2, 51, 52) AND b IN ( ''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (1, 2, 51, 52, NULL) AND b IN ( ''1'', ''2'', NULL)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = ANY (ARRAY[1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = ANY (ARRAY[NULL, 1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2'', NULL])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= ANY (ARRAY[1, 2, 3]) AND b IN (''1'', ''2'', ''3'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= ANY (ARRAY[1, NULL, 2, 3]) AND b IN (''1'', ''2'', NULL, ''3'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND c > ANY (ARRAY[1, 2, 3])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND c > ANY (ARRAY[1, 2, 3, NULL])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND b IN (''1'', ''2'', ''3'') AND c > ANY (ARRAY[1, 2, 3])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND b IN (''1'', ''2'', NULL, ''3'') AND c > ANY (ARRAY[1, 2, NULL, 3])'); - --- create statistics -CREATE STATISTICS mcv_lists_stats (mcv) ON a, b, c FROM mcv_lists; - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 = a AND ''1'' = b'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 1 AND b < ''1'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 > a AND ''1'' > b'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= 0 AND b <= ''0'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 0 >= a AND ''0'' >= b'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'' AND c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 5 AND b < ''1'' AND c < 5'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < 5 AND ''1'' > b AND 5 > c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= 4 AND b <= ''0'' AND c <= 4'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 4 >= a AND ''0'' >= b AND 4 >= c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1 OR d IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1 OR d IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (1, 2, 51, 52) AND b IN ( ''1'', ''2'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (1, 2, 51, 52, NULL) AND b IN ( ''1'', ''2'', NULL)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = ANY (ARRAY[1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2''])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = ANY (ARRAY[NULL, 1, 2, 51, 52]) AND b = ANY (ARRAY[''1'', ''2'', NULL])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= ANY (ARRAY[1, 2, 3]) AND b IN (''1'', ''2'', ''3'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a <= ANY (ARRAY[1, NULL, 2, 3]) AND b IN (''1'', ''2'', NULL, ''3'')'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND c > ANY (ARRAY[1, 2, 3])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND c > ANY (ARRAY[1, 2, 3, NULL])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND b IN (''1'', ''2'', ''3'') AND c > ANY (ARRAY[1, 2, 3])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a < ALL (ARRAY[4, 5]) AND b IN (''1'', ''2'', NULL, ''3'') AND c > ANY (ARRAY[1, 2, NULL, 3])'); - --- check change of unrelated column type does not reset the MCV statistics -ALTER TABLE mcv_lists ALTER COLUMN d TYPE VARCHAR(64); - -SELECT d.stxdmcv IS NOT NULL - FROM pg_statistic_ext s, pg_statistic_ext_data d - WHERE s.stxname = 'mcv_lists_stats' - AND d.stxoid = s.oid; - --- check change of column type resets the MCV statistics -ALTER TABLE mcv_lists ALTER COLUMN c TYPE numeric; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'''); - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 AND b = ''1'''); - - --- 100 distinct combinations, all in the MCV list, but with expressions -TRUNCATE mcv_lists; -DROP STATISTICS mcv_lists_stats; - -INSERT INTO mcv_lists (a, b, c, filler1) - SELECT i, i, i, i FROM generate_series(1,1000) s(i); - -ANALYZE mcv_lists; - --- without any stats on the expressions, we have to use default selectivities, which --- is why the estimates here are different from the pre-computed case above - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 = mod(a,20) AND 1 = mod(b::int,10)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) < 1 AND mod(b::int,10) < 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 > mod(a,20) AND 1 > mod(b::int,10)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1 AND mod(c,5) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 OR mod(b::int,10) = 1 OR mod(c,25) = 1 OR d IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) IN (1, 2, 51, 52, NULL) AND mod(b::int,10) IN ( 1, 2, NULL)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = ANY (ARRAY[1, 2, 51, 52]) AND mod(b::int,10) = ANY (ARRAY[1, 2])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) <= ANY (ARRAY[1, NULL, 2, 3]) AND mod(b::int,10) IN (1, 2, NULL, 3)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) < ALL (ARRAY[4, 5]) AND mod(b::int,10) IN (1, 2, 3) AND mod(c,5) > ANY (ARRAY[1, 2, 3])'); - --- create statistics with expressions only (we create three separate stats, in order not to build more complex extended stats) -CREATE STATISTICS mcv_lists_stats_1 ON (mod(a,20)) FROM mcv_lists; -CREATE STATISTICS mcv_lists_stats_2 ON (mod(b::int,10)) FROM mcv_lists; -CREATE STATISTICS mcv_lists_stats_3 ON (mod(c,5)) FROM mcv_lists; - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 = mod(a,20) AND 1 = mod(b::int,10)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) < 1 AND mod(b::int,10) < 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 > mod(a,20) AND 1 > mod(b::int,10)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1 AND mod(c,5) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 OR mod(b::int,10) = 1 OR mod(c,25) = 1 OR d IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) IN (1, 2, 51, 52, NULL) AND mod(b::int,10) IN ( 1, 2, NULL)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = ANY (ARRAY[1, 2, 51, 52]) AND mod(b::int,10) = ANY (ARRAY[1, 2])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) <= ANY (ARRAY[1, NULL, 2, 3]) AND mod(b::int,10) IN (1, 2, NULL, 3)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) < ALL (ARRAY[4, 5]) AND mod(b::int,10) IN (1, 2, 3) AND mod(c,5) > ANY (ARRAY[1, 2, 3])'); - -DROP STATISTICS mcv_lists_stats_1; -DROP STATISTICS mcv_lists_stats_2; -DROP STATISTICS mcv_lists_stats_3; - --- create statistics with both MCV and expressions -CREATE STATISTICS mcv_lists_stats (mcv) ON (mod(a,20)), (mod(b::int,10)), (mod(c,5)) FROM mcv_lists; - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 = mod(a,20) AND 1 = mod(b::int,10)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) < 1 AND mod(b::int,10) < 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE 1 > mod(a,20) AND 1 > mod(b::int,10)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 AND mod(b::int,10) = 1 AND mod(c,5) = 1'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 OR mod(b::int,10) = 1 OR mod(c,25) = 1 OR d IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) IN (1, 2, 51, 52, NULL) AND mod(b::int,10) IN ( 1, 2, NULL)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = ANY (ARRAY[1, 2, 51, 52]) AND mod(b::int,10) = ANY (ARRAY[1, 2])'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) <= ANY (ARRAY[1, NULL, 2, 3]) AND mod(b::int,10) IN (1, 2, NULL, 3)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) < ALL (ARRAY[4, 5]) AND mod(b::int,10) IN (1, 2, 3) AND mod(c,5) > ANY (ARRAY[1, 2, 3])'); - --- we can't use the statistic for OR clauses that are not fully covered (missing 'd' attribute) -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE mod(a,20) = 1 OR mod(b::int,10) = 1 OR mod(c,5) = 1 OR d IS NOT NULL'); - --- 100 distinct combinations with NULL values, all in the MCV list -TRUNCATE mcv_lists; -DROP STATISTICS mcv_lists_stats; - -INSERT INTO mcv_lists (a, b, c, filler1) - SELECT - (CASE WHEN mod(i,100) = 1 THEN NULL ELSE mod(i,100) END), - (CASE WHEN mod(i,50) = 1 THEN NULL ELSE mod(i,50) END), - (CASE WHEN mod(i,25) = 1 THEN NULL ELSE mod(i,25) END), - i - FROM generate_series(1,5000) s(i); - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NULL AND c IS NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NOT NULL AND b IS NULL AND c IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (0, 1) AND b IN (''0'', ''1'')'); - --- create statistics -CREATE STATISTICS mcv_lists_stats (mcv) ON a, b, c FROM mcv_lists; - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NULL AND c IS NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND b IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NOT NULL AND b IS NULL AND c IS NOT NULL'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IN (0, 1) AND b IN (''0'', ''1'')'); - --- test pg_mcv_list_items with a very simple (single item) MCV list -TRUNCATE mcv_lists; -INSERT INTO mcv_lists (a, b, c) SELECT 1, 2, 3 FROM generate_series(1,1000) s(i); -ANALYZE mcv_lists; - -SELECT m.* - FROM pg_statistic_ext s, pg_statistic_ext_data d, - pg_mcv_list_items(d.stxdmcv) m - WHERE s.stxname = 'mcv_lists_stats' - AND d.stxoid = s.oid; - --- 2 distinct combinations with NULL values, all in the MCV list -TRUNCATE mcv_lists; -DROP STATISTICS mcv_lists_stats; - -INSERT INTO mcv_lists (a, b, c, d) - SELECT - NULL, -- always NULL - (CASE WHEN mod(i,2) = 0 THEN NULL ELSE 'x' END), - (CASE WHEN mod(i,2) = 0 THEN NULL ELSE 0 END), - (CASE WHEN mod(i,2) = 0 THEN NULL ELSE 'x' END) - FROM generate_series(1,5000) s(i); - -ANALYZE mcv_lists; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE b = ''x'' OR d = ''x'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''x'' OR d = ''x'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND (b = ''x'' OR d = ''x'')'); - --- create statistics -CREATE STATISTICS mcv_lists_stats (mcv) ON a, b, d FROM mcv_lists; - -ANALYZE mcv_lists; - --- test pg_mcv_list_items with MCV list containing variable-length data and NULLs -SELECT m.* - FROM pg_statistic_ext s, pg_statistic_ext_data d, - pg_mcv_list_items(d.stxdmcv) m - WHERE s.stxname = 'mcv_lists_stats' - AND d.stxoid = s.oid; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE b = ''x'' OR d = ''x'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''x'' OR d = ''x'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a IS NULL AND (b = ''x'' OR d = ''x'')'); - --- mcv with pass-by-ref fixlen types, e.g. uuid -CREATE TABLE mcv_lists_uuid ( - a UUID, - b UUID, - c UUID -) -WITH (autovacuum_enabled = off); - -INSERT INTO mcv_lists_uuid (a, b, c) - SELECT - md5(mod(i,100)::text)::uuid, - md5(mod(i,50)::text)::uuid, - md5(mod(i,25)::text)::uuid - FROM generate_series(1,5000) s(i); - -ANALYZE mcv_lists_uuid; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_uuid WHERE a = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'' AND b = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_uuid WHERE a = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'' AND b = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'' AND c = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'''); - -CREATE STATISTICS mcv_lists_uuid_stats (mcv) ON a, b, c - FROM mcv_lists_uuid; - -ANALYZE mcv_lists_uuid; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_uuid WHERE a = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'' AND b = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'''); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_uuid WHERE a = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'' AND b = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'' AND c = ''1679091c-5a88-0faf-6fb5-e6087eb1b2dc'''); - -DROP TABLE mcv_lists_uuid; - --- mcv with arrays -CREATE TABLE mcv_lists_arrays ( - a TEXT[], - b NUMERIC[], - c INT[] -) -WITH (autovacuum_enabled = off); - -INSERT INTO mcv_lists_arrays (a, b, c) - SELECT - ARRAY[md5((i/100)::text), md5((i/100-1)::text), md5((i/100+1)::text)], - ARRAY[(i/100-1)::numeric/1000, (i/100)::numeric/1000, (i/100+1)::numeric/1000], - ARRAY[(i/100-1), i/100, (i/100+1)] - FROM generate_series(1,5000) s(i); - -CREATE STATISTICS mcv_lists_arrays_stats (mcv) ON a, b, c - FROM mcv_lists_arrays; - -ANALYZE mcv_lists_arrays; - --- mcv with bool -CREATE TABLE mcv_lists_bool ( - a BOOL, - b BOOL, - c BOOL -) -WITH (autovacuum_enabled = off); - -INSERT INTO mcv_lists_bool (a, b, c) - SELECT - (mod(i,2) = 0), (mod(i,4) = 0), (mod(i,8) = 0) - FROM generate_series(1,10000) s(i); - -ANALYZE mcv_lists_bool; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE a AND b AND c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND b AND c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND NOT b AND c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND b AND NOT c'); - -CREATE STATISTICS mcv_lists_bool_stats (mcv) ON a, b, c - FROM mcv_lists_bool; - -ANALYZE mcv_lists_bool; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE a AND b AND c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND b AND c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND NOT b AND c'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND b AND NOT c'); - --- mcv covering just a small fraction of data -CREATE TABLE mcv_lists_partial ( - a INT, - b INT, - c INT -); - --- 10 frequent groups, each with 100 elements -INSERT INTO mcv_lists_partial (a, b, c) - SELECT - mod(i,10), - mod(i,10), - mod(i,10) - FROM generate_series(0,999) s(i); - --- 100 groups that will make it to the MCV list (includes the 10 frequent ones) -INSERT INTO mcv_lists_partial (a, b, c) - SELECT - i, - i, - i - FROM generate_series(0,99) s(i); - --- 4000 groups in total, most of which won't make it (just a single item) -INSERT INTO mcv_lists_partial (a, b, c) - SELECT - i, - i, - i - FROM generate_series(0,3999) s(i); - -ANALYZE mcv_lists_partial; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 AND b = 0 AND c = 0'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 OR b = 0 OR c = 0'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 10 AND b = 10 AND c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 10 OR b = 10 OR c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 AND b = 0 AND c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 OR b = 0 OR c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE (a = 0 AND b = 0 AND c = 0) OR (a = 1 AND b = 1 AND c = 1) OR (a = 2 AND b = 2 AND c = 2)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE (a = 0 AND b = 0) OR (a = 0 AND c = 0) OR (b = 0 AND c = 0)'); - -CREATE STATISTICS mcv_lists_partial_stats (mcv) ON a, b, c - FROM mcv_lists_partial; - -ANALYZE mcv_lists_partial; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 AND b = 0 AND c = 0'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 OR b = 0 OR c = 0'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 10 AND b = 10 AND c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 10 OR b = 10 OR c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 AND b = 0 AND c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE a = 0 OR b = 0 OR c = 10'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE (a = 0 AND b = 0 AND c = 0) OR (a = 1 AND b = 1 AND c = 1) OR (a = 2 AND b = 2 AND c = 2)'); - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_partial WHERE (a = 0 AND b = 0) OR (a = 0 AND c = 0) OR (b = 0 AND c = 0)'); - -DROP TABLE mcv_lists_partial; - --- check the ability to use multiple MCV lists -CREATE TABLE mcv_lists_multi ( - a INTEGER, - b INTEGER, - c INTEGER, - d INTEGER -) -WITH (autovacuum_enabled = off); - -INSERT INTO mcv_lists_multi (a, b, c, d) - SELECT - mod(i,5), - mod(i,5), - mod(i,7), - mod(i,7) - FROM generate_series(1,5000) s(i); - -ANALYZE mcv_lists_multi; - --- estimates without any mcv statistics -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE a = 0 AND b = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE b = 0 AND c = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE b = 0 OR c = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE a = 0 AND b = 0 AND c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE (a = 0 AND b = 0) OR (c = 0 AND d = 0)'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE a = 0 OR b = 0 OR c = 0 OR d = 0'); - --- create separate MCV statistics -CREATE STATISTICS mcv_lists_multi_1 (mcv) ON a, b FROM mcv_lists_multi; -CREATE STATISTICS mcv_lists_multi_2 (mcv) ON c, d FROM mcv_lists_multi; - -ANALYZE mcv_lists_multi; - -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE a = 0 AND b = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE b = 0 AND c = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE b = 0 OR c = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE a = 0 AND b = 0 AND c = 0 AND d = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE (a = 0 AND b = 0) OR (c = 0 AND d = 0)'); -SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_multi WHERE a = 0 OR b = 0 OR c = 0 OR d = 0'); - -DROP TABLE mcv_lists_multi; - - --- statistics on integer expressions -CREATE TABLE expr_stats (a int, b int, c int); -INSERT INTO expr_stats SELECT mod(i,10), mod(i,10), mod(i,10) FROM generate_series(1,1000) s(i); -ANALYZE expr_stats; - -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE (2*a) = 0 AND (3*b) = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE (a+b) = 0 AND (a-b) = 0'); - -CREATE STATISTICS expr_stats_1 (mcv) ON (a+b), (a-b), (2*a), (3*b) FROM expr_stats; -ANALYZE expr_stats; - -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE (2*a) = 0 AND (3*b) = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE (a+b) = 0 AND (a-b) = 0'); - -DROP STATISTICS expr_stats_1; -DROP TABLE expr_stats; - --- statistics on a mix columns and expressions -CREATE TABLE expr_stats (a int, b int, c int); -INSERT INTO expr_stats SELECT mod(i,10), mod(i,10), mod(i,10) FROM generate_series(1,1000) s(i); -ANALYZE expr_stats; - -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND (2*a) = 0 AND (3*b) = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 3 AND b = 3 AND (a-b) = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND b = 1 AND (a-b) = 0'); - -CREATE STATISTICS expr_stats_1 (mcv) ON a, b, (2*a), (3*b), (a+b), (a-b) FROM expr_stats; -ANALYZE expr_stats; - -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND (2*a) = 0 AND (3*b) = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 3 AND b = 3 AND (a-b) = 0'); -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND b = 1 AND (a-b) = 0'); - -DROP TABLE expr_stats; - --- statistics on expressions with different data types -CREATE TABLE expr_stats (a int, b name, c text); -INSERT INTO expr_stats SELECT mod(i,10), md5(mod(i,10)::text), md5(mod(i,10)::text) FROM generate_series(1,1000) s(i); -ANALYZE expr_stats; - -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND (b || c) <= ''z'' AND (c || b) >= ''0'''); - -CREATE STATISTICS expr_stats_1 (mcv) ON a, b, (b || c), (c || b) FROM expr_stats; -ANALYZE expr_stats; - -SELECT * FROM check_estimated_rows('SELECT * FROM expr_stats WHERE a = 0 AND (b || c) <= ''z'' AND (c || b) >= ''0'''); - -DROP TABLE expr_stats; - --- test handling of a mix of compatible and incompatible expressions -CREATE TABLE expr_stats_incompatible_test ( - c0 double precision, - c1 boolean NOT NULL -); - -CREATE STATISTICS expr_stat_comp_1 ON c0, c1 FROM expr_stats_incompatible_test; - -INSERT INTO expr_stats_incompatible_test VALUES (1234,false), (5678,true); -ANALYZE expr_stats_incompatible_test; - -SELECT c0 FROM ONLY expr_stats_incompatible_test WHERE -( - upper('x') LIKE ('x'||('[0,1]'::int4range)) - AND - (c0 IN (0, 1) OR c1) -); - -DROP TABLE expr_stats_incompatible_test; - --- Permission tests. Users should not be able to see specific data values in --- the extended statistics, if they lack permission to see those values in --- the underlying table. --- --- Currently this is only relevant for MCV stats. -CREATE SCHEMA tststats; - -CREATE TABLE tststats.priv_test_tbl ( - a int, - b int -); - -INSERT INTO tststats.priv_test_tbl - SELECT mod(i,5), mod(i,10) FROM generate_series(1,100) s(i); - -CREATE STATISTICS tststats.priv_test_stats (mcv) ON a, b - FROM tststats.priv_test_tbl; - -ANALYZE tststats.priv_test_tbl; - --- Check printing info about extended statistics by \dX -create table stts_t1 (a int, b int); -create statistics stts_1 (ndistinct) on a, b from stts_t1; -create statistics stts_2 (ndistinct, dependencies) on a, b from stts_t1; -create statistics stts_3 (ndistinct, dependencies, mcv) on a, b from stts_t1; - -create table stts_t2 (a int, b int, c int); -create statistics stts_4 on b, c from stts_t2; - -create table stts_t3 (col1 int, col2 int, col3 int); -create statistics stts_hoge on col1, col2, col3 from stts_t3; - -create schema stts_s1; -create schema stts_s2; -create statistics stts_s1.stts_foo on col1, col2 from stts_t3; -create statistics stts_s2.stts_yama (dependencies, mcv) on col1, col3 from stts_t3; - -insert into stts_t1 select i,i from generate_series(1,100) i; -analyze stts_t1; -set search_path to public, stts_s1, stts_s2, tststats; - -\dX -\dX stts_? -\dX *stts_hoge -\dX+ -\dX+ stts_? -\dX+ *stts_hoge -\dX+ stts_s2.stts_yama - -set search_path to public, stts_s1; -\dX - -create role regress_stats_ext nosuperuser; -set role regress_stats_ext; -\dX -reset role; - -drop table stts_t1, stts_t2, stts_t3; -drop schema stts_s1, stts_s2 cascade; -drop user regress_stats_ext; -reset search_path; - --- User with no access -CREATE USER regress_stats_user1; -GRANT USAGE ON SCHEMA tststats TO regress_stats_user1; -SET SESSION AUTHORIZATION regress_stats_user1; -SELECT * FROM tststats.priv_test_tbl; -- Permission denied - --- Attempt to gain access using a leaky operator -CREATE FUNCTION op_leak(int, int) RETURNS bool - AS 'BEGIN RAISE NOTICE ''op_leak => %, %'', $1, $2; RETURN $1 < $2; END' - LANGUAGE plpgsql; -CREATE OPERATOR <<< (procedure = op_leak, leftarg = int, rightarg = int, - restrict = scalarltsel); -SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Permission denied -DELETE FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Permission denied - --- Grant access via a security barrier view, but hide all data -RESET SESSION AUTHORIZATION; -CREATE VIEW tststats.priv_test_view WITH (security_barrier=true) - AS SELECT * FROM tststats.priv_test_tbl WHERE false; -GRANT SELECT, DELETE ON tststats.priv_test_view TO regress_stats_user1; - --- Should now have access via the view, but see nothing and leak nothing -SET SESSION AUTHORIZATION regress_stats_user1; -SELECT * FROM tststats.priv_test_view WHERE a <<< 0 AND b <<< 0; -- Should not leak -DELETE FROM tststats.priv_test_view WHERE a <<< 0 AND b <<< 0; -- Should not leak - --- Grant table access, but hide all data with RLS -RESET SESSION AUTHORIZATION; -ALTER TABLE tststats.priv_test_tbl ENABLE ROW LEVEL SECURITY; -GRANT SELECT, DELETE ON tststats.priv_test_tbl TO regress_stats_user1; - --- Should now have direct table access, but see nothing and leak nothing -SET SESSION AUTHORIZATION regress_stats_user1; -SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak -DELETE FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak - --- Tidy up -DROP OPERATOR <<< (int, int); -DROP FUNCTION op_leak(int, int); -RESET SESSION AUTHORIZATION; -DROP SCHEMA tststats CASCADE; -DROP USER regress_stats_user1; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsubscription.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsubscription.sql deleted file mode 100644 index 74c38ead5d..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsubscription.sql +++ /dev/null @@ -1,260 +0,0 @@ --- --- SUBSCRIPTION --- - -CREATE ROLE regress_subscription_user LOGIN SUPERUSER; -CREATE ROLE regress_subscription_user2; -CREATE ROLE regress_subscription_user_dummy LOGIN NOSUPERUSER; -SET SESSION AUTHORIZATION 'regress_subscription_user'; - --- fail - no publications -CREATE SUBSCRIPTION regress_testsub CONNECTION 'foo'; - --- fail - no connection -CREATE SUBSCRIPTION regress_testsub PUBLICATION foo; - --- fail - cannot do CREATE SUBSCRIPTION CREATE SLOT inside transaction block -BEGIN; -CREATE SUBSCRIPTION regress_testsub CONNECTION 'testconn' PUBLICATION testpub WITH (create_slot); -COMMIT; - --- fail - invalid connection string -CREATE SUBSCRIPTION regress_testsub CONNECTION 'testconn' PUBLICATION testpub; - --- fail - duplicate publications -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION foo, testpub, foo WITH (connect = false); - --- ok -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false); - -COMMENT ON SUBSCRIPTION regress_testsub IS 'test subscription'; -SELECT obj_description(s.oid, 'pg_subscription') FROM pg_subscription s; - --- fail - name already exists -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false); - --- fail - must be superuser -SET SESSION AUTHORIZATION 'regress_subscription_user2'; -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION foo WITH (connect = false); -SET SESSION AUTHORIZATION 'regress_subscription_user'; - --- fail - invalid option combinations -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, copy_data = true); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, enabled = true); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, create_slot = true); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE, enabled = true); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE, enabled = false, create_slot = true); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE, enabled = false); -CREATE SUBSCRIPTION regress_testsub2 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE, create_slot = false); - --- ok - with slot_name = NONE -CREATE SUBSCRIPTION regress_testsub3 CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (slot_name = NONE, connect = false); --- fail -ALTER SUBSCRIPTION regress_testsub3 ENABLE; -ALTER SUBSCRIPTION regress_testsub3 REFRESH PUBLICATION; - -DROP SUBSCRIPTION regress_testsub3; - --- fail - invalid connection string -ALTER SUBSCRIPTION regress_testsub CONNECTION 'foobar'; - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET PUBLICATION testpub2, testpub3 WITH (refresh = false); -ALTER SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist2'; -ALTER SUBSCRIPTION regress_testsub SET (slot_name = 'newname'); - --- fail -ALTER SUBSCRIPTION regress_testsub SET (slot_name = ''); - --- fail -ALTER SUBSCRIPTION regress_doesnotexist CONNECTION 'dbname=regress_doesnotexist2'; -ALTER SUBSCRIPTION regress_testsub SET (create_slot = false); - --- ok -ALTER SUBSCRIPTION regress_testsub SKIP (lsn = '0/12345'); - -\dRs+ - --- ok - with lsn = NONE -ALTER SUBSCRIPTION regress_testsub SKIP (lsn = NONE); - --- fail -ALTER SUBSCRIPTION regress_testsub SKIP (lsn = '0/0'); - -\dRs+ - -BEGIN; -ALTER SUBSCRIPTION regress_testsub ENABLE; - -\dRs - -ALTER SUBSCRIPTION regress_testsub DISABLE; - -\dRs - -COMMIT; - --- fail - must be owner of subscription -SET ROLE regress_subscription_user_dummy; -ALTER SUBSCRIPTION regress_testsub RENAME TO regress_testsub_dummy; -RESET ROLE; - -ALTER SUBSCRIPTION regress_testsub RENAME TO regress_testsub_foo; -ALTER SUBSCRIPTION regress_testsub_foo SET (synchronous_commit = local); -ALTER SUBSCRIPTION regress_testsub_foo SET (synchronous_commit = foobar); - -\dRs+ - --- rename back to keep the rest simple -ALTER SUBSCRIPTION regress_testsub_foo RENAME TO regress_testsub; - --- fail - new owner must be superuser -ALTER SUBSCRIPTION regress_testsub OWNER TO regress_subscription_user2; -ALTER ROLE regress_subscription_user2 SUPERUSER; --- now it works -ALTER SUBSCRIPTION regress_testsub OWNER TO regress_subscription_user2; - --- fail - cannot do DROP SUBSCRIPTION inside transaction block with slot name -BEGIN; -DROP SUBSCRIPTION regress_testsub; -COMMIT; - -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); - --- now it works -BEGIN; -DROP SUBSCRIPTION regress_testsub; -COMMIT; - -DROP SUBSCRIPTION IF EXISTS regress_testsub; -DROP SUBSCRIPTION regress_testsub; -- fail - --- fail - binary must be boolean -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, binary = foo); - --- now it works -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, binary = true); - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET (binary = false); -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); - -\dRs+ - -DROP SUBSCRIPTION regress_testsub; - --- fail - streaming must be boolean -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, streaming = foo); - --- now it works -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, streaming = true); - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET (streaming = false); -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); - -\dRs+ - --- fail - publication already exists -ALTER SUBSCRIPTION regress_testsub ADD PUBLICATION testpub WITH (refresh = false); - --- fail - publication used more than once -ALTER SUBSCRIPTION regress_testsub ADD PUBLICATION testpub1, testpub1 WITH (refresh = false); - --- ok - add two publications into subscription -ALTER SUBSCRIPTION regress_testsub ADD PUBLICATION testpub1, testpub2 WITH (refresh = false); - --- fail - publications already exist -ALTER SUBSCRIPTION regress_testsub ADD PUBLICATION testpub1, testpub2 WITH (refresh = false); - -\dRs+ - --- fail - publication used more then once -ALTER SUBSCRIPTION regress_testsub DROP PUBLICATION testpub1, testpub1 WITH (refresh = false); - --- fail - all publications are deleted -ALTER SUBSCRIPTION regress_testsub DROP PUBLICATION testpub, testpub1, testpub2 WITH (refresh = false); - --- fail - publication does not exist in subscription -ALTER SUBSCRIPTION regress_testsub DROP PUBLICATION testpub3 WITH (refresh = false); - --- ok - delete publications -ALTER SUBSCRIPTION regress_testsub DROP PUBLICATION testpub1, testpub2 WITH (refresh = false); - -\dRs+ - -DROP SUBSCRIPTION regress_testsub; - -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION mypub - WITH (connect = false, create_slot = false, copy_data = false); - -ALTER SUBSCRIPTION regress_testsub ENABLE; - --- fail - ALTER SUBSCRIPTION with refresh is not allowed in a transaction --- block or function -BEGIN; -ALTER SUBSCRIPTION regress_testsub SET PUBLICATION mypub WITH (refresh = true); -END; - -BEGIN; -ALTER SUBSCRIPTION regress_testsub REFRESH PUBLICATION; -END; - -CREATE FUNCTION func() RETURNS VOID AS -$$ ALTER SUBSCRIPTION regress_testsub SET PUBLICATION mypub WITH (refresh = true) $$ LANGUAGE SQL; -SELECT func(); - -ALTER SUBSCRIPTION regress_testsub DISABLE; -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); -DROP SUBSCRIPTION regress_testsub; -DROP FUNCTION func; - --- fail - two_phase must be boolean -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, two_phase = foo); - --- now it works -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, two_phase = true); - -\dRs+ ---fail - alter of two_phase option not supported. -ALTER SUBSCRIPTION regress_testsub SET (two_phase = false); - --- but can alter streaming when two_phase enabled -ALTER SUBSCRIPTION regress_testsub SET (streaming = true); - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); -DROP SUBSCRIPTION regress_testsub; - --- two_phase and streaming are compatible. -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, streaming = true, two_phase = true); - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); -DROP SUBSCRIPTION regress_testsub; - --- fail - disable_on_error must be boolean -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, disable_on_error = foo); - --- now it works -CREATE SUBSCRIPTION regress_testsub CONNECTION 'dbname=regress_doesnotexist' PUBLICATION testpub WITH (connect = false, disable_on_error = false); - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET (disable_on_error = true); - -\dRs+ - -ALTER SUBSCRIPTION regress_testsub SET (slot_name = NONE); -DROP SUBSCRIPTION regress_testsub; - -RESET SESSION AUTHORIZATION; -DROP ROLE regress_subscription_user; -DROP ROLE regress_subscription_user2; -DROP ROLE regress_subscription_user_dummy; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsubselect.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsubselect.sql deleted file mode 100644 index 94ba91f5bb..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fsubselect.sql +++ /dev/null @@ -1,939 +0,0 @@ --- --- SUBSELECT --- - -SELECT 1 AS one WHERE 1 IN (SELECT 1); - -SELECT 1 AS zero WHERE 1 NOT IN (SELECT 1); - -SELECT 1 AS zero WHERE 1 IN (SELECT 2); - --- Check grammar's handling of extra parens in assorted contexts - -SELECT * FROM (SELECT 1 AS x) ss; -SELECT * FROM ((SELECT 1 AS x)) ss; - -(SELECT 2) UNION SELECT 2; -((SELECT 2)) UNION SELECT 2; - -SELECT ((SELECT 2) UNION SELECT 2); -SELECT (((SELECT 2)) UNION SELECT 2); - -SELECT (SELECT ARRAY[1,2,3])[1]; -SELECT ((SELECT ARRAY[1,2,3]))[2]; -SELECT (((SELECT ARRAY[1,2,3])))[3]; - --- Set up some simple test tables - -CREATE TABLE SUBSELECT_TBL ( - f1 integer, - f2 integer, - f3 float -); - -INSERT INTO SUBSELECT_TBL VALUES (1, 2, 3); -INSERT INTO SUBSELECT_TBL VALUES (2, 3, 4); -INSERT INTO SUBSELECT_TBL VALUES (3, 4, 5); -INSERT INTO SUBSELECT_TBL VALUES (1, 1, 1); -INSERT INTO SUBSELECT_TBL VALUES (2, 2, 2); -INSERT INTO SUBSELECT_TBL VALUES (3, 3, 3); -INSERT INTO SUBSELECT_TBL VALUES (6, 7, 8); -INSERT INTO SUBSELECT_TBL VALUES (8, 9, NULL); - -SELECT * FROM SUBSELECT_TBL; - --- Uncorrelated subselects - -SELECT f1 AS "Constant Select" FROM SUBSELECT_TBL - WHERE f1 IN (SELECT 1); - -SELECT f1 AS "Uncorrelated Field" FROM SUBSELECT_TBL - WHERE f1 IN (SELECT f2 FROM SUBSELECT_TBL); - -SELECT f1 AS "Uncorrelated Field" FROM SUBSELECT_TBL - WHERE f1 IN (SELECT f2 FROM SUBSELECT_TBL WHERE - f2 IN (SELECT f1 FROM SUBSELECT_TBL)); - -SELECT f1, f2 - FROM SUBSELECT_TBL - WHERE (f1, f2) NOT IN (SELECT f2, CAST(f3 AS int4) FROM SUBSELECT_TBL - WHERE f3 IS NOT NULL); - --- Correlated subselects - -SELECT f1 AS "Correlated Field", f2 AS "Second Field" - FROM SUBSELECT_TBL upper - WHERE f1 IN (SELECT f2 FROM SUBSELECT_TBL WHERE f1 = upper.f1); - -SELECT f1 AS "Correlated Field", f3 AS "Second Field" - FROM SUBSELECT_TBL upper - WHERE f1 IN - (SELECT f2 FROM SUBSELECT_TBL WHERE CAST(upper.f2 AS float) = f3); - -SELECT f1 AS "Correlated Field", f3 AS "Second Field" - FROM SUBSELECT_TBL upper - WHERE f3 IN (SELECT upper.f1 + f2 FROM SUBSELECT_TBL - WHERE f2 = CAST(f3 AS integer)); - -SELECT f1 AS "Correlated Field" - FROM SUBSELECT_TBL - WHERE (f1, f2) IN (SELECT f2, CAST(f3 AS int4) FROM SUBSELECT_TBL - WHERE f3 IS NOT NULL); - --- --- Use some existing tables in the regression test --- - -SELECT ss.f1 AS "Correlated Field", ss.f3 AS "Second Field" - FROM SUBSELECT_TBL ss - WHERE f1 NOT IN (SELECT f1+1 FROM INT4_TBL - WHERE f1 != ss.f1 AND f1 < 2147483647); - -select q1, float8(count(*)) / (select count(*) from int8_tbl) -from int8_tbl group by q1 order by q1; - --- Unspecified-type literals in output columns should resolve as text - -SELECT *, pg_typeof(f1) FROM - (SELECT 'foo' AS f1 FROM generate_series(1,3)) ss ORDER BY 1; - --- ... unless there's context to suggest differently - -explain (verbose, costs off) select '42' union all select '43'; -explain (verbose, costs off) select '42' union all select 43; - --- check materialization of an initplan reference (bug #14524) -explain (verbose, costs off) -select 1 = all (select (select 1)); -select 1 = all (select (select 1)); - --- --- Check EXISTS simplification with LIMIT --- -explain (costs off) -select * from int4_tbl o where exists - (select 1 from int4_tbl i where i.f1=o.f1 limit null); -explain (costs off) -select * from int4_tbl o where not exists - (select 1 from int4_tbl i where i.f1=o.f1 limit 1); -explain (costs off) -select * from int4_tbl o where exists - (select 1 from int4_tbl i where i.f1=o.f1 limit 0); - --- --- Test cases to catch unpleasant interactions between IN-join processing --- and subquery pullup. --- - -select count(*) from - (select 1 from tenk1 a - where unique1 IN (select hundred from tenk1 b)) ss; -select count(distinct ss.ten) from - (select ten from tenk1 a - where unique1 IN (select hundred from tenk1 b)) ss; -select count(*) from - (select 1 from tenk1 a - where unique1 IN (select distinct hundred from tenk1 b)) ss; -select count(distinct ss.ten) from - (select ten from tenk1 a - where unique1 IN (select distinct hundred from tenk1 b)) ss; - --- --- Test cases to check for overenthusiastic optimization of --- "IN (SELECT DISTINCT ...)" and related cases. Per example from --- Luca Pireddu and Michael Fuhr. --- - -CREATE TEMP TABLE foo (id integer); -CREATE TEMP TABLE bar (id1 integer, id2 integer); - -INSERT INTO foo VALUES (1); - -INSERT INTO bar VALUES (1, 1); -INSERT INTO bar VALUES (2, 2); -INSERT INTO bar VALUES (3, 1); - --- These cases require an extra level of distinct-ing above subquery s -SELECT * FROM foo WHERE id IN - (SELECT id2 FROM (SELECT DISTINCT id1, id2 FROM bar) AS s); -SELECT * FROM foo WHERE id IN - (SELECT id2 FROM (SELECT id1,id2 FROM bar GROUP BY id1,id2) AS s); -SELECT * FROM foo WHERE id IN - (SELECT id2 FROM (SELECT id1, id2 FROM bar UNION - SELECT id1, id2 FROM bar) AS s); - --- These cases do not -SELECT * FROM foo WHERE id IN - (SELECT id2 FROM (SELECT DISTINCT ON (id2) id1, id2 FROM bar) AS s); -SELECT * FROM foo WHERE id IN - (SELECT id2 FROM (SELECT id2 FROM bar GROUP BY id2) AS s); -SELECT * FROM foo WHERE id IN - (SELECT id2 FROM (SELECT id2 FROM bar UNION - SELECT id2 FROM bar) AS s); - --- --- Test case to catch problems with multiply nested sub-SELECTs not getting --- recalculated properly. Per bug report from Didier Moens. --- - -CREATE TABLE orderstest ( - approver_ref integer, - po_ref integer, - ordercanceled boolean -); - -INSERT INTO orderstest VALUES (1, 1, false); -INSERT INTO orderstest VALUES (66, 5, false); -INSERT INTO orderstest VALUES (66, 6, false); -INSERT INTO orderstest VALUES (66, 7, false); -INSERT INTO orderstest VALUES (66, 1, true); -INSERT INTO orderstest VALUES (66, 8, false); -INSERT INTO orderstest VALUES (66, 1, false); -INSERT INTO orderstest VALUES (77, 1, false); -INSERT INTO orderstest VALUES (1, 1, false); -INSERT INTO orderstest VALUES (66, 1, false); -INSERT INTO orderstest VALUES (1, 1, false); - -CREATE VIEW orders_view AS -SELECT *, -(SELECT CASE - WHEN ord.approver_ref=1 THEN '---' ELSE 'Approved' - END) AS "Approved", -(SELECT CASE - WHEN ord.ordercanceled - THEN 'Canceled' - ELSE - (SELECT CASE - WHEN ord.po_ref=1 - THEN - (SELECT CASE - WHEN ord.approver_ref=1 - THEN '---' - ELSE 'Approved' - END) - ELSE 'PO' - END) -END) AS "Status", -(CASE - WHEN ord.ordercanceled - THEN 'Canceled' - ELSE - (CASE - WHEN ord.po_ref=1 - THEN - (CASE - WHEN ord.approver_ref=1 - THEN '---' - ELSE 'Approved' - END) - ELSE 'PO' - END) -END) AS "Status_OK" -FROM orderstest ord; - -SELECT * FROM orders_view; - -DROP TABLE orderstest cascade; - --- --- Test cases to catch situations where rule rewriter fails to propagate --- hasSubLinks flag correctly. Per example from Kyle Bateman. --- - -create temp table parts ( - partnum text, - cost float8 -); - -create temp table shipped ( - ttype char(2), - ordnum int4, - partnum text, - value float8 -); - -create temp view shipped_view as - select * from shipped where ttype = 'wt'; - -create rule shipped_view_insert as on insert to shipped_view do instead - insert into shipped values('wt', new.ordnum, new.partnum, new.value); - -insert into parts (partnum, cost) values (1, 1234.56); - -insert into shipped_view (ordnum, partnum, value) - values (0, 1, (select cost from parts where partnum = '1')); - -select * from shipped_view; - -create rule shipped_view_update as on update to shipped_view do instead - update shipped set partnum = new.partnum, value = new.value - where ttype = new.ttype and ordnum = new.ordnum; - -update shipped_view set value = 11 - from int4_tbl a join int4_tbl b - on (a.f1 = (select f1 from int4_tbl c where c.f1=b.f1)) - where ordnum = a.f1; - -select * from shipped_view; - -select f1, ss1 as relabel from - (select *, (select sum(f1) from int4_tbl b where f1 >= a.f1) as ss1 - from int4_tbl a) ss; - --- --- Test cases involving PARAM_EXEC parameters and min/max index optimizations. --- Per bug report from David Sanchez i Gregori. --- - -select * from ( - select max(unique1) from tenk1 as a - where exists (select 1 from tenk1 as b where b.thousand = a.unique2) -) ss; - -select * from ( - select min(unique1) from tenk1 as a - where not exists (select 1 from tenk1 as b where b.unique2 = 10000) -) ss; - --- --- Test that an IN implemented using a UniquePath does unique-ification --- with the right semantics, as per bug #4113. (Unfortunately we have --- no simple way to ensure that this test case actually chooses that type --- of plan, but it does in releases 7.4-8.3. Note that an ordering difference --- here might mean that some other plan type is being used, rendering the test --- pointless.) --- - -create temp table numeric_table (num_col numeric); -insert into numeric_table values (1), (1.000000000000000000001), (2), (3); - -create temp table float_table (float_col float8); -insert into float_table values (1), (2), (3); - -select * from float_table - where float_col in (select num_col from numeric_table); - -select * from numeric_table - where num_col in (select float_col from float_table); - --- --- Test case for bug #4290: bogus calculation of subplan param sets --- - -create temp table ta (id int primary key, val int); - -insert into ta values(1,1); -insert into ta values(2,2); - -create temp table tb (id int primary key, aval int); - -insert into tb values(1,1); -insert into tb values(2,1); -insert into tb values(3,2); -insert into tb values(4,2); - -create temp table tc (id int primary key, aid int); - -insert into tc values(1,1); -insert into tc values(2,2); - -select - ( select min(tb.id) from tb - where tb.aval = (select ta.val from ta where ta.id = tc.aid) ) as min_tb_id -from tc; - --- --- Test case for 8.3 "failed to locate grouping columns" bug --- - -create temp table t1 (f1 numeric(14,0), f2 varchar(30)); - -select * from - (select distinct f1, f2, (select f2 from t1 x where x.f1 = up.f1) as fs - from t1 up) ss -group by f1,f2,fs; - --- --- Test case for bug #5514 (mishandling of whole-row Vars in subselects) --- - -create temp table table_a(id integer); -insert into table_a values (42); - -create temp view view_a as select * from table_a; - -select view_a from view_a; -select (select view_a) from view_a; -select (select (select view_a)) from view_a; -select (select (a.*)::text) from view_a a; - --- --- Check that whole-row Vars reading the result of a subselect don't include --- any junk columns therein --- - -select q from (select max(f1) from int4_tbl group by f1 order by f1) q; -with q as (select max(f1) from int4_tbl group by f1 order by f1) - select q from q; - --- --- Test case for sublinks pulled up into joinaliasvars lists in an --- inherited update/delete query --- - -begin; -- this shouldn't delete anything, but be safe - -delete from road -where exists ( - select 1 - from - int4_tbl cross join - ( select f1, array(select q1 from int8_tbl) as arr - from text_tbl ) ss - where road.name = ss.f1 ); - -rollback; - --- --- Test case for sublinks pushed down into subselects via join alias expansion --- - -select - (select sq1) as qq1 -from - (select exists(select 1 from int4_tbl where f1 = q2) as sq1, 42 as dummy - from int8_tbl) sq0 - join - int4_tbl i4 on dummy = i4.f1; - --- --- Test case for subselect within UPDATE of INSERT...ON CONFLICT DO UPDATE --- -create temp table upsert(key int4 primary key, val text); -insert into upsert values(1, 'val') on conflict (key) do update set val = 'not seen'; -insert into upsert values(1, 'val') on conflict (key) do update set val = 'seen with subselect ' || (select f1 from int4_tbl where f1 != 0 limit 1)::text; - -select * from upsert; - -with aa as (select 'int4_tbl' u from int4_tbl limit 1) -insert into upsert values (1, 'x'), (999, 'y') -on conflict (key) do update set val = (select u from aa) -returning *; - --- --- Test case for cross-type partial matching in hashed subplan (bug #7597) --- - -create temp table outer_7597 (f1 int4, f2 int4); -insert into outer_7597 values (0, 0); -insert into outer_7597 values (1, 0); -insert into outer_7597 values (0, null); -insert into outer_7597 values (1, null); - -create temp table inner_7597(c1 int8, c2 int8); -insert into inner_7597 values(0, null); - -select * from outer_7597 where (f1, f2) not in (select * from inner_7597); - --- --- Similar test case using text that verifies that collation --- information is passed through by execTuplesEqual() in nodeSubplan.c --- (otherwise it would error in texteq()) --- - -create temp table outer_text (f1 text, f2 text); -insert into outer_text values ('a', 'a'); -insert into outer_text values ('b', 'a'); -insert into outer_text values ('a', null); -insert into outer_text values ('b', null); - -create temp table inner_text (c1 text, c2 text); -insert into inner_text values ('a', null); -insert into inner_text values ('123', '456'); - -select * from outer_text where (f1, f2) not in (select * from inner_text); - --- --- Another test case for cross-type hashed subplans: comparison of --- inner-side values must be done with appropriate operator --- - -explain (verbose, costs off) -select 'foo'::text in (select 'bar'::name union all select 'bar'::name); - -select 'foo'::text in (select 'bar'::name union all select 'bar'::name); - --- --- Test that we don't try to hash nested records (bug #17363) --- (Hashing could be supported, but for now we don't) --- - -explain (verbose, costs off) -select row(row(row(1))) = any (select row(row(1))); - -select row(row(row(1))) = any (select row(row(1))); - --- --- Test case for premature memory release during hashing of subplan output --- - -select '1'::text in (select '1'::name union all select '1'::name); - --- --- Test that we don't try to use a hashed subplan if the simplified --- testexpr isn't of the right shape --- - --- this fails by default, of course -select * from int8_tbl where q1 in (select c1 from inner_text); - -begin; - --- make an operator to allow it to succeed -create function bogus_int8_text_eq(int8, text) returns boolean -language sql as 'select $1::text = $2'; - -create operator = (procedure=bogus_int8_text_eq, leftarg=int8, rightarg=text); - -explain (costs off) -select * from int8_tbl where q1 in (select c1 from inner_text); -select * from int8_tbl where q1 in (select c1 from inner_text); - --- inlining of this function results in unusual number of hash clauses, --- which we can still cope with -create or replace function bogus_int8_text_eq(int8, text) returns boolean -language sql as 'select $1::text = $2 and $1::text = $2'; - -explain (costs off) -select * from int8_tbl where q1 in (select c1 from inner_text); -select * from int8_tbl where q1 in (select c1 from inner_text); - --- inlining of this function causes LHS and RHS to be switched, --- which we can't cope with, so hashing should be abandoned -create or replace function bogus_int8_text_eq(int8, text) returns boolean -language sql as 'select $2 = $1::text'; - -explain (costs off) -select * from int8_tbl where q1 in (select c1 from inner_text); -select * from int8_tbl where q1 in (select c1 from inner_text); - -rollback; -- to get rid of the bogus operator - --- --- Test resolution of hashed vs non-hashed implementation of EXISTS subplan --- -explain (costs off) -select count(*) from tenk1 t -where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0); -select count(*) from tenk1 t -where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0); - -explain (costs off) -select count(*) from tenk1 t -where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0) - and thousand = 1; -select count(*) from tenk1 t -where (exists(select 1 from tenk1 k where k.unique1 = t.unique2) or ten < 0) - and thousand = 1; - --- It's possible for the same EXISTS to get resolved both ways -create temp table exists_tbl (c1 int, c2 int, c3 int) partition by list (c1); -create temp table exists_tbl_null partition of exists_tbl for values in (null); -create temp table exists_tbl_def partition of exists_tbl default; -insert into exists_tbl select x, x/2, x+1 from generate_series(0,10) x; -analyze exists_tbl; -explain (costs off) -select * from exists_tbl t1 - where (exists(select 1 from exists_tbl t2 where t1.c1 = t2.c2) or c3 < 0); -select * from exists_tbl t1 - where (exists(select 1 from exists_tbl t2 where t1.c1 = t2.c2) or c3 < 0); - --- --- Test case for planner bug with nested EXISTS handling --- -select a.thousand from tenk1 a, tenk1 b -where a.thousand = b.thousand - and exists ( select 1 from tenk1 c where b.hundred = c.hundred - and not exists ( select 1 from tenk1 d - where a.thousand = d.thousand ) ); - --- --- Check that nested sub-selects are not pulled up if they contain volatiles --- -explain (verbose, costs off) - select x, x from - (select (select now()) as x from (values(1),(2)) v(y)) ss; -explain (verbose, costs off) - select x, x from - (select (select random()) as x from (values(1),(2)) v(y)) ss; -explain (verbose, costs off) - select x, x from - (select (select now() where y=y) as x from (values(1),(2)) v(y)) ss; -explain (verbose, costs off) - select x, x from - (select (select random() where y=y) as x from (values(1),(2)) v(y)) ss; - --- --- Test rescan of a hashed subplan (the use of random() is to prevent the --- sub-select from being pulled up, which would result in not hashing) --- -explain (verbose, costs off) -select sum(ss.tst::int) from - onek o cross join lateral ( - select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst, - random() as r - from onek i where i.unique1 = o.unique1 ) ss -where o.ten = 0; - -select sum(ss.tst::int) from - onek o cross join lateral ( - select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst, - random() as r - from onek i where i.unique1 = o.unique1 ) ss -where o.ten = 0; - --- --- Test rescan of a SetOp node --- -explain (costs off) -select count(*) from - onek o cross join lateral ( - select * from onek i1 where i1.unique1 = o.unique1 - except - select * from onek i2 where i2.unique1 = o.unique2 - ) ss -where o.ten = 1; - -select count(*) from - onek o cross join lateral ( - select * from onek i1 where i1.unique1 = o.unique1 - except - select * from onek i2 where i2.unique1 = o.unique2 - ) ss -where o.ten = 1; - --- --- Test rescan of a RecursiveUnion node --- -explain (costs off) -select sum(o.four), sum(ss.a) from - onek o cross join lateral ( - with recursive x(a) as - (select o.four as a - union - select a + 1 from x - where a < 10) - select * from x - ) ss -where o.ten = 1; - -select sum(o.four), sum(ss.a) from - onek o cross join lateral ( - with recursive x(a) as - (select o.four as a - union - select a + 1 from x - where a < 10) - select * from x - ) ss -where o.ten = 1; - --- --- Check we don't misoptimize a NOT IN where the subquery returns no rows. --- -create temp table notinouter (a int); -create temp table notininner (b int not null); -insert into notinouter values (null), (1); - -select * from notinouter where a not in (select b from notininner); - --- --- Check we behave sanely in corner case of empty SELECT list (bug #8648) --- -create temp table nocolumns(); -select exists(select * from nocolumns); - --- --- Check behavior with a SubPlan in VALUES (bug #14924) --- -select val.x - from generate_series(1,10) as s(i), - lateral ( - values ((select s.i + 1)), (s.i + 101) - ) as val(x) -where s.i < 10 and (select val.x) < 110; - --- another variant of that (bug #16213) -explain (verbose, costs off) -select * from -(values - (3 not in (select * from (values (1), (2)) ss1)), - (false) -) ss; - -select * from -(values - (3 not in (select * from (values (1), (2)) ss1)), - (false) -) ss; - --- --- Check sane behavior with nested IN SubLinks --- -explain (verbose, costs off) -select * from int4_tbl where - (case when f1 in (select unique1 from tenk1 a) then f1 else null end) in - (select ten from tenk1 b); -select * from int4_tbl where - (case when f1 in (select unique1 from tenk1 a) then f1 else null end) in - (select ten from tenk1 b); - --- --- Check for incorrect optimization when IN subquery contains a SRF --- -explain (verbose, costs off) -select * from int4_tbl o where (f1, f1) in - (select f1, generate_series(1,50) / 10 g from int4_tbl i group by f1); -select * from int4_tbl o where (f1, f1) in - (select f1, generate_series(1,50) / 10 g from int4_tbl i group by f1); - --- --- check for over-optimization of whole-row Var referencing an Append plan --- -select (select q from - (select 1,2,3 where f1 > 0 - union all - select 4,5,6.0 where f1 <= 0 - ) q ) -from int4_tbl; - --- --- Check for sane handling of a lateral reference in a subquery's quals --- (most of the complication here is to prevent the test case from being --- flattened too much) --- -explain (verbose, costs off) -select * from - int4_tbl i4, - lateral ( - select i4.f1 > 1 as b, 1 as id - from (select random() order by 1) as t1 - union all - select true as b, 2 as id - ) as t2 -where b and f1 >= 0; - -select * from - int4_tbl i4, - lateral ( - select i4.f1 > 1 as b, 1 as id - from (select random() order by 1) as t1 - union all - select true as b, 2 as id - ) as t2 -where b and f1 >= 0; - --- --- Check that volatile quals aren't pushed down past a DISTINCT: --- nextval() should not be called more than the nominal number of times --- -create temp sequence ts1; - -select * from - (select distinct ten from tenk1) ss - where ten < 10 + nextval('ts1') - order by 1; - -select nextval('ts1'); - --- --- Check that volatile quals aren't pushed down past a set-returning function; --- while a nonvolatile qual can be, if it doesn't reference the SRF. --- -create function tattle(x int, y int) returns bool -volatile language plpgsql as $$ -begin - raise notice 'x = %, y = %', x, y; - return x > y; -end$$; - -explain (verbose, costs off) -select * from - (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss - where tattle(x, 8); - -select * from - (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss - where tattle(x, 8); - --- if we pretend it's stable, we get different results: -alter function tattle(x int, y int) stable; - -explain (verbose, costs off) -select * from - (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss - where tattle(x, 8); - -select * from - (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss - where tattle(x, 8); - --- although even a stable qual should not be pushed down if it references SRF -explain (verbose, costs off) -select * from - (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss - where tattle(x, u); - -select * from - (select 9 as x, unnest(array[1,2,3,11,12,13]) as u) ss - where tattle(x, u); - -drop function tattle(x int, y int); - --- --- Test that LIMIT can be pushed to SORT through a subquery that just projects --- columns. We check for that having happened by looking to see if EXPLAIN --- ANALYZE shows that a top-N sort was used. We must suppress or filter away --- all the non-invariant parts of the EXPLAIN ANALYZE output. --- -create table sq_limit (pk int primary key, c1 int, c2 int); -insert into sq_limit values - (1, 1, 1), - (2, 2, 2), - (3, 3, 3), - (4, 4, 4), - (5, 1, 1), - (6, 2, 2), - (7, 3, 3), - (8, 4, 4); - -create function explain_sq_limit() returns setof text language plpgsql as -$$ -declare ln text; -begin - for ln in - explain (analyze, summary off, timing off, costs off) - select * from (select pk,c2 from sq_limit order by c1,pk) as x limit 3 - loop - ln := regexp_replace(ln, 'Memory: \S*', 'Memory: xxx'); - return next ln; - end loop; -end; -$$; - -select * from explain_sq_limit(); - -select * from (select pk,c2 from sq_limit order by c1,pk) as x limit 3; - -drop function explain_sq_limit(); - -drop table sq_limit; - --- --- Ensure that backward scan direction isn't propagated into --- expression subqueries (bug #15336) --- - -begin; - -declare c1 scroll cursor for - select * from generate_series(1,4) i - where i <> all (values (2),(3)); - -move forward all in c1; -fetch backward all in c1; - -commit; - --- --- Tests for CTE inlining behavior --- - --- Basic subquery that can be inlined -explain (verbose, costs off) -with x as (select * from (select f1 from subselect_tbl) ss) -select * from x where f1 = 1; - --- Explicitly request materialization -explain (verbose, costs off) -with x as materialized (select * from (select f1 from subselect_tbl) ss) -select * from x where f1 = 1; - --- Stable functions are safe to inline -explain (verbose, costs off) -with x as (select * from (select f1, now() from subselect_tbl) ss) -select * from x where f1 = 1; - --- Volatile functions prevent inlining -explain (verbose, costs off) -with x as (select * from (select f1, random() from subselect_tbl) ss) -select * from x where f1 = 1; - --- SELECT FOR UPDATE cannot be inlined -explain (verbose, costs off) -with x as (select * from (select f1 from subselect_tbl for update) ss) -select * from x where f1 = 1; - --- Multiply-referenced CTEs are inlined only when requested -explain (verbose, costs off) -with x as (select * from (select f1, now() as n from subselect_tbl) ss) -select * from x, x x2 where x.n = x2.n; - -explain (verbose, costs off) -with x as not materialized (select * from (select f1, now() as n from subselect_tbl) ss) -select * from x, x x2 where x.n = x2.n; - --- Multiply-referenced CTEs can't be inlined if they contain outer self-refs -explain (verbose, costs off) -with recursive x(a) as - ((values ('a'), ('b')) - union all - (with z as not materialized (select * from x) - select z.a || z1.a as a from z cross join z as z1 - where length(z.a || z1.a) < 5)) -select * from x; - -with recursive x(a) as - ((values ('a'), ('b')) - union all - (with z as not materialized (select * from x) - select z.a || z1.a as a from z cross join z as z1 - where length(z.a || z1.a) < 5)) -select * from x; - -explain (verbose, costs off) -with recursive x(a) as - ((values ('a'), ('b')) - union all - (with z as not materialized (select * from x) - select z.a || z.a as a from z - where length(z.a || z.a) < 5)) -select * from x; - -with recursive x(a) as - ((values ('a'), ('b')) - union all - (with z as not materialized (select * from x) - select z.a || z.a as a from z - where length(z.a || z.a) < 5)) -select * from x; - --- Check handling of outer references -explain (verbose, costs off) -with x as (select * from int4_tbl) -select * from (with y as (select * from x) select * from y) ss; - -explain (verbose, costs off) -with x as materialized (select * from int4_tbl) -select * from (with y as (select * from x) select * from y) ss; - --- Ensure that we inline the currect CTE when there are --- multiple CTEs with the same name -explain (verbose, costs off) -with x as (select 1 as y) -select * from (with x as (select 2 as y) select * from x) ss; - --- Row marks are not pushed into CTEs -explain (verbose, costs off) -with x as (select * from subselect_tbl) -select * from x for update; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftablesample.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftablesample.sql deleted file mode 100644 index aa17994277..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftablesample.sql +++ /dev/null @@ -1,110 +0,0 @@ -CREATE TABLE test_tablesample (id int, name text) WITH (fillfactor=10); --- use fillfactor so we don't have to load too much data to get multiple pages - -INSERT INTO test_tablesample - SELECT i, repeat(i::text, 200) FROM generate_series(0, 9) s(i); - -SELECT t.id FROM test_tablesample AS t TABLESAMPLE SYSTEM (50) REPEATABLE (0); -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (100.0/11) REPEATABLE (0); -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (0); -SELECT id FROM test_tablesample TABLESAMPLE BERNOULLI (50) REPEATABLE (0); -SELECT id FROM test_tablesample TABLESAMPLE BERNOULLI (5.5) REPEATABLE (0); - --- 100% should give repeatable count results (ie, all rows) in any case -SELECT count(*) FROM test_tablesample TABLESAMPLE SYSTEM (100); -SELECT count(*) FROM test_tablesample TABLESAMPLE SYSTEM (100) REPEATABLE (1+2); -SELECT count(*) FROM test_tablesample TABLESAMPLE SYSTEM (100) REPEATABLE (0.4); - -CREATE VIEW test_tablesample_v1 AS - SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (10*2) REPEATABLE (2); -CREATE VIEW test_tablesample_v2 AS - SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (99); -\d+ test_tablesample_v1 -\d+ test_tablesample_v2 - --- check a sampled query doesn't affect cursor in progress -BEGIN; -DECLARE tablesample_cur SCROLL CURSOR FOR - SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (0); - -FETCH FIRST FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; - -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (0); - -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; - -FETCH FIRST FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; -FETCH NEXT FROM tablesample_cur; - -CLOSE tablesample_cur; -END; - -EXPLAIN (COSTS OFF) - SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (2); -EXPLAIN (COSTS OFF) - SELECT * FROM test_tablesample_v1; - --- check inheritance behavior -explain (costs off) - select count(*) from person tablesample bernoulli (100); -select count(*) from person tablesample bernoulli (100); -select count(*) from person; - --- check that collations get assigned within the tablesample arguments -SELECT count(*) FROM test_tablesample TABLESAMPLE bernoulli (('1'::text < '0'::text)::int); - --- check behavior during rescans, as well as correct handling of min/max pct -select * from - (values (0),(100)) v(pct), - lateral (select count(*) from tenk1 tablesample bernoulli (pct)) ss; -select * from - (values (0),(100)) v(pct), - lateral (select count(*) from tenk1 tablesample system (pct)) ss; -explain (costs off) -select pct, count(unique1) from - (values (0),(100)) v(pct), - lateral (select * from tenk1 tablesample bernoulli (pct)) ss - group by pct; -select pct, count(unique1) from - (values (0),(100)) v(pct), - lateral (select * from tenk1 tablesample bernoulli (pct)) ss - group by pct; -select pct, count(unique1) from - (values (0),(100)) v(pct), - lateral (select * from tenk1 tablesample system (pct)) ss - group by pct; - --- errors -SELECT id FROM test_tablesample TABLESAMPLE FOOBAR (1); - -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (NULL); -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (50) REPEATABLE (NULL); - -SELECT id FROM test_tablesample TABLESAMPLE BERNOULLI (-1); -SELECT id FROM test_tablesample TABLESAMPLE BERNOULLI (200); -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (-1); -SELECT id FROM test_tablesample TABLESAMPLE SYSTEM (200); - -SELECT id FROM test_tablesample_v1 TABLESAMPLE BERNOULLI (1); -INSERT INTO test_tablesample_v1 VALUES(1); - -WITH query_select AS (SELECT * FROM test_tablesample) -SELECT * FROM query_select TABLESAMPLE BERNOULLI (5.5) REPEATABLE (1); - -SELECT q.* FROM (SELECT * FROM test_tablesample) as q TABLESAMPLE BERNOULLI (5); - --- check partitioned tables support tablesample -create table parted_sample (a int) partition by list (a); -create table parted_sample_1 partition of parted_sample for values in (1); -create table parted_sample_2 partition of parted_sample for values in (2); -explain (costs off) - select * from parted_sample tablesample bernoulli (100); -drop table parted_sample, parted_sample_1, parted_sample_2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftablespace.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftablespace.sql deleted file mode 100644 index 21db433f2a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftablespace.sql +++ /dev/null @@ -1,435 +0,0 @@ --- relative tablespace locations are not allowed -CREATE TABLESPACE regress_tblspace LOCATION 'relative'; -- fail - --- empty tablespace locations are not usually allowed -CREATE TABLESPACE regress_tblspace LOCATION ''; -- fail - --- as a special developer-only option to allow us to use tablespaces --- with streaming replication on the same server, an empty location --- can be allowed as a way to say that the tablespace should be created --- as a directory in pg_tblspc, rather than being a symlink -SET allow_in_place_tablespaces = true; - --- create a tablespace using WITH clause -CREATE TABLESPACE regress_tblspacewith LOCATION '' WITH (some_nonexistent_parameter = true); -- fail -CREATE TABLESPACE regress_tblspacewith LOCATION '' WITH (random_page_cost = 3.0); -- ok - --- check to see the parameter was used -SELECT spcoptions FROM pg_tablespace WHERE spcname = 'regress_tblspacewith'; - --- drop the tablespace so we can re-use the location -DROP TABLESPACE regress_tblspacewith; - --- create a tablespace we can use -CREATE TABLESPACE regress_tblspace LOCATION ''; --- This returns a relative path as of an effect of allow_in_place_tablespaces, --- masking the tablespace OID used in the path name. -SELECT regexp_replace(pg_tablespace_location(oid), '(pg_tblspc)/(\d+)', '\1/NNN') - FROM pg_tablespace WHERE spcname = 'regress_tblspace'; - --- try setting and resetting some properties for the new tablespace -ALTER TABLESPACE regress_tblspace SET (random_page_cost = 1.0, seq_page_cost = 1.1); -ALTER TABLESPACE regress_tblspace SET (some_nonexistent_parameter = true); -- fail -ALTER TABLESPACE regress_tblspace RESET (random_page_cost = 2.0); -- fail -ALTER TABLESPACE regress_tblspace RESET (random_page_cost, effective_io_concurrency); -- ok - --- REINDEX (TABLESPACE) --- catalogs and system tablespaces --- system catalog, fail -REINDEX (TABLESPACE regress_tblspace) TABLE pg_am; -REINDEX (TABLESPACE regress_tblspace) TABLE CONCURRENTLY pg_am; --- shared catalog, fail -REINDEX (TABLESPACE regress_tblspace) TABLE pg_authid; -REINDEX (TABLESPACE regress_tblspace) TABLE CONCURRENTLY pg_authid; --- toast relations, fail -REINDEX (TABLESPACE regress_tblspace) INDEX pg_toast.pg_toast_1260_index; -REINDEX (TABLESPACE regress_tblspace) INDEX CONCURRENTLY pg_toast.pg_toast_1260_index; -REINDEX (TABLESPACE regress_tblspace) TABLE pg_toast.pg_toast_1260; -REINDEX (TABLESPACE regress_tblspace) TABLE CONCURRENTLY pg_toast.pg_toast_1260; --- system catalog, fail -REINDEX (TABLESPACE pg_global) TABLE pg_authid; -REINDEX (TABLESPACE pg_global) TABLE CONCURRENTLY pg_authid; - --- table with toast relation -CREATE TABLE regress_tblspace_test_tbl (num1 bigint, num2 double precision, t text); -INSERT INTO regress_tblspace_test_tbl (num1, num2, t) - SELECT round(random()*100), random(), 'text' - FROM generate_series(1, 10) s(i); -CREATE INDEX regress_tblspace_test_tbl_idx ON regress_tblspace_test_tbl (num1); --- move to global tablespace, fail -REINDEX (TABLESPACE pg_global) INDEX regress_tblspace_test_tbl_idx; -REINDEX (TABLESPACE pg_global) INDEX CONCURRENTLY regress_tblspace_test_tbl_idx; - --- check transactional behavior of REINDEX (TABLESPACE) -BEGIN; -REINDEX (TABLESPACE regress_tblspace) INDEX regress_tblspace_test_tbl_idx; -REINDEX (TABLESPACE regress_tblspace) TABLE regress_tblspace_test_tbl; -ROLLBACK; --- no relation moved to the new tablespace -SELECT c.relname FROM pg_class c, pg_tablespace s - WHERE c.reltablespace = s.oid AND s.spcname = 'regress_tblspace'; - --- check that all indexes are moved to a new tablespace with different --- relfilenode. --- Save first the existing relfilenode for the toast and main relations. -SELECT relfilenode as main_filenode FROM pg_class - WHERE relname = 'regress_tblspace_test_tbl_idx' \gset -SELECT relfilenode as toast_filenode FROM pg_class - WHERE oid = - (SELECT i.indexrelid - FROM pg_class c, - pg_index i - WHERE i.indrelid = c.reltoastrelid AND - c.relname = 'regress_tblspace_test_tbl') \gset -REINDEX (TABLESPACE regress_tblspace) TABLE regress_tblspace_test_tbl; -SELECT c.relname FROM pg_class c, pg_tablespace s - WHERE c.reltablespace = s.oid AND s.spcname = 'regress_tblspace' - ORDER BY c.relname; -ALTER TABLE regress_tblspace_test_tbl SET TABLESPACE regress_tblspace; -ALTER TABLE regress_tblspace_test_tbl SET TABLESPACE pg_default; -SELECT c.relname FROM pg_class c, pg_tablespace s - WHERE c.reltablespace = s.oid AND s.spcname = 'regress_tblspace' - ORDER BY c.relname; --- Move back to the default tablespace. -ALTER INDEX regress_tblspace_test_tbl_idx SET TABLESPACE pg_default; -SELECT c.relname FROM pg_class c, pg_tablespace s - WHERE c.reltablespace = s.oid AND s.spcname = 'regress_tblspace' - ORDER BY c.relname; -REINDEX (TABLESPACE regress_tblspace, CONCURRENTLY) TABLE regress_tblspace_test_tbl; -SELECT c.relname FROM pg_class c, pg_tablespace s - WHERE c.reltablespace = s.oid AND s.spcname = 'regress_tblspace' - ORDER BY c.relname; -SELECT relfilenode = :main_filenode AS main_same FROM pg_class - WHERE relname = 'regress_tblspace_test_tbl_idx'; -SELECT relfilenode = :toast_filenode as toast_same FROM pg_class - WHERE oid = - (SELECT i.indexrelid - FROM pg_class c, - pg_index i - WHERE i.indrelid = c.reltoastrelid AND - c.relname = 'regress_tblspace_test_tbl'); -DROP TABLE regress_tblspace_test_tbl; - --- REINDEX (TABLESPACE) with partitions --- Create a partition tree and check the set of relations reindexed --- with their new tablespace. -CREATE TABLE tbspace_reindex_part (c1 int, c2 int) PARTITION BY RANGE (c1); -CREATE TABLE tbspace_reindex_part_0 PARTITION OF tbspace_reindex_part - FOR VALUES FROM (0) TO (10) PARTITION BY list (c2); -CREATE TABLE tbspace_reindex_part_0_1 PARTITION OF tbspace_reindex_part_0 - FOR VALUES IN (1); -CREATE TABLE tbspace_reindex_part_0_2 PARTITION OF tbspace_reindex_part_0 - FOR VALUES IN (2); --- This partitioned table will have no partitions. -CREATE TABLE tbspace_reindex_part_10 PARTITION OF tbspace_reindex_part - FOR VALUES FROM (10) TO (20) PARTITION BY list (c2); --- Create some partitioned indexes -CREATE INDEX tbspace_reindex_part_index ON ONLY tbspace_reindex_part (c1); -CREATE INDEX tbspace_reindex_part_index_0 ON ONLY tbspace_reindex_part_0 (c1); -ALTER INDEX tbspace_reindex_part_index ATTACH PARTITION tbspace_reindex_part_index_0; --- This partitioned index will have no partitions. -CREATE INDEX tbspace_reindex_part_index_10 ON ONLY tbspace_reindex_part_10 (c1); -ALTER INDEX tbspace_reindex_part_index ATTACH PARTITION tbspace_reindex_part_index_10; -CREATE INDEX tbspace_reindex_part_index_0_1 ON ONLY tbspace_reindex_part_0_1 (c1); -ALTER INDEX tbspace_reindex_part_index_0 ATTACH PARTITION tbspace_reindex_part_index_0_1; -CREATE INDEX tbspace_reindex_part_index_0_2 ON ONLY tbspace_reindex_part_0_2 (c1); -ALTER INDEX tbspace_reindex_part_index_0 ATTACH PARTITION tbspace_reindex_part_index_0_2; -SELECT relid, parentrelid, level FROM pg_partition_tree('tbspace_reindex_part_index') - ORDER BY relid, level; --- Track the original tablespace, relfilenode and OID of each index --- in the tree. -CREATE TEMP TABLE reindex_temp_before AS - SELECT oid, relname, relfilenode, reltablespace - FROM pg_class - WHERE relname ~ 'tbspace_reindex_part_index'; -REINDEX (TABLESPACE regress_tblspace, CONCURRENTLY) TABLE tbspace_reindex_part; --- REINDEX CONCURRENTLY changes the OID of the old relation, hence a check --- based on the relation name below. -SELECT b.relname, - CASE WHEN a.relfilenode = b.relfilenode THEN 'relfilenode is unchanged' - ELSE 'relfilenode has changed' END AS filenode, - CASE WHEN a.reltablespace = b.reltablespace THEN 'reltablespace is unchanged' - ELSE 'reltablespace has changed' END AS tbspace - FROM reindex_temp_before b JOIN pg_class a ON b.relname = a.relname - ORDER BY 1; -DROP TABLE tbspace_reindex_part; - --- create a schema we can use -CREATE SCHEMA testschema; - --- try a table -CREATE TABLE testschema.foo (i int) TABLESPACE regress_tblspace; -SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c - where c.reltablespace = t.oid AND c.relname = 'foo'; - -INSERT INTO testschema.foo VALUES(1); -INSERT INTO testschema.foo VALUES(2); - --- tables from dynamic sources -CREATE TABLE testschema.asselect TABLESPACE regress_tblspace AS SELECT 1; -SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c - where c.reltablespace = t.oid AND c.relname = 'asselect'; - -PREPARE selectsource(int) AS SELECT $1; -CREATE TABLE testschema.asexecute TABLESPACE regress_tblspace - AS EXECUTE selectsource(2); -SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c - where c.reltablespace = t.oid AND c.relname = 'asexecute'; - --- index -CREATE INDEX foo_idx on testschema.foo(i) TABLESPACE regress_tblspace; -SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c - where c.reltablespace = t.oid AND c.relname = 'foo_idx'; - --- check \d output -\d testschema.foo -\d testschema.foo_idx - --- --- partitioned table --- -CREATE TABLE testschema.part (a int) PARTITION BY LIST (a); -SET default_tablespace TO pg_global; -CREATE TABLE testschema.part_1 PARTITION OF testschema.part FOR VALUES IN (1); -RESET default_tablespace; -CREATE TABLE testschema.part_1 PARTITION OF testschema.part FOR VALUES IN (1); -SET default_tablespace TO regress_tblspace; -CREATE TABLE testschema.part_2 PARTITION OF testschema.part FOR VALUES IN (2); -SET default_tablespace TO pg_global; -CREATE TABLE testschema.part_3 PARTITION OF testschema.part FOR VALUES IN (3); -ALTER TABLE testschema.part SET TABLESPACE regress_tblspace; -CREATE TABLE testschema.part_3 PARTITION OF testschema.part FOR VALUES IN (3); -CREATE TABLE testschema.part_4 PARTITION OF testschema.part FOR VALUES IN (4) - TABLESPACE pg_default; -CREATE TABLE testschema.part_56 PARTITION OF testschema.part FOR VALUES IN (5, 6) - PARTITION BY LIST (a); -ALTER TABLE testschema.part SET TABLESPACE pg_default; -CREATE TABLE testschema.part_78 PARTITION OF testschema.part FOR VALUES IN (7, 8) - PARTITION BY LIST (a); -CREATE TABLE testschema.part_910 PARTITION OF testschema.part FOR VALUES IN (9, 10) - PARTITION BY LIST (a) TABLESPACE regress_tblspace; -RESET default_tablespace; -CREATE TABLE testschema.part_78 PARTITION OF testschema.part FOR VALUES IN (7, 8) - PARTITION BY LIST (a); - -SELECT relname, spcname FROM pg_catalog.pg_class c - JOIN pg_catalog.pg_namespace n ON (c.relnamespace = n.oid) - LEFT JOIN pg_catalog.pg_tablespace t ON c.reltablespace = t.oid - where c.relname LIKE 'part%' AND n.nspname = 'testschema' order by relname; -RESET default_tablespace; -DROP TABLE testschema.part; - --- partitioned index -CREATE TABLE testschema.part (a int) PARTITION BY LIST (a); -CREATE TABLE testschema.part1 PARTITION OF testschema.part FOR VALUES IN (1); -CREATE INDEX part_a_idx ON testschema.part (a) TABLESPACE regress_tblspace; -CREATE TABLE testschema.part2 PARTITION OF testschema.part FOR VALUES IN (2); -SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c - where c.reltablespace = t.oid AND c.relname LIKE 'part%_idx'; -\d testschema.part -\d+ testschema.part -\d testschema.part1 -\d+ testschema.part1 -\d testschema.part_a_idx -\d+ testschema.part_a_idx - --- partitioned rels cannot specify the default tablespace. These fail: -CREATE TABLE testschema.dflt (a int PRIMARY KEY) PARTITION BY LIST (a) TABLESPACE pg_default; -CREATE TABLE testschema.dflt (a int PRIMARY KEY USING INDEX TABLESPACE pg_default) PARTITION BY LIST (a); -SET default_tablespace TO 'pg_default'; -CREATE TABLE testschema.dflt (a int PRIMARY KEY) PARTITION BY LIST (a) TABLESPACE regress_tblspace; -CREATE TABLE testschema.dflt (a int PRIMARY KEY USING INDEX TABLESPACE regress_tblspace) PARTITION BY LIST (a); --- but these work: -CREATE TABLE testschema.dflt (a int PRIMARY KEY USING INDEX TABLESPACE regress_tblspace) PARTITION BY LIST (a) TABLESPACE regress_tblspace; -SET default_tablespace TO ''; -CREATE TABLE testschema.dflt2 (a int PRIMARY KEY) PARTITION BY LIST (a); -DROP TABLE testschema.dflt, testschema.dflt2; - --- check that default_tablespace doesn't affect ALTER TABLE index rebuilds -CREATE TABLE testschema.test_default_tab(id bigint) TABLESPACE regress_tblspace; -INSERT INTO testschema.test_default_tab VALUES (1); -CREATE INDEX test_index1 on testschema.test_default_tab (id); -CREATE INDEX test_index2 on testschema.test_default_tab (id) TABLESPACE regress_tblspace; -ALTER TABLE testschema.test_default_tab ADD CONSTRAINT test_index3 PRIMARY KEY (id); -ALTER TABLE testschema.test_default_tab ADD CONSTRAINT test_index4 UNIQUE (id) USING INDEX TABLESPACE regress_tblspace; - -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 --- use a custom tablespace for default_tablespace -SET default_tablespace TO regress_tblspace; --- tablespace should not change if no rewrite -ALTER TABLE testschema.test_default_tab ALTER id TYPE bigint; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 -SELECT * FROM testschema.test_default_tab; --- tablespace should not change even if there is an index rewrite -ALTER TABLE testschema.test_default_tab ALTER id TYPE int; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 -SELECT * FROM testschema.test_default_tab; --- now use the default tablespace for default_tablespace -SET default_tablespace TO ''; --- tablespace should not change if no rewrite -ALTER TABLE testschema.test_default_tab ALTER id TYPE int; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 --- tablespace should not change even if there is an index rewrite -ALTER TABLE testschema.test_default_tab ALTER id TYPE bigint; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 -DROP TABLE testschema.test_default_tab; - --- check that default_tablespace doesn't affect ALTER TABLE index rebuilds --- (this time with a partitioned table) -CREATE TABLE testschema.test_default_tab_p(id bigint, val bigint) - PARTITION BY LIST (id) TABLESPACE regress_tblspace; -CREATE TABLE testschema.test_default_tab_p1 PARTITION OF testschema.test_default_tab_p - FOR VALUES IN (1); -INSERT INTO testschema.test_default_tab_p VALUES (1); -CREATE INDEX test_index1 on testschema.test_default_tab_p (val); -CREATE INDEX test_index2 on testschema.test_default_tab_p (val) TABLESPACE regress_tblspace; -ALTER TABLE testschema.test_default_tab_p ADD CONSTRAINT test_index3 PRIMARY KEY (id); -ALTER TABLE testschema.test_default_tab_p ADD CONSTRAINT test_index4 UNIQUE (id) USING INDEX TABLESPACE regress_tblspace; - -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 --- use a custom tablespace for default_tablespace -SET default_tablespace TO regress_tblspace; --- tablespace should not change if no rewrite -ALTER TABLE testschema.test_default_tab_p ALTER val TYPE bigint; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 -SELECT * FROM testschema.test_default_tab_p; --- tablespace should not change even if there is an index rewrite -ALTER TABLE testschema.test_default_tab_p ALTER val TYPE int; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 -SELECT * FROM testschema.test_default_tab_p; --- now use the default tablespace for default_tablespace -SET default_tablespace TO ''; --- tablespace should not change if no rewrite -ALTER TABLE testschema.test_default_tab_p ALTER val TYPE int; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 --- tablespace should not change even if there is an index rewrite -ALTER TABLE testschema.test_default_tab_p ALTER val TYPE bigint; -\d testschema.test_index1 -\d testschema.test_index2 -\d testschema.test_index3 -\d testschema.test_index4 -DROP TABLE testschema.test_default_tab_p; - --- check that default_tablespace affects index additions in ALTER TABLE -CREATE TABLE testschema.test_tab(id int) TABLESPACE regress_tblspace; -INSERT INTO testschema.test_tab VALUES (1); -SET default_tablespace TO regress_tblspace; -ALTER TABLE testschema.test_tab ADD CONSTRAINT test_tab_unique UNIQUE (id); -SET default_tablespace TO ''; -ALTER TABLE testschema.test_tab ADD CONSTRAINT test_tab_pkey PRIMARY KEY (id); -\d testschema.test_tab_unique -\d testschema.test_tab_pkey -SELECT * FROM testschema.test_tab; -DROP TABLE testschema.test_tab; - --- check that default_tablespace is handled correctly by multi-command --- ALTER TABLE that includes a tablespace-preserving rewrite -CREATE TABLE testschema.test_tab(a int, b int, c int); -SET default_tablespace TO regress_tblspace; -ALTER TABLE testschema.test_tab ADD CONSTRAINT test_tab_unique UNIQUE (a); -CREATE INDEX test_tab_a_idx ON testschema.test_tab (a); -SET default_tablespace TO ''; -CREATE INDEX test_tab_b_idx ON testschema.test_tab (b); -\d testschema.test_tab_unique -\d testschema.test_tab_a_idx -\d testschema.test_tab_b_idx -ALTER TABLE testschema.test_tab ALTER b TYPE bigint, ADD UNIQUE (c); -\d testschema.test_tab_unique -\d testschema.test_tab_a_idx -\d testschema.test_tab_b_idx -DROP TABLE testschema.test_tab; - --- let's try moving a table from one place to another -CREATE TABLE testschema.atable AS VALUES (1), (2); -CREATE UNIQUE INDEX anindex ON testschema.atable(column1); - -ALTER TABLE testschema.atable SET TABLESPACE regress_tblspace; -ALTER INDEX testschema.anindex SET TABLESPACE regress_tblspace; -ALTER INDEX testschema.part_a_idx SET TABLESPACE pg_global; -ALTER INDEX testschema.part_a_idx SET TABLESPACE pg_default; -ALTER INDEX testschema.part_a_idx SET TABLESPACE regress_tblspace; - -INSERT INTO testschema.atable VALUES(3); -- ok -INSERT INTO testschema.atable VALUES(1); -- fail (checks index) -SELECT COUNT(*) FROM testschema.atable; -- checks heap - --- let's try moving a materialized view from one place to another -CREATE MATERIALIZED VIEW testschema.amv AS SELECT * FROM testschema.atable; -ALTER MATERIALIZED VIEW testschema.amv SET TABLESPACE regress_tblspace; -REFRESH MATERIALIZED VIEW testschema.amv; -SELECT COUNT(*) FROM testschema.amv; - --- Will fail with bad path -CREATE TABLESPACE regress_badspace LOCATION '/no/such/location'; - --- No such tablespace -CREATE TABLE bar (i int) TABLESPACE regress_nosuchspace; - --- Fail, in use for some partitioned object -DROP TABLESPACE regress_tblspace; -ALTER INDEX testschema.part_a_idx SET TABLESPACE pg_default; --- Fail, not empty -DROP TABLESPACE regress_tblspace; - -CREATE ROLE regress_tablespace_user1 login; -CREATE ROLE regress_tablespace_user2 login; -GRANT USAGE ON SCHEMA testschema TO regress_tablespace_user2; - -ALTER TABLESPACE regress_tblspace OWNER TO regress_tablespace_user1; - -CREATE TABLE testschema.tablespace_acl (c int); --- new owner lacks permission to create this index from scratch -CREATE INDEX k ON testschema.tablespace_acl (c) TABLESPACE regress_tblspace; -ALTER TABLE testschema.tablespace_acl OWNER TO regress_tablespace_user2; - -SET SESSION ROLE regress_tablespace_user2; -CREATE TABLE tablespace_table (i int) TABLESPACE regress_tblspace; -- fail -ALTER TABLE testschema.tablespace_acl ALTER c TYPE bigint; -REINDEX (TABLESPACE regress_tblspace) TABLE tablespace_table; -- fail -REINDEX (TABLESPACE regress_tblspace, CONCURRENTLY) TABLE tablespace_table; -- fail -RESET ROLE; - -ALTER TABLESPACE regress_tblspace RENAME TO regress_tblspace_renamed; - -ALTER TABLE ALL IN TABLESPACE regress_tblspace_renamed SET TABLESPACE pg_default; -ALTER INDEX ALL IN TABLESPACE regress_tblspace_renamed SET TABLESPACE pg_default; -ALTER MATERIALIZED VIEW ALL IN TABLESPACE regress_tblspace_renamed SET TABLESPACE pg_default; - --- Should show notice that nothing was done -ALTER TABLE ALL IN TABLESPACE regress_tblspace_renamed SET TABLESPACE pg_default; -ALTER MATERIALIZED VIEW ALL IN TABLESPACE regress_tblspace_renamed SET TABLESPACE pg_default; - --- Should succeed -DROP TABLESPACE regress_tblspace_renamed; - -DROP SCHEMA testschema CASCADE; - -DROP ROLE regress_tablespace_user1; -DROP ROLE regress_tablespace_user2; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftemp.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftemp.sql deleted file mode 100644 index 424d12b283..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftemp.sql +++ /dev/null @@ -1,297 +0,0 @@ --- --- TEMP --- Test temp relations and indexes --- - --- test temp table/index masking - -CREATE TABLE temptest(col int); - -CREATE INDEX i_temptest ON temptest(col); - -CREATE TEMP TABLE temptest(tcol int); - -CREATE INDEX i_temptest ON temptest(tcol); - -SELECT * FROM temptest; - -DROP INDEX i_temptest; - -DROP TABLE temptest; - -SELECT * FROM temptest; - -DROP INDEX i_temptest; - -DROP TABLE temptest; - --- test temp table selects - -CREATE TABLE temptest(col int); - -INSERT INTO temptest VALUES (1); - -CREATE TEMP TABLE temptest(tcol float); - -INSERT INTO temptest VALUES (2.1); - -SELECT * FROM temptest; - -DROP TABLE temptest; - -SELECT * FROM temptest; - -DROP TABLE temptest; - --- test temp table deletion - -CREATE TEMP TABLE temptest(col int); - -\c - -SELECT * FROM temptest; - --- Test ON COMMIT DELETE ROWS - -CREATE TEMP TABLE temptest(col int) ON COMMIT DELETE ROWS; - --- while we're here, verify successful truncation of index with SQL function -CREATE INDEX ON temptest(bit_length('')); - -BEGIN; -INSERT INTO temptest VALUES (1); -INSERT INTO temptest VALUES (2); - -SELECT * FROM temptest; -COMMIT; - -SELECT * FROM temptest; - -DROP TABLE temptest; - -BEGIN; -CREATE TEMP TABLE temptest(col) ON COMMIT DELETE ROWS AS SELECT 1; - -SELECT * FROM temptest; -COMMIT; - -SELECT * FROM temptest; - -DROP TABLE temptest; - --- Test ON COMMIT DROP - -BEGIN; - -CREATE TEMP TABLE temptest(col int) ON COMMIT DROP; - -INSERT INTO temptest VALUES (1); -INSERT INTO temptest VALUES (2); - -SELECT * FROM temptest; -COMMIT; - -SELECT * FROM temptest; - -BEGIN; -CREATE TEMP TABLE temptest(col) ON COMMIT DROP AS SELECT 1; - -SELECT * FROM temptest; -COMMIT; - -SELECT * FROM temptest; - --- ON COMMIT is only allowed for TEMP - -CREATE TABLE temptest(col int) ON COMMIT DELETE ROWS; -CREATE TABLE temptest(col) ON COMMIT DELETE ROWS AS SELECT 1; - --- Test foreign keys -BEGIN; -CREATE TEMP TABLE temptest1(col int PRIMARY KEY); -CREATE TEMP TABLE temptest2(col int REFERENCES temptest1) - ON COMMIT DELETE ROWS; -INSERT INTO temptest1 VALUES (1); -INSERT INTO temptest2 VALUES (1); -COMMIT; -SELECT * FROM temptest1; -SELECT * FROM temptest2; - -BEGIN; -CREATE TEMP TABLE temptest3(col int PRIMARY KEY) ON COMMIT DELETE ROWS; -CREATE TEMP TABLE temptest4(col int REFERENCES temptest3); -COMMIT; - --- Test manipulation of temp schema's placement in search path - -create table public.whereami (f1 text); -insert into public.whereami values ('public'); - -create temp table whereami (f1 text); -insert into whereami values ('temp'); - -create function public.whoami() returns text - as $$select 'public'::text$$ language sql; - -create function pg_temp.whoami() returns text - as $$select 'temp'::text$$ language sql; - --- default should have pg_temp implicitly first, but only for tables -select * from whereami; -select whoami(); - --- can list temp first explicitly, but it still doesn't affect functions -set search_path = pg_temp, public; -select * from whereami; -select whoami(); - --- or put it last for security -set search_path = public, pg_temp; -select * from whereami; -select whoami(); - --- you can invoke a temp function explicitly, though -select pg_temp.whoami(); - -drop table public.whereami; - --- types in temp schema -set search_path = pg_temp, public; -create domain pg_temp.nonempty as text check (value <> ''); --- function-syntax invocation of types matches rules for functions -select nonempty(''); -select pg_temp.nonempty(''); --- other syntax matches rules for tables -select ''::nonempty; - -reset search_path; - --- For partitioned temp tables, ON COMMIT actions ignore storage-less --- partitioned tables. -begin; -create temp table temp_parted_oncommit (a int) - partition by list (a) on commit delete rows; -create temp table temp_parted_oncommit_1 - partition of temp_parted_oncommit - for values in (1) on commit delete rows; -insert into temp_parted_oncommit values (1); -commit; --- partitions are emptied by the previous commit -select * from temp_parted_oncommit; -drop table temp_parted_oncommit; - --- Check dependencies between ON COMMIT actions with a partitioned --- table and its partitions. Using ON COMMIT DROP on a parent removes --- the whole set. -begin; -create temp table temp_parted_oncommit_test (a int) - partition by list (a) on commit drop; -create temp table temp_parted_oncommit_test1 - partition of temp_parted_oncommit_test - for values in (1) on commit delete rows; -create temp table temp_parted_oncommit_test2 - partition of temp_parted_oncommit_test - for values in (2) on commit drop; -insert into temp_parted_oncommit_test values (1), (2); -commit; --- no relations remain in this case. -select relname from pg_class where relname ~ '^temp_parted_oncommit_test'; --- Using ON COMMIT DELETE on a partitioned table does not remove --- all rows if partitions preserve their data. -begin; -create temp table temp_parted_oncommit_test (a int) - partition by list (a) on commit delete rows; -create temp table temp_parted_oncommit_test1 - partition of temp_parted_oncommit_test - for values in (1) on commit preserve rows; -create temp table temp_parted_oncommit_test2 - partition of temp_parted_oncommit_test - for values in (2) on commit drop; -insert into temp_parted_oncommit_test values (1), (2); -commit; --- Data from the remaining partition is still here as its rows are --- preserved. -select * from temp_parted_oncommit_test; --- two relations remain in this case. -select relname from pg_class where relname ~ '^temp_parted_oncommit_test' - order by relname; -drop table temp_parted_oncommit_test; - --- Check dependencies between ON COMMIT actions with inheritance trees. --- Using ON COMMIT DROP on a parent removes the whole set. -begin; -create temp table temp_inh_oncommit_test (a int) on commit drop; -create temp table temp_inh_oncommit_test1 () - inherits(temp_inh_oncommit_test) on commit delete rows; -insert into temp_inh_oncommit_test1 values (1); -commit; --- no relations remain in this case -select relname from pg_class where relname ~ '^temp_inh_oncommit_test'; --- Data on the parent is removed, and the child goes away. -begin; -create temp table temp_inh_oncommit_test (a int) on commit delete rows; -create temp table temp_inh_oncommit_test1 () - inherits(temp_inh_oncommit_test) on commit drop; -insert into temp_inh_oncommit_test1 values (1); -insert into temp_inh_oncommit_test values (1); -commit; -select * from temp_inh_oncommit_test; --- one relation remains -select relname from pg_class where relname ~ '^temp_inh_oncommit_test'; -drop table temp_inh_oncommit_test; - --- Tests with two-phase commit --- Transactions creating objects in a temporary namespace cannot be used --- with two-phase commit. - --- These cases generate errors about temporary namespace. --- Function creation -begin; -create function pg_temp.twophase_func() returns void as - $$ select '2pc_func'::text $$ language sql; -prepare transaction 'twophase_func'; --- Function drop -create function pg_temp.twophase_func() returns void as - $$ select '2pc_func'::text $$ language sql; -begin; -drop function pg_temp.twophase_func(); -prepare transaction 'twophase_func'; --- Operator creation -begin; -create operator pg_temp.@@ (leftarg = int4, rightarg = int4, procedure = int4mi); -prepare transaction 'twophase_operator'; - --- These generate errors about temporary tables. -begin; -create type pg_temp.twophase_type as (a int); -prepare transaction 'twophase_type'; -begin; -create view pg_temp.twophase_view as select 1; -prepare transaction 'twophase_view'; -begin; -create sequence pg_temp.twophase_seq; -prepare transaction 'twophase_sequence'; - --- Temporary tables cannot be used with two-phase commit. -create temp table twophase_tab (a int); -begin; -select a from twophase_tab; -prepare transaction 'twophase_tab'; -begin; -insert into twophase_tab values (1); -prepare transaction 'twophase_tab'; -begin; -lock twophase_tab in access exclusive mode; -prepare transaction 'twophase_tab'; -begin; -drop table twophase_tab; -prepare transaction 'twophase_tab'; - --- Corner case: current_schema may create a temporary schema if namespace --- creation is pending, so check after that. First reset the connection --- to remove the temporary namespace. -\c - -SET search_path TO 'pg_temp'; -BEGIN; -SELECT current_schema() ~ 'pg_temp' AS is_temp_schema; -PREPARE TRANSACTION 'twophase_search'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftest_setup.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftest_setup.sql deleted file mode 100644 index 02c0c84c3a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftest_setup.sql +++ /dev/null @@ -1,282 +0,0 @@ --- --- TEST_SETUP --- prepare environment expected by regression test scripts --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv abs_srcdir PG_ABS_SRCDIR -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set regresslib :libdir '/regress' :dlsuffix - --- --- synchronous_commit=off delays when hint bits may be set. Some plans change --- depending on the number of all-visible pages, which in turn can be --- influenced by the delayed hint bits. Force synchronous_commit=on to avoid --- that source of variability. --- -SET synchronous_commit = on; - --- --- Postgres formerly made the public schema read/write by default, --- and most of the core regression tests still expect that. --- -GRANT ALL ON SCHEMA public TO public; - --- --- These tables have traditionally been referenced by many tests, --- so create and populate them. Insert only non-error values here. --- (Some subsequent tests try to insert erroneous values. That's okay --- because the table won't actually change. Do not change the contents --- of these tables in later tests, as it may affect other tests.) --- - -CREATE TABLE CHAR_TBL(f1 char(4)); - -INSERT INTO CHAR_TBL (f1) VALUES - ('a'), - ('ab'), - ('abcd'), - ('abcd '); -VACUUM CHAR_TBL; - -CREATE TABLE FLOAT8_TBL(f1 float8); - -INSERT INTO FLOAT8_TBL(f1) VALUES - ('0.0'), - ('-34.84'), - ('-1004.30'), - ('-1.2345678901234e+200'), - ('-1.2345678901234e-200'); -VACUUM FLOAT8_TBL; - -CREATE TABLE INT2_TBL(f1 int2); - -INSERT INTO INT2_TBL(f1) VALUES - ('0 '), - (' 1234 '), - (' -1234'), - ('32767'), -- largest and smallest values - ('-32767'); -VACUUM INT2_TBL; - -CREATE TABLE INT4_TBL(f1 int4); - -INSERT INTO INT4_TBL(f1) VALUES - (' 0 '), - ('123456 '), - (' -123456'), - ('2147483647'), -- largest and smallest values - ('-2147483647'); -VACUUM INT4_TBL; - -CREATE TABLE INT8_TBL(q1 int8, q2 int8); - -INSERT INTO INT8_TBL VALUES - (' 123 ',' 456'), - ('123 ','4567890123456789'), - ('4567890123456789','123'), - (+4567890123456789,'4567890123456789'), - ('+4567890123456789','-4567890123456789'); -VACUUM INT8_TBL; - -CREATE TABLE POINT_TBL(f1 point); - -INSERT INTO POINT_TBL(f1) VALUES - ('(0.0,0.0)'), - ('(-10.0,0.0)'), - ('(-3.0,4.0)'), - ('(5.1, 34.5)'), - ('(-5.0,-12.0)'), - ('(1e-300,-1e-300)'), -- To underflow - ('(1e+300,Inf)'), -- To overflow - ('(Inf,1e+300)'), -- Transposed - (' ( Nan , NaN ) '), - ('10.0,10.0'); --- We intentionally don't vacuum point_tbl here; geometry depends on that - -CREATE TABLE TEXT_TBL (f1 text); - -INSERT INTO TEXT_TBL VALUES - ('doh!'), - ('hi de ho neighbor'); -VACUUM TEXT_TBL; - -CREATE TABLE VARCHAR_TBL(f1 varchar(4)); - -INSERT INTO VARCHAR_TBL (f1) VALUES - ('a'), - ('ab'), - ('abcd'), - ('abcd '); -VACUUM VARCHAR_TBL; - -CREATE TABLE onek ( - unique1 int4, - unique2 int4, - two int4, - four int4, - ten int4, - twenty int4, - hundred int4, - thousand int4, - twothousand int4, - fivethous int4, - tenthous int4, - odd int4, - even int4, - stringu1 name, - stringu2 name, - string4 name -); - -\set filename :abs_srcdir '/data/onek.data' -COPY onek FROM :'filename'; -VACUUM ANALYZE onek; - -CREATE TABLE onek2 AS SELECT * FROM onek; -VACUUM ANALYZE onek2; - -CREATE TABLE tenk1 ( - unique1 int4, - unique2 int4, - two int4, - four int4, - ten int4, - twenty int4, - hundred int4, - thousand int4, - twothousand int4, - fivethous int4, - tenthous int4, - odd int4, - even int4, - stringu1 name, - stringu2 name, - string4 name -); - -\set filename :abs_srcdir '/data/tenk.data' -COPY tenk1 FROM :'filename'; -VACUUM ANALYZE tenk1; - -CREATE TABLE tenk2 AS SELECT * FROM tenk1; -VACUUM ANALYZE tenk2; - -CREATE TABLE person ( - name text, - age int4, - location point -); - -\set filename :abs_srcdir '/data/person.data' -COPY person FROM :'filename'; -VACUUM ANALYZE person; - -CREATE TABLE emp ( - salary int4, - manager name -) INHERITS (person); - -\set filename :abs_srcdir '/data/emp.data' -COPY emp FROM :'filename'; -VACUUM ANALYZE emp; - -CREATE TABLE student ( - gpa float8 -) INHERITS (person); - -\set filename :abs_srcdir '/data/student.data' -COPY student FROM :'filename'; -VACUUM ANALYZE student; - -CREATE TABLE stud_emp ( - percent int4 -) INHERITS (emp, student); - -\set filename :abs_srcdir '/data/stud_emp.data' -COPY stud_emp FROM :'filename'; -VACUUM ANALYZE stud_emp; - -CREATE TABLE road ( - name text, - thepath path -); - -\set filename :abs_srcdir '/data/streets.data' -COPY road FROM :'filename'; -VACUUM ANALYZE road; - -CREATE TABLE ihighway () INHERITS (road); - -INSERT INTO ihighway - SELECT * - FROM ONLY road - WHERE name ~ 'I- .*'; -VACUUM ANALYZE ihighway; - -CREATE TABLE shighway ( - surface text -) INHERITS (road); - -INSERT INTO shighway - SELECT *, 'asphalt' - FROM ONLY road - WHERE name ~ 'State Hwy.*'; -VACUUM ANALYZE shighway; - --- --- We must have some enum type in the database for opr_sanity and type_sanity. --- - -create type stoplight as enum ('red', 'yellow', 'green'); - --- --- Also create some non-built-in range types. --- - -create type float8range as range (subtype = float8, subtype_diff = float8mi); - -create type textrange as range (subtype = text, collation = "C"); - --- --- Create some C functions that will be used by various tests. --- - -CREATE FUNCTION binary_coercible(oid, oid) - RETURNS bool - AS :'regresslib', 'binary_coercible' - LANGUAGE C STRICT STABLE PARALLEL SAFE; - -CREATE FUNCTION ttdummy () - RETURNS trigger - AS :'regresslib' - LANGUAGE C; - -CREATE FUNCTION get_columns_length(oid[]) - RETURNS int - AS :'regresslib' - LANGUAGE C STRICT STABLE PARALLEL SAFE; - --- Use hand-rolled hash functions and operator classes to get predictable --- result on different machines. The hash function for int4 simply returns --- the sum of the values passed to it and the one for text returns the length --- of the non-empty string value passed to it or 0. - -create function part_hashint4_noop(value int4, seed int8) - returns int8 as $$ - select value + seed; - $$ language sql strict immutable parallel safe; - -create operator class part_test_int4_ops for type int4 using hash as - operator 1 =, - function 2 part_hashint4_noop(int4, int8); - -create function part_hashtext_length(value text, seed int8) - returns int8 as $$ - select length(coalesce(value, ''))::int8 - $$ language sql strict immutable parallel safe; - -create operator class part_test_text_ops for type text using hash as - operator 1 =, - function 2 part_hashtext_length(text, int8); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftidrangescan.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftidrangescan.sql deleted file mode 100644 index ac09ebb626..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftidrangescan.sql +++ /dev/null @@ -1,101 +0,0 @@ --- tests for tidrangescans - -SET enable_seqscan TO off; -CREATE TABLE tidrangescan(id integer, data text); - --- empty table -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid < '(1, 0)'; -SELECT ctid FROM tidrangescan WHERE ctid < '(1, 0)'; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid > '(9, 0)'; -SELECT ctid FROM tidrangescan WHERE ctid > '(9, 0)'; - --- insert enough tuples to fill at least two pages -INSERT INTO tidrangescan SELECT i,repeat('x', 100) FROM generate_series(1,200) AS s(i); - --- remove all tuples after the 10th tuple on each page. Trying to ensure --- we get the same layout with all CPU architectures and smaller than standard --- page sizes. -DELETE FROM tidrangescan -WHERE substring(ctid::text FROM ',(\d+)\)')::integer > 10 OR substring(ctid::text FROM '\((\d+),')::integer > 2; -VACUUM tidrangescan; - --- range scans with upper bound -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid < '(1,0)'; -SELECT ctid FROM tidrangescan WHERE ctid < '(1,0)'; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid <= '(1,5)'; -SELECT ctid FROM tidrangescan WHERE ctid <= '(1,5)'; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid < '(0,0)'; -SELECT ctid FROM tidrangescan WHERE ctid < '(0,0)'; - --- range scans with lower bound -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid > '(2,8)'; -SELECT ctid FROM tidrangescan WHERE ctid > '(2,8)'; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE '(2,8)' < ctid; -SELECT ctid FROM tidrangescan WHERE '(2,8)' < ctid; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid >= '(2,8)'; -SELECT ctid FROM tidrangescan WHERE ctid >= '(2,8)'; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid >= '(100,0)'; -SELECT ctid FROM tidrangescan WHERE ctid >= '(100,0)'; - --- range scans with both bounds -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE ctid > '(1,4)' AND '(1,7)' >= ctid; -SELECT ctid FROM tidrangescan WHERE ctid > '(1,4)' AND '(1,7)' >= ctid; - -EXPLAIN (COSTS OFF) -SELECT ctid FROM tidrangescan WHERE '(1,7)' >= ctid AND ctid > '(1,4)'; -SELECT ctid FROM tidrangescan WHERE '(1,7)' >= ctid AND ctid > '(1,4)'; - --- extreme offsets -SELECT ctid FROM tidrangescan WHERE ctid > '(0,65535)' AND ctid < '(1,0)' LIMIT 1; -SELECT ctid FROM tidrangescan WHERE ctid < '(0,0)' LIMIT 1; - -SELECT ctid FROM tidrangescan WHERE ctid > '(4294967295,65535)'; -SELECT ctid FROM tidrangescan WHERE ctid < '(0,0)'; - --- NULLs in the range cannot return tuples -SELECT ctid FROM tidrangescan WHERE ctid >= (SELECT NULL::tid); - --- rescans -EXPLAIN (COSTS OFF) -SELECT t.ctid,t2.c FROM tidrangescan t, -LATERAL (SELECT count(*) c FROM tidrangescan t2 WHERE t2.ctid <= t.ctid) t2 -WHERE t.ctid < '(1,0)'; - -SELECT t.ctid,t2.c FROM tidrangescan t, -LATERAL (SELECT count(*) c FROM tidrangescan t2 WHERE t2.ctid <= t.ctid) t2 -WHERE t.ctid < '(1,0)'; - --- cursors - --- Ensure we get a TID Range scan without a Materialize node. -EXPLAIN (COSTS OFF) -DECLARE c SCROLL CURSOR FOR SELECT ctid FROM tidrangescan WHERE ctid < '(1,0)'; - -BEGIN; -DECLARE c SCROLL CURSOR FOR SELECT ctid FROM tidrangescan WHERE ctid < '(1,0)'; -FETCH NEXT c; -FETCH NEXT c; -FETCH PRIOR c; -FETCH FIRST c; -FETCH LAST c; -COMMIT; - -DROP TABLE tidrangescan; - -RESET enable_seqscan; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftidscan.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftidscan.sql deleted file mode 100644 index 313e0fb9b6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftidscan.sql +++ /dev/null @@ -1,104 +0,0 @@ --- tests for tidscans - -CREATE TABLE tidscan(id integer); - --- only insert a few rows, we don't want to spill onto a second table page -INSERT INTO tidscan VALUES (1), (2), (3); - --- show ctids -SELECT ctid, * FROM tidscan; - --- ctid equality - implemented as tidscan -EXPLAIN (COSTS OFF) -SELECT ctid, * FROM tidscan WHERE ctid = '(0,1)'; -SELECT ctid, * FROM tidscan WHERE ctid = '(0,1)'; - -EXPLAIN (COSTS OFF) -SELECT ctid, * FROM tidscan WHERE '(0,1)' = ctid; -SELECT ctid, * FROM tidscan WHERE '(0,1)' = ctid; - --- OR'd clauses -EXPLAIN (COSTS OFF) -SELECT ctid, * FROM tidscan WHERE ctid = '(0,2)' OR '(0,1)' = ctid; -SELECT ctid, * FROM tidscan WHERE ctid = '(0,2)' OR '(0,1)' = ctid; - --- ctid = ScalarArrayOp - implemented as tidscan -EXPLAIN (COSTS OFF) -SELECT ctid, * FROM tidscan WHERE ctid = ANY(ARRAY['(0,1)', '(0,2)']::tid[]); -SELECT ctid, * FROM tidscan WHERE ctid = ANY(ARRAY['(0,1)', '(0,2)']::tid[]); - --- ctid != ScalarArrayOp - can't be implemented as tidscan -EXPLAIN (COSTS OFF) -SELECT ctid, * FROM tidscan WHERE ctid != ANY(ARRAY['(0,1)', '(0,2)']::tid[]); -SELECT ctid, * FROM tidscan WHERE ctid != ANY(ARRAY['(0,1)', '(0,2)']::tid[]); - --- tid equality extracted from sub-AND clauses -EXPLAIN (COSTS OFF) -SELECT ctid, * FROM tidscan -WHERE (id = 3 AND ctid IN ('(0,2)', '(0,3)')) OR (ctid = '(0,1)' AND id = 1); -SELECT ctid, * FROM tidscan -WHERE (id = 3 AND ctid IN ('(0,2)', '(0,3)')) OR (ctid = '(0,1)' AND id = 1); - --- nestloop-with-inner-tidscan joins on tid -SET enable_hashjoin TO off; -- otherwise hash join might win -EXPLAIN (COSTS OFF) -SELECT t1.ctid, t1.*, t2.ctid, t2.* -FROM tidscan t1 JOIN tidscan t2 ON t1.ctid = t2.ctid WHERE t1.id = 1; -SELECT t1.ctid, t1.*, t2.ctid, t2.* -FROM tidscan t1 JOIN tidscan t2 ON t1.ctid = t2.ctid WHERE t1.id = 1; -EXPLAIN (COSTS OFF) -SELECT t1.ctid, t1.*, t2.ctid, t2.* -FROM tidscan t1 LEFT JOIN tidscan t2 ON t1.ctid = t2.ctid WHERE t1.id = 1; -SELECT t1.ctid, t1.*, t2.ctid, t2.* -FROM tidscan t1 LEFT JOIN tidscan t2 ON t1.ctid = t2.ctid WHERE t1.id = 1; -RESET enable_hashjoin; - --- exercise backward scan and rewind -BEGIN; -DECLARE c CURSOR FOR -SELECT ctid, * FROM tidscan WHERE ctid = ANY(ARRAY['(0,1)', '(0,2)']::tid[]); -FETCH ALL FROM c; -FETCH BACKWARD 1 FROM c; -FETCH FIRST FROM c; -ROLLBACK; - --- tidscan via CURRENT OF -BEGIN; -DECLARE c CURSOR FOR SELECT ctid, * FROM tidscan; -FETCH NEXT FROM c; -- skip one row -FETCH NEXT FROM c; --- perform update -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -UPDATE tidscan SET id = -id WHERE CURRENT OF c RETURNING *; -FETCH NEXT FROM c; --- perform update -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -UPDATE tidscan SET id = -id WHERE CURRENT OF c RETURNING *; -SELECT * FROM tidscan; --- position cursor past any rows -FETCH NEXT FROM c; --- should error out -EXPLAIN (ANALYZE, COSTS OFF, SUMMARY OFF, TIMING OFF) -UPDATE tidscan SET id = -id WHERE CURRENT OF c RETURNING *; -ROLLBACK; - --- bulk joins on CTID --- (these plans don't use TID scans, but this still seems like an --- appropriate place for these tests) -EXPLAIN (COSTS OFF) -SELECT count(*) FROM tenk1 t1 JOIN tenk1 t2 ON t1.ctid = t2.ctid; -SELECT count(*) FROM tenk1 t1 JOIN tenk1 t2 ON t1.ctid = t2.ctid; -SET enable_hashjoin TO off; -EXPLAIN (COSTS OFF) -SELECT count(*) FROM tenk1 t1 JOIN tenk1 t2 ON t1.ctid = t2.ctid; -SELECT count(*) FROM tenk1 t1 JOIN tenk1 t2 ON t1.ctid = t2.ctid; -RESET enable_hashjoin; - --- check predicate lock on CTID -BEGIN ISOLATION LEVEL SERIALIZABLE; -SELECT * FROM tidscan WHERE ctid = '(0,1)'; --- locktype should be 'tuple' -SELECT locktype, mode FROM pg_locks WHERE pid = pg_backend_pid() AND mode = 'SIReadLock'; -ROLLBACK; - -DROP TABLE tidscan; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftimestamp.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftimestamp.sql deleted file mode 100644 index ebc969f36c..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftimestamp.sql +++ /dev/null @@ -1,386 +0,0 @@ --- --- TIMESTAMP --- - -CREATE TABLE TIMESTAMP_TBL (d1 timestamp(2) without time zone); - --- Test shorthand input values --- We can't just "select" the results since they aren't constants; test for --- equality instead. We can do that by running the test inside a transaction --- block, within which the value of 'now' shouldn't change, and so these --- related values shouldn't either. - -BEGIN; - -INSERT INTO TIMESTAMP_TBL VALUES ('today'); -INSERT INTO TIMESTAMP_TBL VALUES ('yesterday'); -INSERT INTO TIMESTAMP_TBL VALUES ('tomorrow'); --- time zone should be ignored by this data type -INSERT INTO TIMESTAMP_TBL VALUES ('tomorrow EST'); -INSERT INTO TIMESTAMP_TBL VALUES ('tomorrow zulu'); - -SELECT count(*) AS One FROM TIMESTAMP_TBL WHERE d1 = timestamp without time zone 'today'; -SELECT count(*) AS Three FROM TIMESTAMP_TBL WHERE d1 = timestamp without time zone 'tomorrow'; -SELECT count(*) AS One FROM TIMESTAMP_TBL WHERE d1 = timestamp without time zone 'yesterday'; - -COMMIT; - -DELETE FROM TIMESTAMP_TBL; - --- Verify that 'now' *does* change over a reasonable interval such as 100 msec, --- and that it doesn't change over the same interval within a transaction block - -INSERT INTO TIMESTAMP_TBL VALUES ('now'); -SELECT pg_sleep(0.1); - -BEGIN; -INSERT INTO TIMESTAMP_TBL VALUES ('now'); -SELECT pg_sleep(0.1); -INSERT INTO TIMESTAMP_TBL VALUES ('now'); -SELECT pg_sleep(0.1); -SELECT count(*) AS two FROM TIMESTAMP_TBL WHERE d1 = timestamp(2) without time zone 'now'; -SELECT count(d1) AS three, count(DISTINCT d1) AS two FROM TIMESTAMP_TBL; -COMMIT; - -TRUNCATE TIMESTAMP_TBL; - --- Special values -INSERT INTO TIMESTAMP_TBL VALUES ('-infinity'); -INSERT INTO TIMESTAMP_TBL VALUES ('infinity'); -INSERT INTO TIMESTAMP_TBL VALUES ('epoch'); - --- Postgres v6.0 standard output format -INSERT INTO TIMESTAMP_TBL VALUES ('Mon Feb 10 17:32:01 1997 PST'); - --- Variations on Postgres v6.1 standard output format -INSERT INTO TIMESTAMP_TBL VALUES ('Mon Feb 10 17:32:01.000001 1997 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('Mon Feb 10 17:32:01.999999 1997 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('Mon Feb 10 17:32:01.4 1997 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('Mon Feb 10 17:32:01.5 1997 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('Mon Feb 10 17:32:01.6 1997 PST'); - --- ISO 8601 format -INSERT INTO TIMESTAMP_TBL VALUES ('1997-01-02'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997-01-02 03:04:05'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997-02-10 17:32:01-08'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997-02-10 17:32:01-0800'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997-02-10 17:32:01 -08:00'); -INSERT INTO TIMESTAMP_TBL VALUES ('19970210 173201 -0800'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997-06-10 17:32:01 -07:00'); -INSERT INTO TIMESTAMP_TBL VALUES ('2001-09-22T18:19:20'); - --- POSIX format (note that the timezone abbrev is just decoration here) -INSERT INTO TIMESTAMP_TBL VALUES ('2000-03-15 08:14:01 GMT+8'); -INSERT INTO TIMESTAMP_TBL VALUES ('2000-03-15 13:14:02 GMT-1'); -INSERT INTO TIMESTAMP_TBL VALUES ('2000-03-15 12:14:03 GMT-2'); -INSERT INTO TIMESTAMP_TBL VALUES ('2000-03-15 03:14:04 PST+8'); -INSERT INTO TIMESTAMP_TBL VALUES ('2000-03-15 02:14:05 MST+7:00'); - --- Variations for acceptable input formats -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 10 17:32:01 1997 -0800'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 10 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 10 5:32PM 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997/02/10 17:32:01-0800'); -INSERT INTO TIMESTAMP_TBL VALUES ('1997-02-10 17:32:01 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb-10-1997 17:32:01 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('02-10-1997 17:32:01 PST'); -INSERT INTO TIMESTAMP_TBL VALUES ('19970210 173201 PST'); -set datestyle to ymd; -INSERT INTO TIMESTAMP_TBL VALUES ('97FEB10 5:32:01PM UTC'); -INSERT INTO TIMESTAMP_TBL VALUES ('97/02/10 17:32:01 UTC'); -reset datestyle; -INSERT INTO TIMESTAMP_TBL VALUES ('1997.041 17:32:01 UTC'); -INSERT INTO TIMESTAMP_TBL VALUES ('19970210 173201 America/New_York'); --- this fails (even though TZ is a no-op, we still look it up) -INSERT INTO TIMESTAMP_TBL VALUES ('19970710 173201 America/Does_not_exist'); - --- Check date conversion and date arithmetic -INSERT INTO TIMESTAMP_TBL VALUES ('1997-06-10 18:32:01 PDT'); - -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 10 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 11 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 12 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 13 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 14 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 15 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 1997'); - -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 0097 BC'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 0097'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 0597'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 1097'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 1697'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 1797'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 1897'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 2097'); - -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 28 17:32:01 1996'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 29 17:32:01 1996'); -INSERT INTO TIMESTAMP_TBL VALUES ('Mar 01 17:32:01 1996'); -INSERT INTO TIMESTAMP_TBL VALUES ('Dec 30 17:32:01 1996'); -INSERT INTO TIMESTAMP_TBL VALUES ('Dec 31 17:32:01 1996'); -INSERT INTO TIMESTAMP_TBL VALUES ('Jan 01 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 28 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 29 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Mar 01 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Dec 30 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Dec 31 17:32:01 1997'); -INSERT INTO TIMESTAMP_TBL VALUES ('Dec 31 17:32:01 1999'); -INSERT INTO TIMESTAMP_TBL VALUES ('Jan 01 17:32:01 2000'); -INSERT INTO TIMESTAMP_TBL VALUES ('Dec 31 17:32:01 2000'); -INSERT INTO TIMESTAMP_TBL VALUES ('Jan 01 17:32:01 2001'); - --- Currently unsupported syntax and ranges -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 -0097'); -INSERT INTO TIMESTAMP_TBL VALUES ('Feb 16 17:32:01 5097 BC'); - -SELECT d1 FROM TIMESTAMP_TBL; - --- Check behavior at the boundaries of the timestamp range -SELECT '4714-11-24 00:00:00 BC'::timestamp; -SELECT '4714-11-23 23:59:59 BC'::timestamp; -- out of range -SELECT '294276-12-31 23:59:59'::timestamp; -SELECT '294277-01-01 00:00:00'::timestamp; -- out of range - --- Demonstrate functions and operators -SELECT d1 FROM TIMESTAMP_TBL - WHERE d1 > timestamp without time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMP_TBL - WHERE d1 < timestamp without time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMP_TBL - WHERE d1 = timestamp without time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMP_TBL - WHERE d1 != timestamp without time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMP_TBL - WHERE d1 <= timestamp without time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMP_TBL - WHERE d1 >= timestamp without time zone '1997-01-02'; - -SELECT d1 - timestamp without time zone '1997-01-02' AS diff - FROM TIMESTAMP_TBL WHERE d1 BETWEEN '1902-01-01' AND '2038-01-01'; - -SELECT date_trunc( 'week', timestamp '2004-02-29 15:44:17.71393' ) AS week_trunc; - --- verify date_bin behaves the same as date_trunc for relevant intervals - --- case 1: AD dates, origin < input -SELECT - str, - interval, - date_trunc(str, ts) = date_bin(interval::interval, ts, timestamp '2001-01-01') AS equal -FROM ( - VALUES - ('week', '7 d'), - ('day', '1 d'), - ('hour', '1 h'), - ('minute', '1 m'), - ('second', '1 s'), - ('millisecond', '1 ms'), - ('microsecond', '1 us') -) intervals (str, interval), -(VALUES (timestamp '2020-02-29 15:44:17.71393')) ts (ts); - --- case 2: BC dates, origin < input -SELECT - str, - interval, - date_trunc(str, ts) = date_bin(interval::interval, ts, timestamp '2000-01-01 BC') AS equal -FROM ( - VALUES - ('week', '7 d'), - ('day', '1 d'), - ('hour', '1 h'), - ('minute', '1 m'), - ('second', '1 s'), - ('millisecond', '1 ms'), - ('microsecond', '1 us') -) intervals (str, interval), -(VALUES (timestamp '0055-6-10 15:44:17.71393 BC')) ts (ts); - --- case 3: AD dates, origin > input -SELECT - str, - interval, - date_trunc(str, ts) = date_bin(interval::interval, ts, timestamp '2020-03-02') AS equal -FROM ( - VALUES - ('week', '7 d'), - ('day', '1 d'), - ('hour', '1 h'), - ('minute', '1 m'), - ('second', '1 s'), - ('millisecond', '1 ms'), - ('microsecond', '1 us') -) intervals (str, interval), -(VALUES (timestamp '2020-02-29 15:44:17.71393')) ts (ts); - --- case 4: BC dates, origin > input -SELECT - str, - interval, - date_trunc(str, ts) = date_bin(interval::interval, ts, timestamp '0055-06-17 BC') AS equal -FROM ( - VALUES - ('week', '7 d'), - ('day', '1 d'), - ('hour', '1 h'), - ('minute', '1 m'), - ('second', '1 s'), - ('millisecond', '1 ms'), - ('microsecond', '1 us') -) intervals (str, interval), -(VALUES (timestamp '0055-6-10 15:44:17.71393 BC')) ts (ts); - --- bin timestamps into arbitrary intervals -SELECT - interval, - ts, - origin, - date_bin(interval::interval, ts, origin) -FROM ( - VALUES - ('15 days'), - ('2 hours'), - ('1 hour 30 minutes'), - ('15 minutes'), - ('10 seconds'), - ('100 milliseconds'), - ('250 microseconds') -) intervals (interval), -(VALUES (timestamp '2020-02-11 15:44:17.71393')) ts (ts), -(VALUES (timestamp '2001-01-01')) origin (origin); - --- shift bins using the origin parameter: -SELECT date_bin('5 min'::interval, timestamp '2020-02-01 01:01:01', timestamp '2020-02-01 00:02:30'); - --- disallow intervals with months or years -SELECT date_bin('5 months'::interval, timestamp '2020-02-01 01:01:01', timestamp '2001-01-01'); -SELECT date_bin('5 years'::interval, timestamp '2020-02-01 01:01:01', timestamp '2001-01-01'); - --- disallow zero intervals -SELECT date_bin('0 days'::interval, timestamp '1970-01-01 01:00:00' , timestamp '1970-01-01 00:00:00'); - --- disallow negative intervals -SELECT date_bin('-2 days'::interval, timestamp '1970-01-01 01:00:00' , timestamp '1970-01-01 00:00:00'); - --- Test casting within a BETWEEN qualifier -SELECT d1 - timestamp without time zone '1997-01-02' AS diff - FROM TIMESTAMP_TBL - WHERE d1 BETWEEN timestamp without time zone '1902-01-01' - AND timestamp without time zone '2038-01-01'; - --- DATE_PART (timestamp_part) -SELECT d1 as "timestamp", - date_part( 'year', d1) AS year, date_part( 'month', d1) AS month, - date_part( 'day', d1) AS day, date_part( 'hour', d1) AS hour, - date_part( 'minute', d1) AS minute, date_part( 'second', d1) AS second - FROM TIMESTAMP_TBL; - -SELECT d1 as "timestamp", - date_part( 'quarter', d1) AS quarter, date_part( 'msec', d1) AS msec, - date_part( 'usec', d1) AS usec - FROM TIMESTAMP_TBL; - -SELECT d1 as "timestamp", - date_part( 'isoyear', d1) AS isoyear, date_part( 'week', d1) AS week, - date_part( 'isodow', d1) AS isodow, date_part( 'dow', d1) AS dow, - date_part( 'doy', d1) AS doy - FROM TIMESTAMP_TBL; - -SELECT d1 as "timestamp", - date_part( 'decade', d1) AS decade, - date_part( 'century', d1) AS century, - date_part( 'millennium', d1) AS millennium, - round(date_part( 'julian', d1)) AS julian, - date_part( 'epoch', d1) AS epoch - FROM TIMESTAMP_TBL; - --- extract implementation is mostly the same as date_part, so only --- test a few cases for additional coverage. -SELECT d1 as "timestamp", - extract(microseconds from d1) AS microseconds, - extract(milliseconds from d1) AS milliseconds, - extract(seconds from d1) AS seconds, - round(extract(julian from d1)) AS julian, - extract(epoch from d1) AS epoch - FROM TIMESTAMP_TBL; - --- value near upper bound uses special case in code -SELECT date_part('epoch', '294270-01-01 00:00:00'::timestamp); -SELECT extract(epoch from '294270-01-01 00:00:00'::timestamp); --- another internal overflow test case -SELECT extract(epoch from '5000-01-01 00:00:00'::timestamp); - --- TO_CHAR() -SELECT to_char(d1, 'DAY Day day DY Dy dy MONTH Month month RM MON Mon mon') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'FMDAY FMDay FMday FMMONTH FMMonth FMmonth FMRM') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'Y,YYY YYYY YYY YY Y CC Q MM WW DDD DD D J') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'FMY,YYY FMYYYY FMYYY FMYY FMY FMCC FMQ FMMM FMWW FMDDD FMDD FMD FMJ') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'HH HH12 HH24 MI SS SSSS') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, E'"HH:MI:SS is" HH:MI:SS "\\"text between quote marks\\""') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'HH24--text--MI--text--SS') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'YYYYTH YYYYth Jth') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'YYYY A.D. YYYY a.d. YYYY bc HH:MI:SS P.M. HH:MI:SS p.m. HH:MI:SS pm') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'IYYY IYY IY I IW IDDD ID') - FROM TIMESTAMP_TBL; - -SELECT to_char(d1, 'FMIYYY FMIYY FMIY FMI FMIW FMIDDD FMID') - FROM TIMESTAMP_TBL; - -SELECT to_char(d, 'FF1 FF2 FF3 FF4 FF5 FF6 ff1 ff2 ff3 ff4 ff5 ff6 MS US') - FROM (VALUES - ('2018-11-02 12:34:56'::timestamp), - ('2018-11-02 12:34:56.78'), - ('2018-11-02 12:34:56.78901'), - ('2018-11-02 12:34:56.78901234') - ) d(d); - --- Roman months, with upper and lower case. -SELECT i, - to_char(i * interval '1mon', 'rm'), - to_char(i * interval '1mon', 'RM') - FROM generate_series(-13, 13) i; - --- timestamp numeric fields constructor -SELECT make_timestamp(2014, 12, 28, 6, 30, 45.887); -SELECT make_timestamp(-44, 3, 15, 12, 30, 15); --- should fail -select make_timestamp(0, 7, 15, 12, 30, 15); - --- generate_series for timestamp -select * from generate_series('2020-01-01 00:00'::timestamp, - '2020-01-02 03:00'::timestamp, - '1 hour'::interval); --- the LIMIT should allow this to terminate in a reasonable amount of time --- (but that unfortunately doesn't work yet for SELECT * FROM ...) -select generate_series('2022-01-01 00:00'::timestamp, - 'infinity'::timestamp, - '1 month'::interval) limit 10; --- errors -select * from generate_series('2020-01-01 00:00'::timestamp, - '2020-01-02 03:00'::timestamp, - '0 hour'::interval); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftimestamptz.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftimestamptz.sql deleted file mode 100644 index a107abc5a4..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftimestamptz.sql +++ /dev/null @@ -1,589 +0,0 @@ --- --- TIMESTAMPTZ --- - -CREATE TABLE TIMESTAMPTZ_TBL (d1 timestamp(2) with time zone); - --- Test shorthand input values --- We can't just "select" the results since they aren't constants; test for --- equality instead. We can do that by running the test inside a transaction --- block, within which the value of 'now' shouldn't change, and so these --- related values shouldn't either. - -BEGIN; - -INSERT INTO TIMESTAMPTZ_TBL VALUES ('today'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('yesterday'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('tomorrow'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('tomorrow EST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('tomorrow zulu'); - -SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'today'; -SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'tomorrow'; -SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'yesterday'; -SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'tomorrow EST'; -SELECT count(*) AS One FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp with time zone 'tomorrow zulu'; - -COMMIT; - -DELETE FROM TIMESTAMPTZ_TBL; - --- Verify that 'now' *does* change over a reasonable interval such as 100 msec, --- and that it doesn't change over the same interval within a transaction block - -INSERT INTO TIMESTAMPTZ_TBL VALUES ('now'); -SELECT pg_sleep(0.1); - -BEGIN; -INSERT INTO TIMESTAMPTZ_TBL VALUES ('now'); -SELECT pg_sleep(0.1); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('now'); -SELECT pg_sleep(0.1); -SELECT count(*) AS two FROM TIMESTAMPTZ_TBL WHERE d1 = timestamp(2) with time zone 'now'; -SELECT count(d1) AS three, count(DISTINCT d1) AS two FROM TIMESTAMPTZ_TBL; -COMMIT; - -TRUNCATE TIMESTAMPTZ_TBL; - --- Special values -INSERT INTO TIMESTAMPTZ_TBL VALUES ('-infinity'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('infinity'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('epoch'); - --- Postgres v6.0 standard output format -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01 1997 PST'); - --- Variations on Postgres v6.1 standard output format -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01.000001 1997 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01.999999 1997 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01.4 1997 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01.5 1997 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mon Feb 10 17:32:01.6 1997 PST'); - --- ISO 8601 format -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-01-02'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-01-02 03:04:05'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01-08'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01-0800'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01 -08:00'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('19970210 173201 -0800'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-06-10 17:32:01 -07:00'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('2001-09-22T18:19:20'); - --- POSIX format (note that the timezone abbrev is just decoration here) -INSERT INTO TIMESTAMPTZ_TBL VALUES ('2000-03-15 08:14:01 GMT+8'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('2000-03-15 13:14:02 GMT-1'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('2000-03-15 12:14:03 GMT-2'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('2000-03-15 03:14:04 PST+8'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('2000-03-15 02:14:05 MST+7:00'); - --- Variations for acceptable input formats -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 10 17:32:01 1997 -0800'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 10 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 10 5:32PM 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997/02/10 17:32:01-0800'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-02-10 17:32:01 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb-10-1997 17:32:01 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('02-10-1997 17:32:01 PST'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('19970210 173201 PST'); -set datestyle to ymd; -INSERT INTO TIMESTAMPTZ_TBL VALUES ('97FEB10 5:32:01PM UTC'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('97/02/10 17:32:01 UTC'); -reset datestyle; -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997.041 17:32:01 UTC'); - --- timestamps at different timezones -INSERT INTO TIMESTAMPTZ_TBL VALUES ('19970210 173201 America/New_York'); -SELECT '19970210 173201' AT TIME ZONE 'America/New_York'; -INSERT INTO TIMESTAMPTZ_TBL VALUES ('19970710 173201 America/New_York'); -SELECT '19970710 173201' AT TIME ZONE 'America/New_York'; -INSERT INTO TIMESTAMPTZ_TBL VALUES ('19970710 173201 America/Does_not_exist'); -SELECT '19970710 173201' AT TIME ZONE 'America/Does_not_exist'; - --- Daylight saving time for timestamps beyond 32-bit time_t range. -SELECT '20500710 173201 Europe/Helsinki'::timestamptz; -- DST -SELECT '20500110 173201 Europe/Helsinki'::timestamptz; -- non-DST - -SELECT '205000-07-10 17:32:01 Europe/Helsinki'::timestamptz; -- DST -SELECT '205000-01-10 17:32:01 Europe/Helsinki'::timestamptz; -- non-DST - --- Check date conversion and date arithmetic -INSERT INTO TIMESTAMPTZ_TBL VALUES ('1997-06-10 18:32:01 PDT'); - -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 10 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 11 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 12 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 13 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 14 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 15 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1997'); - -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 0097 BC'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 0097'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 0597'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1097'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1697'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1797'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1897'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 2097'); - -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 28 17:32:01 1996'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 29 17:32:01 1996'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mar 01 17:32:01 1996'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Dec 30 17:32:01 1996'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Dec 31 17:32:01 1996'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Jan 01 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 28 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 29 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Mar 01 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Dec 30 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Dec 31 17:32:01 1997'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Dec 31 17:32:01 1999'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Jan 01 17:32:01 2000'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Dec 31 17:32:01 2000'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Jan 01 17:32:01 2001'); - --- Currently unsupported syntax and ranges -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 -0097'); -INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 5097 BC'); - --- Alternative field order that we've historically supported (sort of) --- with regular and POSIXy timezone specs -SELECT 'Wed Jul 11 10:51:14 America/New_York 2001'::timestamptz; -SELECT 'Wed Jul 11 10:51:14 GMT-4 2001'::timestamptz; -SELECT 'Wed Jul 11 10:51:14 GMT+4 2001'::timestamptz; -SELECT 'Wed Jul 11 10:51:14 PST-03:00 2001'::timestamptz; -SELECT 'Wed Jul 11 10:51:14 PST+03:00 2001'::timestamptz; - -SELECT d1 FROM TIMESTAMPTZ_TBL; - --- Check behavior at the boundaries of the timestamp range -SELECT '4714-11-24 00:00:00+00 BC'::timestamptz; -SELECT '4714-11-23 16:00:00-08 BC'::timestamptz; -SELECT 'Sun Nov 23 16:00:00 4714 PST BC'::timestamptz; -SELECT '4714-11-23 23:59:59+00 BC'::timestamptz; -- out of range -SELECT '294276-12-31 23:59:59+00'::timestamptz; -SELECT '294276-12-31 15:59:59-08'::timestamptz; -SELECT '294277-01-01 00:00:00+00'::timestamptz; -- out of range -SELECT '294277-12-31 16:00:00-08'::timestamptz; -- out of range - --- Demonstrate functions and operators -SELECT d1 FROM TIMESTAMPTZ_TBL - WHERE d1 > timestamp with time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMPTZ_TBL - WHERE d1 < timestamp with time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMPTZ_TBL - WHERE d1 = timestamp with time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMPTZ_TBL - WHERE d1 != timestamp with time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMPTZ_TBL - WHERE d1 <= timestamp with time zone '1997-01-02'; - -SELECT d1 FROM TIMESTAMPTZ_TBL - WHERE d1 >= timestamp with time zone '1997-01-02'; - -SELECT d1 - timestamp with time zone '1997-01-02' AS diff - FROM TIMESTAMPTZ_TBL WHERE d1 BETWEEN '1902-01-01' AND '2038-01-01'; - -SELECT date_trunc( 'week', timestamp with time zone '2004-02-29 15:44:17.71393' ) AS week_trunc; - -SELECT date_trunc('day', timestamp with time zone '2001-02-16 20:38:40+00', 'Australia/Sydney') as sydney_trunc; -- zone name -SELECT date_trunc('day', timestamp with time zone '2001-02-16 20:38:40+00', 'GMT') as gmt_trunc; -- fixed-offset abbreviation -SELECT date_trunc('day', timestamp with time zone '2001-02-16 20:38:40+00', 'VET') as vet_trunc; -- variable-offset abbreviation - --- verify date_bin behaves the same as date_trunc for relevant intervals -SELECT - str, - interval, - date_trunc(str, ts, 'Australia/Sydney') = date_bin(interval::interval, ts, timestamp with time zone '2001-01-01+11') AS equal -FROM ( - VALUES - ('day', '1 d'), - ('hour', '1 h'), - ('minute', '1 m'), - ('second', '1 s'), - ('millisecond', '1 ms'), - ('microsecond', '1 us') -) intervals (str, interval), -(VALUES (timestamptz '2020-02-29 15:44:17.71393+00')) ts (ts); - --- bin timestamps into arbitrary intervals -SELECT - interval, - ts, - origin, - date_bin(interval::interval, ts, origin) -FROM ( - VALUES - ('15 days'), - ('2 hours'), - ('1 hour 30 minutes'), - ('15 minutes'), - ('10 seconds'), - ('100 milliseconds'), - ('250 microseconds') -) intervals (interval), -(VALUES (timestamptz '2020-02-11 15:44:17.71393')) ts (ts), -(VALUES (timestamptz '2001-01-01')) origin (origin); - --- shift bins using the origin parameter: -SELECT date_bin('5 min'::interval, timestamptz '2020-02-01 01:01:01+00', timestamptz '2020-02-01 00:02:30+00'); - --- disallow intervals with months or years -SELECT date_bin('5 months'::interval, timestamp with time zone '2020-02-01 01:01:01+00', timestamp with time zone '2001-01-01+00'); -SELECT date_bin('5 years'::interval, timestamp with time zone '2020-02-01 01:01:01+00', timestamp with time zone '2001-01-01+00'); - --- disallow zero intervals -SELECT date_bin('0 days'::interval, timestamp with time zone '1970-01-01 01:00:00+00' , timestamp with time zone '1970-01-01 00:00:00+00'); - --- disallow negative intervals -SELECT date_bin('-2 days'::interval, timestamp with time zone '1970-01-01 01:00:00+00' , timestamp with time zone '1970-01-01 00:00:00+00'); - --- Test casting within a BETWEEN qualifier -SELECT d1 - timestamp with time zone '1997-01-02' AS diff - FROM TIMESTAMPTZ_TBL - WHERE d1 BETWEEN timestamp with time zone '1902-01-01' AND timestamp with time zone '2038-01-01'; - --- DATE_PART (timestamptz_part) -SELECT d1 as timestamptz, - date_part( 'year', d1) AS year, date_part( 'month', d1) AS month, - date_part( 'day', d1) AS day, date_part( 'hour', d1) AS hour, - date_part( 'minute', d1) AS minute, date_part( 'second', d1) AS second - FROM TIMESTAMPTZ_TBL; - -SELECT d1 as timestamptz, - date_part( 'quarter', d1) AS quarter, date_part( 'msec', d1) AS msec, - date_part( 'usec', d1) AS usec - FROM TIMESTAMPTZ_TBL; - -SELECT d1 as timestamptz, - date_part( 'isoyear', d1) AS isoyear, date_part( 'week', d1) AS week, - date_part( 'isodow', d1) AS isodow, date_part( 'dow', d1) AS dow, - date_part( 'doy', d1) AS doy - FROM TIMESTAMPTZ_TBL; - -SELECT d1 as timestamptz, - date_part( 'decade', d1) AS decade, - date_part( 'century', d1) AS century, - date_part( 'millennium', d1) AS millennium, - round(date_part( 'julian', d1)) AS julian, - date_part( 'epoch', d1) AS epoch - FROM TIMESTAMPTZ_TBL; - -SELECT d1 as timestamptz, - date_part( 'timezone', d1) AS timezone, - date_part( 'timezone_hour', d1) AS timezone_hour, - date_part( 'timezone_minute', d1) AS timezone_minute - FROM TIMESTAMPTZ_TBL; - --- extract implementation is mostly the same as date_part, so only --- test a few cases for additional coverage. -SELECT d1 as "timestamp", - extract(microseconds from d1) AS microseconds, - extract(milliseconds from d1) AS milliseconds, - extract(seconds from d1) AS seconds, - round(extract(julian from d1)) AS julian, - extract(epoch from d1) AS epoch - FROM TIMESTAMPTZ_TBL; - --- value near upper bound uses special case in code -SELECT date_part('epoch', '294270-01-01 00:00:00+00'::timestamptz); -SELECT extract(epoch from '294270-01-01 00:00:00+00'::timestamptz); --- another internal overflow test case -SELECT extract(epoch from '5000-01-01 00:00:00+00'::timestamptz); - --- TO_CHAR() -SELECT to_char(d1, 'DAY Day day DY Dy dy MONTH Month month RM MON Mon mon') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'FMDAY FMDay FMday FMMONTH FMMonth FMmonth FMRM') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'Y,YYY YYYY YYY YY Y CC Q MM WW DDD DD D J') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'FMY,YYY FMYYYY FMYYY FMYY FMY FMCC FMQ FMMM FMWW FMDDD FMDD FMD FMJ') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'HH HH12 HH24 MI SS SSSS') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, E'"HH:MI:SS is" HH:MI:SS "\\"text between quote marks\\""') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'HH24--text--MI--text--SS') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'YYYYTH YYYYth Jth') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'YYYY A.D. YYYY a.d. YYYY bc HH:MI:SS P.M. HH:MI:SS p.m. HH:MI:SS pm') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'IYYY IYY IY I IW IDDD ID') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d1, 'FMIYYY FMIYY FMIY FMI FMIW FMIDDD FMID') - FROM TIMESTAMPTZ_TBL; - -SELECT to_char(d, 'FF1 FF2 FF3 FF4 FF5 FF6 ff1 ff2 ff3 ff4 ff5 ff6 MS US') - FROM (VALUES - ('2018-11-02 12:34:56'::timestamptz), - ('2018-11-02 12:34:56.78'), - ('2018-11-02 12:34:56.78901'), - ('2018-11-02 12:34:56.78901234') - ) d(d); - --- Check OF, TZH, TZM with various zone offsets, particularly fractional hours -SET timezone = '00:00'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '+02:00'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '-13:00'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '-00:30'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '00:30'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '-04:30'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '04:30'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '-04:15'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -SET timezone = '04:15'; -SELECT to_char(now(), 'OF') as "OF", to_char(now(), 'TZH:TZM') as "TZH:TZM"; -RESET timezone; - --- Check of, tzh, tzm with various zone offsets. -SET timezone = '00:00'; -SELECT to_char(now(), 'of') as "Of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '+02:00'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '-13:00'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '-00:30'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '00:30'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '-04:30'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '04:30'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '-04:15'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -SET timezone = '04:15'; -SELECT to_char(now(), 'of') as "of", to_char(now(), 'tzh:tzm') as "tzh:tzm"; -RESET timezone; - - -CREATE TABLE TIMESTAMPTZ_TST (a int , b timestamptz); - --- Test year field value with len > 4 -INSERT INTO TIMESTAMPTZ_TST VALUES(1, 'Sat Mar 12 23:58:48 1000 IST'); -INSERT INTO TIMESTAMPTZ_TST VALUES(2, 'Sat Mar 12 23:58:48 10000 IST'); -INSERT INTO TIMESTAMPTZ_TST VALUES(3, 'Sat Mar 12 23:58:48 100000 IST'); -INSERT INTO TIMESTAMPTZ_TST VALUES(3, '10000 Mar 12 23:58:48 IST'); -INSERT INTO TIMESTAMPTZ_TST VALUES(4, '100000312 23:58:48 IST'); -INSERT INTO TIMESTAMPTZ_TST VALUES(4, '1000000312 23:58:48 IST'); ---Verify data -SELECT * FROM TIMESTAMPTZ_TST ORDER BY a; ---Cleanup -DROP TABLE TIMESTAMPTZ_TST; - --- test timestamptz constructors -set TimeZone to 'America/New_York'; - --- numeric timezone -SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33); -SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '+2'); -SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '-2'); -WITH tzs (tz) AS (VALUES - ('+1'), ('+1:'), ('+1:0'), ('+100'), ('+1:00'), ('+01:00'), - ('+10'), ('+1000'), ('+10:'), ('+10:0'), ('+10:00'), ('+10:00:'), - ('+10:00:1'), ('+10:00:01'), - ('+10:00:10')) - SELECT make_timestamptz(2010, 2, 27, 3, 45, 00, tz), tz FROM tzs; - --- these should fail -SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '2'); -SELECT make_timestamptz(2014, 12, 10, 10, 10, 10, '+16'); -SELECT make_timestamptz(2014, 12, 10, 10, 10, 10, '-16'); - --- should be true -SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '+2') = '1973-07-15 08:15:55.33+02'::timestamptz; - --- full timezone names -SELECT make_timestamptz(2014, 12, 10, 0, 0, 0, 'Europe/Prague') = timestamptz '2014-12-10 00:00:00 Europe/Prague'; -SELECT make_timestamptz(2014, 12, 10, 0, 0, 0, 'Europe/Prague') AT TIME ZONE 'UTC'; -SELECT make_timestamptz(1846, 12, 10, 0, 0, 0, 'Asia/Manila') AT TIME ZONE 'UTC'; -SELECT make_timestamptz(1881, 12, 10, 0, 0, 0, 'Europe/Paris') AT TIME ZONE 'UTC'; -SELECT make_timestamptz(1910, 12, 24, 0, 0, 0, 'Nehwon/Lankhmar'); - --- abbreviations -SELECT make_timestamptz(2008, 12, 10, 10, 10, 10, 'EST'); -SELECT make_timestamptz(2008, 12, 10, 10, 10, 10, 'EDT'); -SELECT make_timestamptz(2014, 12, 10, 10, 10, 10, 'PST8PDT'); - -RESET TimeZone; - --- generate_series for timestamptz -select * from generate_series('2020-01-01 00:00'::timestamptz, - '2020-01-02 03:00'::timestamptz, - '1 hour'::interval); --- the LIMIT should allow this to terminate in a reasonable amount of time --- (but that unfortunately doesn't work yet for SELECT * FROM ...) -select generate_series('2022-01-01 00:00'::timestamptz, - 'infinity'::timestamptz, - '1 month'::interval) limit 10; --- errors -select * from generate_series('2020-01-01 00:00'::timestamptz, - '2020-01-02 03:00'::timestamptz, - '0 hour'::interval); - --- --- Test behavior with a dynamic (time-varying) timezone abbreviation. --- These tests rely on the knowledge that MSK (Europe/Moscow standard time) --- moved forwards in Mar 2011 and backwards again in Oct 2014. --- - -SET TimeZone to 'UTC'; - -SELECT '2011-03-27 00:00:00 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 01:00:00 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 01:59:59 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 02:00:00 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 02:00:01 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 02:59:59 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 03:00:00 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 03:00:01 Europe/Moscow'::timestamptz; -SELECT '2011-03-27 04:00:00 Europe/Moscow'::timestamptz; - -SELECT '2011-03-27 00:00:00 MSK'::timestamptz; -SELECT '2011-03-27 01:00:00 MSK'::timestamptz; -SELECT '2011-03-27 01:59:59 MSK'::timestamptz; -SELECT '2011-03-27 02:00:00 MSK'::timestamptz; -SELECT '2011-03-27 02:00:01 MSK'::timestamptz; -SELECT '2011-03-27 02:59:59 MSK'::timestamptz; -SELECT '2011-03-27 03:00:00 MSK'::timestamptz; -SELECT '2011-03-27 03:00:01 MSK'::timestamptz; -SELECT '2011-03-27 04:00:00 MSK'::timestamptz; - -SELECT '2014-10-26 00:00:00 Europe/Moscow'::timestamptz; -SELECT '2014-10-26 00:59:59 Europe/Moscow'::timestamptz; -SELECT '2014-10-26 01:00:00 Europe/Moscow'::timestamptz; -SELECT '2014-10-26 01:00:01 Europe/Moscow'::timestamptz; -SELECT '2014-10-26 02:00:00 Europe/Moscow'::timestamptz; - -SELECT '2014-10-26 00:00:00 MSK'::timestamptz; -SELECT '2014-10-26 00:59:59 MSK'::timestamptz; -SELECT '2014-10-26 01:00:00 MSK'::timestamptz; -SELECT '2014-10-26 01:00:01 MSK'::timestamptz; -SELECT '2014-10-26 02:00:00 MSK'::timestamptz; - -SELECT '2011-03-27 00:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 01:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 01:59:59'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 02:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 02:00:01'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 02:59:59'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 03:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 03:00:01'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 04:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; - -SELECT '2011-03-27 00:00:00'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 01:00:00'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 01:59:59'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 02:00:00'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 02:00:01'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 02:59:59'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 03:00:00'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 03:00:01'::timestamp AT TIME ZONE 'MSK'; -SELECT '2011-03-27 04:00:00'::timestamp AT TIME ZONE 'MSK'; - -SELECT '2014-10-26 00:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-26 00:59:59'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-26 01:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-26 01:00:01'::timestamp AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-26 02:00:00'::timestamp AT TIME ZONE 'Europe/Moscow'; - -SELECT '2014-10-26 00:00:00'::timestamp AT TIME ZONE 'MSK'; -SELECT '2014-10-26 00:59:59'::timestamp AT TIME ZONE 'MSK'; -SELECT '2014-10-26 01:00:00'::timestamp AT TIME ZONE 'MSK'; -SELECT '2014-10-26 01:00:01'::timestamp AT TIME ZONE 'MSK'; -SELECT '2014-10-26 02:00:00'::timestamp AT TIME ZONE 'MSK'; - -SELECT make_timestamptz(2014, 10, 26, 0, 0, 0, 'MSK'); -SELECT make_timestamptz(2014, 10, 26, 1, 0, 0, 'MSK'); - -SELECT to_timestamp( 0); -- 1970-01-01 00:00:00+00 -SELECT to_timestamp( 946684800); -- 2000-01-01 00:00:00+00 -SELECT to_timestamp(1262349296.7890123); -- 2010-01-01 12:34:56.789012+00 --- edge cases -SELECT to_timestamp(-210866803200); -- 4714-11-24 00:00:00+00 BC --- upper limit varies between integer and float timestamps, so hard to test --- nonfinite values -SELECT to_timestamp(' Infinity'::float); -SELECT to_timestamp('-Infinity'::float); -SELECT to_timestamp('NaN'::float); - - -SET TimeZone to 'Europe/Moscow'; - -SELECT '2011-03-26 21:00:00 UTC'::timestamptz; -SELECT '2011-03-26 22:00:00 UTC'::timestamptz; -SELECT '2011-03-26 22:59:59 UTC'::timestamptz; -SELECT '2011-03-26 23:00:00 UTC'::timestamptz; -SELECT '2011-03-26 23:00:01 UTC'::timestamptz; -SELECT '2011-03-26 23:59:59 UTC'::timestamptz; -SELECT '2011-03-27 00:00:00 UTC'::timestamptz; - -SELECT '2014-10-25 21:00:00 UTC'::timestamptz; -SELECT '2014-10-25 21:59:59 UTC'::timestamptz; -SELECT '2014-10-25 22:00:00 UTC'::timestamptz; -SELECT '2014-10-25 22:00:01 UTC'::timestamptz; -SELECT '2014-10-25 23:00:00 UTC'::timestamptz; - -RESET TimeZone; - -SELECT '2011-03-26 21:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-26 22:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-26 22:59:59 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-26 23:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-26 23:00:01 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-26 23:59:59 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2011-03-27 00:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; - -SELECT '2014-10-25 21:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-25 21:59:59 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-25 22:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-25 22:00:01 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; -SELECT '2014-10-25 23:00:00 UTC'::timestamptz AT TIME ZONE 'Europe/Moscow'; - -SELECT '2011-03-26 21:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2011-03-26 22:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2011-03-26 22:59:59 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2011-03-26 23:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2011-03-26 23:00:01 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2011-03-26 23:59:59 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2011-03-27 00:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; - -SELECT '2014-10-25 21:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2014-10-25 21:59:59 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2014-10-25 22:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2014-10-25 22:00:01 UTC'::timestamptz AT TIME ZONE 'MSK'; -SELECT '2014-10-25 23:00:00 UTC'::timestamptz AT TIME ZONE 'MSK'; - --- --- Test that AT TIME ZONE isn't misoptimized when using an index (bug #14504) --- -create temp table tmptz (f1 timestamptz primary key); -insert into tmptz values ('2017-01-18 00:00+00'); -explain (costs off) -select * from tmptz where f1 at time zone 'utc' = '2017-01-18 00:00'; -select * from tmptz where f1 at time zone 'utc' = '2017-01-18 00:00'; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftransactions.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftransactions.sql deleted file mode 100644 index d71c3ce93e..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftransactions.sql +++ /dev/null @@ -1,606 +0,0 @@ --- --- TRANSACTIONS --- - -BEGIN; - -CREATE TABLE xacttest (a smallint, b real); -INSERT INTO xacttest VALUES - (56, 7.8), - (100, 99.097), - (0, 0.09561), - (42, 324.78); -INSERT INTO xacttest (a, b) VALUES (777, 777.777); - -END; - --- should retrieve one value-- -SELECT a FROM xacttest WHERE a > 100; - - -BEGIN; - -CREATE TABLE disappear (a int4); - -DELETE FROM xacttest; - --- should be empty -SELECT * FROM xacttest; - -ABORT; - --- should not exist -SELECT oid FROM pg_class WHERE relname = 'disappear'; - --- should have members again -SELECT * FROM xacttest; - - --- Read-only tests - -CREATE TABLE writetest (a int); -CREATE TEMPORARY TABLE temptest (a int); - -BEGIN; -SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE; -- ok -SELECT * FROM writetest; -- ok -SET TRANSACTION READ WRITE; --fail -COMMIT; - -BEGIN; -SET TRANSACTION READ ONLY; -- ok -SET TRANSACTION READ WRITE; -- ok -SET TRANSACTION READ ONLY; -- ok -SELECT * FROM writetest; -- ok -SAVEPOINT x; -SET TRANSACTION READ ONLY; -- ok -SELECT * FROM writetest; -- ok -SET TRANSACTION READ ONLY; -- ok -SET TRANSACTION READ WRITE; --fail -COMMIT; - -BEGIN; -SET TRANSACTION READ WRITE; -- ok -SAVEPOINT x; -SET TRANSACTION READ WRITE; -- ok -SET TRANSACTION READ ONLY; -- ok -SELECT * FROM writetest; -- ok -SET TRANSACTION READ ONLY; -- ok -SET TRANSACTION READ WRITE; --fail -COMMIT; - -BEGIN; -SET TRANSACTION READ WRITE; -- ok -SAVEPOINT x; -SET TRANSACTION READ ONLY; -- ok -SELECT * FROM writetest; -- ok -ROLLBACK TO SAVEPOINT x; -SHOW transaction_read_only; -- off -SAVEPOINT y; -SET TRANSACTION READ ONLY; -- ok -SELECT * FROM writetest; -- ok -RELEASE SAVEPOINT y; -SHOW transaction_read_only; -- off -COMMIT; - -SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY; - -DROP TABLE writetest; -- fail -INSERT INTO writetest VALUES (1); -- fail -SELECT * FROM writetest; -- ok -DELETE FROM temptest; -- ok -UPDATE temptest SET a = 0 FROM writetest WHERE temptest.a = 1 AND writetest.a = temptest.a; -- ok -PREPARE test AS UPDATE writetest SET a = 0; -- ok -EXECUTE test; -- fail -SELECT * FROM writetest, temptest; -- ok -CREATE TABLE test AS SELECT * FROM writetest; -- fail - -START TRANSACTION READ WRITE; -DROP TABLE writetest; -- ok -COMMIT; - --- Subtransactions, basic tests --- create & drop tables -SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE; -CREATE TABLE trans_foobar (a int); -BEGIN; - CREATE TABLE trans_foo (a int); - SAVEPOINT one; - DROP TABLE trans_foo; - CREATE TABLE trans_bar (a int); - ROLLBACK TO SAVEPOINT one; - RELEASE SAVEPOINT one; - SAVEPOINT two; - CREATE TABLE trans_baz (a int); - RELEASE SAVEPOINT two; - drop TABLE trans_foobar; - CREATE TABLE trans_barbaz (a int); -COMMIT; --- should exist: trans_barbaz, trans_baz, trans_foo -SELECT * FROM trans_foo; -- should be empty -SELECT * FROM trans_bar; -- shouldn't exist -SELECT * FROM trans_barbaz; -- should be empty -SELECT * FROM trans_baz; -- should be empty - --- inserts -BEGIN; - INSERT INTO trans_foo VALUES (1); - SAVEPOINT one; - INSERT into trans_bar VALUES (1); - ROLLBACK TO one; - RELEASE SAVEPOINT one; - SAVEPOINT two; - INSERT into trans_barbaz VALUES (1); - RELEASE two; - SAVEPOINT three; - SAVEPOINT four; - INSERT INTO trans_foo VALUES (2); - RELEASE SAVEPOINT four; - ROLLBACK TO SAVEPOINT three; - RELEASE SAVEPOINT three; - INSERT INTO trans_foo VALUES (3); -COMMIT; -SELECT * FROM trans_foo; -- should have 1 and 3 -SELECT * FROM trans_barbaz; -- should have 1 - --- test whole-tree commit -BEGIN; - SAVEPOINT one; - SELECT trans_foo; - ROLLBACK TO SAVEPOINT one; - RELEASE SAVEPOINT one; - SAVEPOINT two; - CREATE TABLE savepoints (a int); - SAVEPOINT three; - INSERT INTO savepoints VALUES (1); - SAVEPOINT four; - INSERT INTO savepoints VALUES (2); - SAVEPOINT five; - INSERT INTO savepoints VALUES (3); - ROLLBACK TO SAVEPOINT five; -COMMIT; -COMMIT; -- should not be in a transaction block -SELECT * FROM savepoints; - --- test whole-tree rollback -BEGIN; - SAVEPOINT one; - DELETE FROM savepoints WHERE a=1; - RELEASE SAVEPOINT one; - SAVEPOINT two; - DELETE FROM savepoints WHERE a=1; - SAVEPOINT three; - DELETE FROM savepoints WHERE a=2; -ROLLBACK; -COMMIT; -- should not be in a transaction block - -SELECT * FROM savepoints; - --- test whole-tree commit on an aborted subtransaction -BEGIN; - INSERT INTO savepoints VALUES (4); - SAVEPOINT one; - INSERT INTO savepoints VALUES (5); - SELECT trans_foo; -COMMIT; -SELECT * FROM savepoints; - -BEGIN; - INSERT INTO savepoints VALUES (6); - SAVEPOINT one; - INSERT INTO savepoints VALUES (7); - RELEASE SAVEPOINT one; - INSERT INTO savepoints VALUES (8); -COMMIT; --- rows 6 and 8 should have been created by the same xact -SELECT a.xmin = b.xmin FROM savepoints a, savepoints b WHERE a.a=6 AND b.a=8; --- rows 6 and 7 should have been created by different xacts -SELECT a.xmin = b.xmin FROM savepoints a, savepoints b WHERE a.a=6 AND b.a=7; - -BEGIN; - INSERT INTO savepoints VALUES (9); - SAVEPOINT one; - INSERT INTO savepoints VALUES (10); - ROLLBACK TO SAVEPOINT one; - INSERT INTO savepoints VALUES (11); -COMMIT; -SELECT a FROM savepoints WHERE a in (9, 10, 11); --- rows 9 and 11 should have been created by different xacts -SELECT a.xmin = b.xmin FROM savepoints a, savepoints b WHERE a.a=9 AND b.a=11; - -BEGIN; - INSERT INTO savepoints VALUES (12); - SAVEPOINT one; - INSERT INTO savepoints VALUES (13); - SAVEPOINT two; - INSERT INTO savepoints VALUES (14); - ROLLBACK TO SAVEPOINT one; - INSERT INTO savepoints VALUES (15); - SAVEPOINT two; - INSERT INTO savepoints VALUES (16); - SAVEPOINT three; - INSERT INTO savepoints VALUES (17); -COMMIT; -SELECT a FROM savepoints WHERE a BETWEEN 12 AND 17; - -BEGIN; - INSERT INTO savepoints VALUES (18); - SAVEPOINT one; - INSERT INTO savepoints VALUES (19); - SAVEPOINT two; - INSERT INTO savepoints VALUES (20); - ROLLBACK TO SAVEPOINT one; - INSERT INTO savepoints VALUES (21); - ROLLBACK TO SAVEPOINT one; - INSERT INTO savepoints VALUES (22); -COMMIT; -SELECT a FROM savepoints WHERE a BETWEEN 18 AND 22; - -DROP TABLE savepoints; - --- only in a transaction block: -SAVEPOINT one; -ROLLBACK TO SAVEPOINT one; -RELEASE SAVEPOINT one; - --- Only "rollback to" allowed in aborted state -BEGIN; - SAVEPOINT one; - SELECT 0/0; - SAVEPOINT two; -- ignored till the end of ... - RELEASE SAVEPOINT one; -- ignored till the end of ... - ROLLBACK TO SAVEPOINT one; - SELECT 1; -COMMIT; -SELECT 1; -- this should work - --- check non-transactional behavior of cursors -BEGIN; - DECLARE c CURSOR FOR SELECT unique2 FROM tenk1 ORDER BY unique2; - SAVEPOINT one; - FETCH 10 FROM c; - ROLLBACK TO SAVEPOINT one; - FETCH 10 FROM c; - RELEASE SAVEPOINT one; - FETCH 10 FROM c; - CLOSE c; - DECLARE c CURSOR FOR SELECT unique2/0 FROM tenk1 ORDER BY unique2; - SAVEPOINT two; - FETCH 10 FROM c; - ROLLBACK TO SAVEPOINT two; - -- c is now dead to the world ... - FETCH 10 FROM c; - ROLLBACK TO SAVEPOINT two; - RELEASE SAVEPOINT two; - FETCH 10 FROM c; -COMMIT; - --- --- Check that "stable" functions are really stable. They should not be --- able to see the partial results of the calling query. (Ideally we would --- also check that they don't see commits of concurrent transactions, but --- that's a mite hard to do within the limitations of pg_regress.) --- -select * from xacttest; - -create or replace function max_xacttest() returns smallint language sql as -'select max(a) from xacttest' stable; - -begin; -update xacttest set a = max_xacttest() + 10 where a > 0; -select * from xacttest; -rollback; - --- But a volatile function can see the partial results of the calling query -create or replace function max_xacttest() returns smallint language sql as -'select max(a) from xacttest' volatile; - -begin; -update xacttest set a = max_xacttest() + 10 where a > 0; -select * from xacttest; -rollback; - --- Now the same test with plpgsql (since it depends on SPI which is different) -create or replace function max_xacttest() returns smallint language plpgsql as -'begin return max(a) from xacttest; end' stable; - -begin; -update xacttest set a = max_xacttest() + 10 where a > 0; -select * from xacttest; -rollback; - -create or replace function max_xacttest() returns smallint language plpgsql as -'begin return max(a) from xacttest; end' volatile; - -begin; -update xacttest set a = max_xacttest() + 10 where a > 0; -select * from xacttest; -rollback; - - --- test case for problems with dropping an open relation during abort -BEGIN; - savepoint x; - CREATE TABLE koju (a INT UNIQUE); - INSERT INTO koju VALUES (1); - INSERT INTO koju VALUES (1); - rollback to x; - - CREATE TABLE koju (a INT UNIQUE); - INSERT INTO koju VALUES (1); - INSERT INTO koju VALUES (1); -ROLLBACK; - -DROP TABLE trans_foo; -DROP TABLE trans_baz; -DROP TABLE trans_barbaz; - - --- test case for problems with revalidating an open relation during abort -create function inverse(int) returns float8 as -$$ -begin - analyze revalidate_bug; - return 1::float8/$1; -exception - when division_by_zero then return 0; -end$$ language plpgsql volatile; - -create table revalidate_bug (c float8 unique); -insert into revalidate_bug values (1); -insert into revalidate_bug values (inverse(0)); - -drop table revalidate_bug; -drop function inverse(int); - - --- verify that cursors created during an aborted subtransaction are --- closed, but that we do not rollback the effect of any FETCHs --- performed in the aborted subtransaction -begin; - -savepoint x; -create table abc (a int); -insert into abc values (5); -insert into abc values (10); -declare foo cursor for select * from abc; -fetch from foo; -rollback to x; - --- should fail -fetch from foo; -commit; - -begin; - -create table abc (a int); -insert into abc values (5); -insert into abc values (10); -insert into abc values (15); -declare foo cursor for select * from abc; - -fetch from foo; - -savepoint x; -fetch from foo; -rollback to x; - -fetch from foo; - -abort; - - --- Test for proper cleanup after a failure in a cursor portal --- that was created in an outer subtransaction -CREATE FUNCTION invert(x float8) RETURNS float8 LANGUAGE plpgsql AS -$$ begin return 1/x; end $$; - -CREATE FUNCTION create_temp_tab() RETURNS text -LANGUAGE plpgsql AS $$ -BEGIN - CREATE TEMP TABLE new_table (f1 float8); - -- case of interest is that we fail while holding an open - -- relcache reference to new_table - INSERT INTO new_table SELECT invert(0.0); - RETURN 'foo'; -END $$; - -BEGIN; -DECLARE ok CURSOR FOR SELECT * FROM int8_tbl; -DECLARE ctt CURSOR FOR SELECT create_temp_tab(); -FETCH ok; -SAVEPOINT s1; -FETCH ok; -- should work -FETCH ctt; -- error occurs here -ROLLBACK TO s1; -FETCH ok; -- should work -FETCH ctt; -- must be rejected -COMMIT; - -DROP FUNCTION create_temp_tab(); -DROP FUNCTION invert(x float8); - - --- Tests for AND CHAIN - -CREATE TABLE abc (a int); - --- set nondefault value so we have something to override below -SET default_transaction_read_only = on; - -START TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ WRITE, DEFERRABLE; -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -INSERT INTO abc VALUES (1); -INSERT INTO abc VALUES (2); -COMMIT AND CHAIN; -- TBLOCK_END -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -INSERT INTO abc VALUES ('error'); -INSERT INTO abc VALUES (3); -- check it's really aborted -COMMIT AND CHAIN; -- TBLOCK_ABORT_END -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -INSERT INTO abc VALUES (4); -COMMIT; - -START TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ WRITE, DEFERRABLE; -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -SAVEPOINT x; -INSERT INTO abc VALUES ('error'); -COMMIT AND CHAIN; -- TBLOCK_ABORT_PENDING -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -INSERT INTO abc VALUES (5); -COMMIT; - -START TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ WRITE, DEFERRABLE; -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -SAVEPOINT x; -COMMIT AND CHAIN; -- TBLOCK_SUBCOMMIT -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -COMMIT; - --- different mix of options just for fun -START TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ WRITE, NOT DEFERRABLE; -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -INSERT INTO abc VALUES (6); -ROLLBACK AND CHAIN; -- TBLOCK_ABORT_PENDING -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -INSERT INTO abc VALUES ('error'); -ROLLBACK AND CHAIN; -- TBLOCK_ABORT_END -SHOW transaction_isolation; -SHOW transaction_read_only; -SHOW transaction_deferrable; -ROLLBACK; - --- not allowed outside a transaction block -COMMIT AND CHAIN; -- error -ROLLBACK AND CHAIN; -- error - -SELECT * FROM abc ORDER BY 1; - -RESET default_transaction_read_only; - -DROP TABLE abc; - - --- Test assorted behaviors around the implicit transaction block created --- when multiple SQL commands are sent in a single Query message. These --- tests rely on the fact that psql will not break SQL commands apart at a --- backslash-quoted semicolon, but will send them as one Query. - -create temp table i_table (f1 int); - --- psql will show all results of a multi-statement Query -SELECT 1\; SELECT 2\; SELECT 3; - --- this implicitly commits: -insert into i_table values(1)\; select * from i_table; --- 1/0 error will cause rolling back the whole implicit transaction -insert into i_table values(2)\; select * from i_table\; select 1/0; -select * from i_table; - -rollback; -- we are not in a transaction at this point - --- can use regular begin/commit/rollback within a single Query -begin\; insert into i_table values(3)\; commit; -rollback; -- we are not in a transaction at this point -begin\; insert into i_table values(4)\; rollback; -rollback; -- we are not in a transaction at this point - --- begin converts implicit transaction into a regular one that --- can extend past the end of the Query -select 1\; begin\; insert into i_table values(5); -commit; -select 1\; begin\; insert into i_table values(6); -rollback; - --- commit in implicit-transaction state commits but issues a warning. -insert into i_table values(7)\; commit\; insert into i_table values(8)\; select 1/0; --- similarly, rollback aborts but issues a warning. -insert into i_table values(9)\; rollback\; select 2; - -select * from i_table; - -rollback; -- we are not in a transaction at this point - --- implicit transaction block is still a transaction block, for e.g. VACUUM -SELECT 1\; VACUUM; -SELECT 1\; COMMIT\; VACUUM; - --- we disallow savepoint-related commands in implicit-transaction state -SELECT 1\; SAVEPOINT sp; -SELECT 1\; COMMIT\; SAVEPOINT sp; -ROLLBACK TO SAVEPOINT sp\; SELECT 2; -SELECT 2\; RELEASE SAVEPOINT sp\; SELECT 3; - --- but this is OK, because the BEGIN converts it to a regular xact -SELECT 1\; BEGIN\; SAVEPOINT sp\; ROLLBACK TO SAVEPOINT sp\; COMMIT; - - --- Tests for AND CHAIN in implicit transaction blocks - -SET TRANSACTION READ ONLY\; COMMIT AND CHAIN; -- error -SHOW transaction_read_only; - -SET TRANSACTION READ ONLY\; ROLLBACK AND CHAIN; -- error -SHOW transaction_read_only; - -CREATE TABLE abc (a int); - --- COMMIT/ROLLBACK + COMMIT/ROLLBACK AND CHAIN -INSERT INTO abc VALUES (7)\; COMMIT\; INSERT INTO abc VALUES (8)\; COMMIT AND CHAIN; -- 7 commit, 8 error -INSERT INTO abc VALUES (9)\; ROLLBACK\; INSERT INTO abc VALUES (10)\; ROLLBACK AND CHAIN; -- 9 rollback, 10 error - --- COMMIT/ROLLBACK AND CHAIN + COMMIT/ROLLBACK -INSERT INTO abc VALUES (11)\; COMMIT AND CHAIN\; INSERT INTO abc VALUES (12)\; COMMIT; -- 11 error, 12 not reached -INSERT INTO abc VALUES (13)\; ROLLBACK AND CHAIN\; INSERT INTO abc VALUES (14)\; ROLLBACK; -- 13 error, 14 not reached - --- START TRANSACTION + COMMIT/ROLLBACK AND CHAIN -START TRANSACTION ISOLATION LEVEL REPEATABLE READ\; INSERT INTO abc VALUES (15)\; COMMIT AND CHAIN; -- 15 ok -SHOW transaction_isolation; -- transaction is active at this point -COMMIT; - -START TRANSACTION ISOLATION LEVEL REPEATABLE READ\; INSERT INTO abc VALUES (16)\; ROLLBACK AND CHAIN; -- 16 ok -SHOW transaction_isolation; -- transaction is active at this point -ROLLBACK; - -SET default_transaction_isolation = 'read committed'; - --- START TRANSACTION + COMMIT/ROLLBACK + COMMIT/ROLLBACK AND CHAIN -START TRANSACTION ISOLATION LEVEL REPEATABLE READ\; INSERT INTO abc VALUES (17)\; COMMIT\; INSERT INTO abc VALUES (18)\; COMMIT AND CHAIN; -- 17 commit, 18 error -SHOW transaction_isolation; -- out of transaction block - -START TRANSACTION ISOLATION LEVEL REPEATABLE READ\; INSERT INTO abc VALUES (19)\; ROLLBACK\; INSERT INTO abc VALUES (20)\; ROLLBACK AND CHAIN; -- 19 rollback, 20 error -SHOW transaction_isolation; -- out of transaction block - -RESET default_transaction_isolation; - -SELECT * FROM abc ORDER BY 1; - -DROP TABLE abc; - - --- Test for successful cleanup of an aborted transaction at session exit. --- THIS MUST BE THE LAST TEST IN THIS FILE. - -begin; -select 1/0; -rollback to X; - --- DO NOT ADD ANYTHING HERE. diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftriggers.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftriggers.sql deleted file mode 100644 index 83cd00f54f..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftriggers.sql +++ /dev/null @@ -1,2706 +0,0 @@ --- --- TRIGGERS --- - --- directory paths and dlsuffix are passed to us in environment variables -\getenv libdir PG_LIBDIR -\getenv dlsuffix PG_DLSUFFIX - -\set autoinclib :libdir '/autoinc' :dlsuffix -\set refintlib :libdir '/refint' :dlsuffix -\set regresslib :libdir '/regress' :dlsuffix - -CREATE FUNCTION autoinc () - RETURNS trigger - AS :'autoinclib' - LANGUAGE C; - -CREATE FUNCTION check_primary_key () - RETURNS trigger - AS :'refintlib' - LANGUAGE C; - -CREATE FUNCTION check_foreign_key () - RETURNS trigger - AS :'refintlib' - LANGUAGE C; - -CREATE FUNCTION trigger_return_old () - RETURNS trigger - AS :'regresslib' - LANGUAGE C; - -CREATE FUNCTION set_ttdummy (int4) - RETURNS int4 - AS :'regresslib' - LANGUAGE C STRICT; - -create table pkeys (pkey1 int4 not null, pkey2 text not null); -create table fkeys (fkey1 int4, fkey2 text, fkey3 int); -create table fkeys2 (fkey21 int4, fkey22 text, pkey23 int not null); - -create index fkeys_i on fkeys (fkey1, fkey2); -create index fkeys2_i on fkeys2 (fkey21, fkey22); -create index fkeys2p_i on fkeys2 (pkey23); - -insert into pkeys values (10, '1'); -insert into pkeys values (20, '2'); -insert into pkeys values (30, '3'); -insert into pkeys values (40, '4'); -insert into pkeys values (50, '5'); -insert into pkeys values (60, '6'); -create unique index pkeys_i on pkeys (pkey1, pkey2); - --- --- For fkeys: --- (fkey1, fkey2) --> pkeys (pkey1, pkey2) --- (fkey3) --> fkeys2 (pkey23) --- -create trigger check_fkeys_pkey_exist - before insert or update on fkeys - for each row - execute function - check_primary_key ('fkey1', 'fkey2', 'pkeys', 'pkey1', 'pkey2'); - -create trigger check_fkeys_pkey2_exist - before insert or update on fkeys - for each row - execute function check_primary_key ('fkey3', 'fkeys2', 'pkey23'); - --- --- For fkeys2: --- (fkey21, fkey22) --> pkeys (pkey1, pkey2) --- -create trigger check_fkeys2_pkey_exist - before insert or update on fkeys2 - for each row - execute procedure - check_primary_key ('fkey21', 'fkey22', 'pkeys', 'pkey1', 'pkey2'); - --- Test comments -COMMENT ON TRIGGER check_fkeys2_pkey_bad ON fkeys2 IS 'wrong'; -COMMENT ON TRIGGER check_fkeys2_pkey_exist ON fkeys2 IS 'right'; -COMMENT ON TRIGGER check_fkeys2_pkey_exist ON fkeys2 IS NULL; - --- --- For pkeys: --- ON DELETE/UPDATE (pkey1, pkey2) CASCADE: --- fkeys (fkey1, fkey2) and fkeys2 (fkey21, fkey22) --- -create trigger check_pkeys_fkey_cascade - before delete or update on pkeys - for each row - execute procedure - check_foreign_key (2, 'cascade', 'pkey1', 'pkey2', - 'fkeys', 'fkey1', 'fkey2', 'fkeys2', 'fkey21', 'fkey22'); - --- --- For fkeys2: --- ON DELETE/UPDATE (pkey23) RESTRICT: --- fkeys (fkey3) --- -create trigger check_fkeys2_fkey_restrict - before delete or update on fkeys2 - for each row - execute procedure check_foreign_key (1, 'restrict', 'pkey23', 'fkeys', 'fkey3'); - -insert into fkeys2 values (10, '1', 1); -insert into fkeys2 values (30, '3', 2); -insert into fkeys2 values (40, '4', 5); -insert into fkeys2 values (50, '5', 3); --- no key in pkeys -insert into fkeys2 values (70, '5', 3); - -insert into fkeys values (10, '1', 2); -insert into fkeys values (30, '3', 3); -insert into fkeys values (40, '4', 2); -insert into fkeys values (50, '5', 2); --- no key in pkeys -insert into fkeys values (70, '5', 1); --- no key in fkeys2 -insert into fkeys values (60, '6', 4); - -delete from pkeys where pkey1 = 30 and pkey2 = '3'; -delete from pkeys where pkey1 = 40 and pkey2 = '4'; -update pkeys set pkey1 = 7, pkey2 = '70' where pkey1 = 50 and pkey2 = '5'; -update pkeys set pkey1 = 7, pkey2 = '70' where pkey1 = 10 and pkey2 = '1'; - -SELECT trigger_name, event_manipulation, event_object_schema, event_object_table, - action_order, action_condition, action_orientation, action_timing, - action_reference_old_table, action_reference_new_table - FROM information_schema.triggers - WHERE event_object_table in ('pkeys', 'fkeys', 'fkeys2') - ORDER BY trigger_name COLLATE "C", 2; - -DROP TABLE pkeys; -DROP TABLE fkeys; -DROP TABLE fkeys2; - --- Check behavior when trigger returns unmodified trigtuple -create table trigtest (f1 int, f2 text); - -create trigger trigger_return_old - before insert or delete or update on trigtest - for each row execute procedure trigger_return_old(); - -insert into trigtest values(1, 'foo'); -select * from trigtest; -update trigtest set f2 = f2 || 'bar'; -select * from trigtest; -delete from trigtest; -select * from trigtest; - --- Also check what happens when such a trigger runs before or after others -create function f1_times_10() returns trigger as -$$ begin new.f1 := new.f1 * 10; return new; end $$ language plpgsql; - -create trigger trigger_alpha - before insert or update on trigtest - for each row execute procedure f1_times_10(); - -insert into trigtest values(1, 'foo'); -select * from trigtest; -update trigtest set f2 = f2 || 'bar'; -select * from trigtest; -delete from trigtest; -select * from trigtest; - -create trigger trigger_zed - before insert or update on trigtest - for each row execute procedure f1_times_10(); - -insert into trigtest values(1, 'foo'); -select * from trigtest; -update trigtest set f2 = f2 || 'bar'; -select * from trigtest; -delete from trigtest; -select * from trigtest; - -drop trigger trigger_alpha on trigtest; - -insert into trigtest values(1, 'foo'); -select * from trigtest; -update trigtest set f2 = f2 || 'bar'; -select * from trigtest; -delete from trigtest; -select * from trigtest; - -drop table trigtest; - --- Check behavior with an implicit column default, too (bug #16644) -create table trigtest ( - a integer, - b bool default true not null, - c text default 'xyzzy' not null); - -create trigger trigger_return_old - before insert or delete or update on trigtest - for each row execute procedure trigger_return_old(); - -insert into trigtest values(1); -select * from trigtest; - -alter table trigtest add column d integer default 42 not null; - -select * from trigtest; -update trigtest set a = 2 where a = 1 returning *; -select * from trigtest; - -alter table trigtest drop column b; - -select * from trigtest; -update trigtest set a = 2 where a = 1 returning *; -select * from trigtest; - -drop table trigtest; - -create sequence ttdummy_seq increment 10 start 0 minvalue 0; - -create table tttest ( - price_id int4, - price_val int4, - price_on int4, - price_off int4 default 999999 -); - -create trigger ttdummy - before delete or update on tttest - for each row - execute procedure - ttdummy (price_on, price_off); - -create trigger ttserial - before insert or update on tttest - for each row - execute procedure - autoinc (price_on, ttdummy_seq); - -insert into tttest values (1, 1, null); -insert into tttest values (2, 2, null); -insert into tttest values (3, 3, 0); - -select * from tttest; -delete from tttest where price_id = 2; -select * from tttest; --- what do we see ? - --- get current prices -select * from tttest where price_off = 999999; - --- change price for price_id == 3 -update tttest set price_val = 30 where price_id = 3; -select * from tttest; - --- now we want to change pric_id in ALL tuples --- this gets us not what we need -update tttest set price_id = 5 where price_id = 3; -select * from tttest; - --- restore data as before last update: -select set_ttdummy(0); -delete from tttest where price_id = 5; -update tttest set price_off = 999999 where price_val = 30; -select * from tttest; - --- and try change price_id now! -update tttest set price_id = 5 where price_id = 3; -select * from tttest; --- isn't it what we need ? - -select set_ttdummy(1); - --- we want to correct some "date" -update tttest set price_on = -1 where price_id = 1; --- but this doesn't work - --- try in this way -select set_ttdummy(0); -update tttest set price_on = -1 where price_id = 1; -select * from tttest; --- isn't it what we need ? - --- get price for price_id == 5 as it was @ "date" 35 -select * from tttest where price_on <= 35 and price_off > 35 and price_id = 5; - -drop table tttest; -drop sequence ttdummy_seq; - --- --- tests for per-statement triggers --- - -CREATE TABLE log_table (tstamp timestamp default timeofday()::timestamp); - -CREATE TABLE main_table (a int unique, b int); - -COPY main_table (a,b) FROM stdin; -5 10 -20 20 -30 10 -50 35 -80 15 -\. - -CREATE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS ' -BEGIN - RAISE NOTICE ''trigger_func(%) called: action = %, when = %, level = %'', TG_ARGV[0], TG_OP, TG_WHEN, TG_LEVEL; - RETURN NULL; -END;'; - -CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('before_ins_stmt'); - -CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('after_ins_stmt'); - --- --- if neither 'FOR EACH ROW' nor 'FOR EACH STATEMENT' was specified, --- CREATE TRIGGER should default to 'FOR EACH STATEMENT' --- -CREATE TRIGGER after_upd_stmt_trig AFTER UPDATE ON main_table -EXECUTE PROCEDURE trigger_func('after_upd_stmt'); - --- Both insert and update statement level triggers (before and after) should --- fire. Doesn't fire UPDATE before trigger, but only because one isn't --- defined. -INSERT INTO main_table (a, b) VALUES (5, 10) ON CONFLICT (a) - DO UPDATE SET b = EXCLUDED.b; - -CREATE TRIGGER after_upd_row_trig AFTER UPDATE ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('after_upd_row'); - -INSERT INTO main_table DEFAULT VALUES; - -UPDATE main_table SET a = a + 1 WHERE b < 30; --- UPDATE that effects zero rows should still call per-statement trigger -UPDATE main_table SET a = a + 2 WHERE b > 100; - --- constraint now unneeded -ALTER TABLE main_table DROP CONSTRAINT main_table_a_key; - --- COPY should fire per-row and per-statement INSERT triggers -COPY main_table (a, b) FROM stdin; -30 40 -50 60 -\. - -SELECT * FROM main_table ORDER BY a, b; - --- --- test triggers with WHEN clause --- - -CREATE TRIGGER modified_a BEFORE UPDATE OF a ON main_table -FOR EACH ROW WHEN (OLD.a <> NEW.a) EXECUTE PROCEDURE trigger_func('modified_a'); -CREATE TRIGGER modified_any BEFORE UPDATE OF a ON main_table -FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*) EXECUTE PROCEDURE trigger_func('modified_any'); -CREATE TRIGGER insert_a AFTER INSERT ON main_table -FOR EACH ROW WHEN (NEW.a = 123) EXECUTE PROCEDURE trigger_func('insert_a'); -CREATE TRIGGER delete_a AFTER DELETE ON main_table -FOR EACH ROW WHEN (OLD.a = 123) EXECUTE PROCEDURE trigger_func('delete_a'); -CREATE TRIGGER insert_when BEFORE INSERT ON main_table -FOR EACH STATEMENT WHEN (true) EXECUTE PROCEDURE trigger_func('insert_when'); -CREATE TRIGGER delete_when AFTER DELETE ON main_table -FOR EACH STATEMENT WHEN (true) EXECUTE PROCEDURE trigger_func('delete_when'); -SELECT trigger_name, event_manipulation, event_object_schema, event_object_table, - action_order, action_condition, action_orientation, action_timing, - action_reference_old_table, action_reference_new_table - FROM information_schema.triggers - WHERE event_object_table IN ('main_table') - ORDER BY trigger_name COLLATE "C", 2; -INSERT INTO main_table (a) VALUES (123), (456); -COPY main_table FROM stdin; -123 999 -456 999 -\. -DELETE FROM main_table WHERE a IN (123, 456); -UPDATE main_table SET a = 50, b = 60; -SELECT * FROM main_table ORDER BY a, b; -SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_a'; -SELECT pg_get_triggerdef(oid, false) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_a'; -SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_any'; - --- Test RENAME TRIGGER -ALTER TRIGGER modified_a ON main_table RENAME TO modified_modified_a; -SELECT count(*) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_a'; -SELECT count(*) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_modified_a'; - -DROP TRIGGER modified_modified_a ON main_table; -DROP TRIGGER modified_any ON main_table; -DROP TRIGGER insert_a ON main_table; -DROP TRIGGER delete_a ON main_table; -DROP TRIGGER insert_when ON main_table; -DROP TRIGGER delete_when ON main_table; - --- Test WHEN condition accessing system columns. -create table table_with_oids(a int); -insert into table_with_oids values (1); -create trigger oid_unchanged_trig after update on table_with_oids - for each row - when (new.tableoid = old.tableoid AND new.tableoid <> 0) - execute procedure trigger_func('after_upd_oid_unchanged'); -update table_with_oids set a = a + 1; -drop table table_with_oids; - --- Test column-level triggers -DROP TRIGGER after_upd_row_trig ON main_table; - -CREATE TRIGGER before_upd_a_row_trig BEFORE UPDATE OF a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_upd_a_row'); -CREATE TRIGGER after_upd_b_row_trig AFTER UPDATE OF b ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('after_upd_b_row'); -CREATE TRIGGER after_upd_a_b_row_trig AFTER UPDATE OF a, b ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('after_upd_a_b_row'); - -CREATE TRIGGER before_upd_a_stmt_trig BEFORE UPDATE OF a ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('before_upd_a_stmt'); -CREATE TRIGGER after_upd_b_stmt_trig AFTER UPDATE OF b ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('after_upd_b_stmt'); - -SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'after_upd_a_b_row_trig'; - -UPDATE main_table SET a = 50; -UPDATE main_table SET b = 10; - --- --- Test case for bug with BEFORE trigger followed by AFTER trigger with WHEN --- - -CREATE TABLE some_t (some_col boolean NOT NULL); -CREATE FUNCTION dummy_update_func() RETURNS trigger AS $$ -BEGIN - RAISE NOTICE 'dummy_update_func(%) called: action = %, old = %, new = %', - TG_ARGV[0], TG_OP, OLD, NEW; - RETURN NEW; -END; -$$ LANGUAGE plpgsql; -CREATE TRIGGER some_trig_before BEFORE UPDATE ON some_t FOR EACH ROW - EXECUTE PROCEDURE dummy_update_func('before'); -CREATE TRIGGER some_trig_aftera AFTER UPDATE ON some_t FOR EACH ROW - WHEN (NOT OLD.some_col AND NEW.some_col) - EXECUTE PROCEDURE dummy_update_func('aftera'); -CREATE TRIGGER some_trig_afterb AFTER UPDATE ON some_t FOR EACH ROW - WHEN (NOT NEW.some_col) - EXECUTE PROCEDURE dummy_update_func('afterb'); -INSERT INTO some_t VALUES (TRUE); -UPDATE some_t SET some_col = TRUE; -UPDATE some_t SET some_col = FALSE; -UPDATE some_t SET some_col = TRUE; -DROP TABLE some_t; - --- bogus cases -CREATE TRIGGER error_upd_and_col BEFORE UPDATE OR UPDATE OF a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_upd_and_col'); -CREATE TRIGGER error_upd_a_a BEFORE UPDATE OF a, a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_upd_a_a'); -CREATE TRIGGER error_ins_a BEFORE INSERT OF a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_ins_a'); -CREATE TRIGGER error_ins_when BEFORE INSERT OR UPDATE ON main_table -FOR EACH ROW WHEN (OLD.a <> NEW.a) -EXECUTE PROCEDURE trigger_func('error_ins_old'); -CREATE TRIGGER error_del_when BEFORE DELETE OR UPDATE ON main_table -FOR EACH ROW WHEN (OLD.a <> NEW.a) -EXECUTE PROCEDURE trigger_func('error_del_new'); -CREATE TRIGGER error_del_when BEFORE INSERT OR UPDATE ON main_table -FOR EACH ROW WHEN (NEW.tableoid <> 0) -EXECUTE PROCEDURE trigger_func('error_when_sys_column'); -CREATE TRIGGER error_stmt_when BEFORE UPDATE OF a ON main_table -FOR EACH STATEMENT WHEN (OLD.* IS DISTINCT FROM NEW.*) -EXECUTE PROCEDURE trigger_func('error_stmt_when'); - --- check dependency restrictions -ALTER TABLE main_table DROP COLUMN b; --- this should succeed, but we'll roll it back to keep the triggers around -begin; -DROP TRIGGER after_upd_a_b_row_trig ON main_table; -DROP TRIGGER after_upd_b_row_trig ON main_table; -DROP TRIGGER after_upd_b_stmt_trig ON main_table; -ALTER TABLE main_table DROP COLUMN b; -rollback; - --- Test enable/disable triggers - -create table trigtest (i serial primary key); --- test that disabling RI triggers works -create table trigtest2 (i int references trigtest(i) on delete cascade); - -create function trigtest() returns trigger as $$ -begin - raise notice '% % % %', TG_TABLE_NAME, TG_OP, TG_WHEN, TG_LEVEL; - return new; -end;$$ language plpgsql; - -create trigger trigtest_b_row_tg before insert or update or delete on trigtest -for each row execute procedure trigtest(); -create trigger trigtest_a_row_tg after insert or update or delete on trigtest -for each row execute procedure trigtest(); -create trigger trigtest_b_stmt_tg before insert or update or delete on trigtest -for each statement execute procedure trigtest(); -create trigger trigtest_a_stmt_tg after insert or update or delete on trigtest -for each statement execute procedure trigtest(); - -insert into trigtest default values; -alter table trigtest disable trigger trigtest_b_row_tg; -insert into trigtest default values; -alter table trigtest disable trigger user; -insert into trigtest default values; -alter table trigtest enable trigger trigtest_a_stmt_tg; -insert into trigtest default values; -set session_replication_role = replica; -insert into trigtest default values; -- does not trigger -alter table trigtest enable always trigger trigtest_a_stmt_tg; -insert into trigtest default values; -- now it does -reset session_replication_role; -insert into trigtest2 values(1); -insert into trigtest2 values(2); -delete from trigtest where i=2; -select * from trigtest2; -alter table trigtest disable trigger all; -delete from trigtest where i=1; -select * from trigtest2; --- ensure we still insert, even when all triggers are disabled -insert into trigtest default values; -select * from trigtest; -drop table trigtest2; -drop table trigtest; - - --- dump trigger data -CREATE TABLE trigger_test ( - i int, - v varchar -); - -CREATE OR REPLACE FUNCTION trigger_data() RETURNS trigger -LANGUAGE plpgsql AS $$ - -declare - - argstr text; - relid text; - -begin - - relid := TG_relid::regclass; - - -- plpgsql can't discover its trigger data in a hash like perl and python - -- can, or by a sort of reflection like tcl can, - -- so we have to hard code the names. - raise NOTICE 'TG_NAME: %', TG_name; - raise NOTICE 'TG_WHEN: %', TG_when; - raise NOTICE 'TG_LEVEL: %', TG_level; - raise NOTICE 'TG_OP: %', TG_op; - raise NOTICE 'TG_RELID::regclass: %', relid; - raise NOTICE 'TG_RELNAME: %', TG_relname; - raise NOTICE 'TG_TABLE_NAME: %', TG_table_name; - raise NOTICE 'TG_TABLE_SCHEMA: %', TG_table_schema; - raise NOTICE 'TG_NARGS: %', TG_nargs; - - argstr := '['; - for i in 0 .. TG_nargs - 1 loop - if i > 0 then - argstr := argstr || ', '; - end if; - argstr := argstr || TG_argv[i]; - end loop; - argstr := argstr || ']'; - raise NOTICE 'TG_ARGV: %', argstr; - - if TG_OP != 'INSERT' then - raise NOTICE 'OLD: %', OLD; - end if; - - if TG_OP != 'DELETE' then - raise NOTICE 'NEW: %', NEW; - end if; - - if TG_OP = 'DELETE' then - return OLD; - else - return NEW; - end if; - -end; -$$; - -CREATE TRIGGER show_trigger_data_trig -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -insert into trigger_test values(1,'insert'); -update trigger_test set v = 'update' where i = 1; -delete from trigger_test; - -DROP TRIGGER show_trigger_data_trig on trigger_test; - -DROP FUNCTION trigger_data(); - -DROP TABLE trigger_test; - --- --- Test use of row comparisons on OLD/NEW --- - -CREATE TABLE trigger_test (f1 int, f2 text, f3 text); - --- this is the obvious (and wrong...) way to compare rows -CREATE FUNCTION mytrigger() RETURNS trigger LANGUAGE plpgsql as $$ -begin - if row(old.*) = row(new.*) then - raise notice 'row % not changed', new.f1; - else - raise notice 'row % changed', new.f1; - end if; - return new; -end$$; - -CREATE TRIGGER t -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE mytrigger(); - -INSERT INTO trigger_test VALUES(1, 'foo', 'bar'); -INSERT INTO trigger_test VALUES(2, 'baz', 'quux'); - -UPDATE trigger_test SET f3 = 'bar'; -UPDATE trigger_test SET f3 = NULL; --- this demonstrates that the above isn't really working as desired: -UPDATE trigger_test SET f3 = NULL; - --- the right way when considering nulls is -CREATE OR REPLACE FUNCTION mytrigger() RETURNS trigger LANGUAGE plpgsql as $$ -begin - if row(old.*) is distinct from row(new.*) then - raise notice 'row % changed', new.f1; - else - raise notice 'row % not changed', new.f1; - end if; - return new; -end$$; - -UPDATE trigger_test SET f3 = 'bar'; -UPDATE trigger_test SET f3 = NULL; -UPDATE trigger_test SET f3 = NULL; - -DROP TABLE trigger_test; - -DROP FUNCTION mytrigger(); - --- Test snapshot management in serializable transactions involving triggers --- per bug report in 6bc73d4c0910042358k3d1adff3qa36f8df75198ecea@mail.gmail.com -CREATE FUNCTION serializable_update_trig() RETURNS trigger LANGUAGE plpgsql AS -$$ -declare - rec record; -begin - new.description = 'updated in trigger'; - return new; -end; -$$; - -CREATE TABLE serializable_update_tab ( - id int, - filler text, - description text -); - -CREATE TRIGGER serializable_update_trig BEFORE UPDATE ON serializable_update_tab - FOR EACH ROW EXECUTE PROCEDURE serializable_update_trig(); - -INSERT INTO serializable_update_tab SELECT a, repeat('xyzxz', 100), 'new' - FROM generate_series(1, 50) a; - -BEGIN; -SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -UPDATE serializable_update_tab SET description = 'no no', id = 1 WHERE id = 1; -COMMIT; -SELECT description FROM serializable_update_tab WHERE id = 1; -DROP TABLE serializable_update_tab; - --- minimal update trigger - -CREATE TABLE min_updates_test ( - f1 text, - f2 int, - f3 int); - -INSERT INTO min_updates_test VALUES ('a',1,2),('b','2',null); - -CREATE TRIGGER z_min_update -BEFORE UPDATE ON min_updates_test -FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger(); - -\set QUIET false - -UPDATE min_updates_test SET f1 = f1; - -UPDATE min_updates_test SET f2 = f2 + 1; - -UPDATE min_updates_test SET f3 = 2 WHERE f3 is null; - -\set QUIET true - -SELECT * FROM min_updates_test; - -DROP TABLE min_updates_test; - --- --- Test triggers on views --- - -CREATE VIEW main_view AS SELECT a, b FROM main_table; - --- VIEW trigger function -CREATE OR REPLACE FUNCTION view_trigger() RETURNS trigger -LANGUAGE plpgsql AS $$ -declare - argstr text := ''; -begin - for i in 0 .. TG_nargs - 1 loop - if i > 0 then - argstr := argstr || ', '; - end if; - argstr := argstr || TG_argv[i]; - end loop; - - raise notice '% % % % (%)', TG_TABLE_NAME, TG_WHEN, TG_OP, TG_LEVEL, argstr; - - if TG_LEVEL = 'ROW' then - if TG_OP = 'INSERT' then - raise NOTICE 'NEW: %', NEW; - INSERT INTO main_table VALUES (NEW.a, NEW.b); - RETURN NEW; - end if; - - if TG_OP = 'UPDATE' then - raise NOTICE 'OLD: %, NEW: %', OLD, NEW; - UPDATE main_table SET a = NEW.a, b = NEW.b WHERE a = OLD.a AND b = OLD.b; - if NOT FOUND then RETURN NULL; end if; - RETURN NEW; - end if; - - if TG_OP = 'DELETE' then - raise NOTICE 'OLD: %', OLD; - DELETE FROM main_table WHERE a = OLD.a AND b = OLD.b; - if NOT FOUND then RETURN NULL; end if; - RETURN OLD; - end if; - end if; - - RETURN NULL; -end; -$$; - --- Before row triggers aren't allowed on views -CREATE TRIGGER invalid_trig BEFORE INSERT ON main_view -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_ins_row'); - -CREATE TRIGGER invalid_trig BEFORE UPDATE ON main_view -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_upd_row'); - -CREATE TRIGGER invalid_trig BEFORE DELETE ON main_view -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_del_row'); - --- After row triggers aren't allowed on views -CREATE TRIGGER invalid_trig AFTER INSERT ON main_view -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_ins_row'); - -CREATE TRIGGER invalid_trig AFTER UPDATE ON main_view -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_upd_row'); - -CREATE TRIGGER invalid_trig AFTER DELETE ON main_view -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_del_row'); - --- Truncate triggers aren't allowed on views -CREATE TRIGGER invalid_trig BEFORE TRUNCATE ON main_view -EXECUTE PROCEDURE trigger_func('before_tru_row'); - -CREATE TRIGGER invalid_trig AFTER TRUNCATE ON main_view -EXECUTE PROCEDURE trigger_func('before_tru_row'); - --- INSTEAD OF triggers aren't allowed on tables -CREATE TRIGGER invalid_trig INSTEAD OF INSERT ON main_table -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_ins'); - -CREATE TRIGGER invalid_trig INSTEAD OF UPDATE ON main_table -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_upd'); - -CREATE TRIGGER invalid_trig INSTEAD OF DELETE ON main_table -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_del'); - --- Don't support WHEN clauses with INSTEAD OF triggers -CREATE TRIGGER invalid_trig INSTEAD OF UPDATE ON main_view -FOR EACH ROW WHEN (OLD.a <> NEW.a) EXECUTE PROCEDURE view_trigger('instead_of_upd'); - --- Don't support column-level INSTEAD OF triggers -CREATE TRIGGER invalid_trig INSTEAD OF UPDATE OF a ON main_view -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_upd'); - --- Don't support statement-level INSTEAD OF triggers -CREATE TRIGGER invalid_trig INSTEAD OF UPDATE ON main_view -EXECUTE PROCEDURE view_trigger('instead_of_upd'); - --- Valid INSTEAD OF triggers -CREATE TRIGGER instead_of_insert_trig INSTEAD OF INSERT ON main_view -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_ins'); - -CREATE TRIGGER instead_of_update_trig INSTEAD OF UPDATE ON main_view -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_upd'); - -CREATE TRIGGER instead_of_delete_trig INSTEAD OF DELETE ON main_view -FOR EACH ROW EXECUTE PROCEDURE view_trigger('instead_of_del'); - --- Valid BEFORE statement VIEW triggers -CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_view -FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('before_view_ins_stmt'); - -CREATE TRIGGER before_upd_stmt_trig BEFORE UPDATE ON main_view -FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('before_view_upd_stmt'); - -CREATE TRIGGER before_del_stmt_trig BEFORE DELETE ON main_view -FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('before_view_del_stmt'); - --- Valid AFTER statement VIEW triggers -CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON main_view -FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('after_view_ins_stmt'); - -CREATE TRIGGER after_upd_stmt_trig AFTER UPDATE ON main_view -FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('after_view_upd_stmt'); - -CREATE TRIGGER after_del_stmt_trig AFTER DELETE ON main_view -FOR EACH STATEMENT EXECUTE PROCEDURE view_trigger('after_view_del_stmt'); - -\set QUIET false - --- Insert into view using trigger -INSERT INTO main_view VALUES (20, 30); -INSERT INTO main_view VALUES (21, 31) RETURNING a, b; - --- Table trigger will prevent updates -UPDATE main_view SET b = 31 WHERE a = 20; -UPDATE main_view SET b = 32 WHERE a = 21 AND b = 31 RETURNING a, b; - --- Remove table trigger to allow updates -DROP TRIGGER before_upd_a_row_trig ON main_table; -UPDATE main_view SET b = 31 WHERE a = 20; -UPDATE main_view SET b = 32 WHERE a = 21 AND b = 31 RETURNING a, b; - --- Before and after stmt triggers should fire even when no rows are affected -UPDATE main_view SET b = 0 WHERE false; - --- Delete from view using trigger -DELETE FROM main_view WHERE a IN (20,21); -DELETE FROM main_view WHERE a = 31 RETURNING a, b; - -\set QUIET true - --- Describe view should list triggers -\d main_view - --- Test dropping view triggers -DROP TRIGGER instead_of_insert_trig ON main_view; -DROP TRIGGER instead_of_delete_trig ON main_view; -\d+ main_view -DROP VIEW main_view; - --- --- Test triggers on a join view --- -CREATE TABLE country_table ( - country_id serial primary key, - country_name text unique not null, - continent text not null -); - -INSERT INTO country_table (country_name, continent) - VALUES ('Japan', 'Asia'), - ('UK', 'Europe'), - ('USA', 'North America') - RETURNING *; - -CREATE TABLE city_table ( - city_id serial primary key, - city_name text not null, - population bigint, - country_id int references country_table -); - -CREATE VIEW city_view AS - SELECT city_id, city_name, population, country_name, continent - FROM city_table ci - LEFT JOIN country_table co ON co.country_id = ci.country_id; - -CREATE FUNCTION city_insert() RETURNS trigger LANGUAGE plpgsql AS $$ -declare - ctry_id int; -begin - if NEW.country_name IS NOT NULL then - SELECT country_id, continent INTO ctry_id, NEW.continent - FROM country_table WHERE country_name = NEW.country_name; - if NOT FOUND then - raise exception 'No such country: "%"', NEW.country_name; - end if; - else - NEW.continent := NULL; - end if; - - if NEW.city_id IS NOT NULL then - INSERT INTO city_table - VALUES(NEW.city_id, NEW.city_name, NEW.population, ctry_id); - else - INSERT INTO city_table(city_name, population, country_id) - VALUES(NEW.city_name, NEW.population, ctry_id) - RETURNING city_id INTO NEW.city_id; - end if; - - RETURN NEW; -end; -$$; - -CREATE TRIGGER city_insert_trig INSTEAD OF INSERT ON city_view -FOR EACH ROW EXECUTE PROCEDURE city_insert(); - -CREATE FUNCTION city_delete() RETURNS trigger LANGUAGE plpgsql AS $$ -begin - DELETE FROM city_table WHERE city_id = OLD.city_id; - if NOT FOUND then RETURN NULL; end if; - RETURN OLD; -end; -$$; - -CREATE TRIGGER city_delete_trig INSTEAD OF DELETE ON city_view -FOR EACH ROW EXECUTE PROCEDURE city_delete(); - -CREATE FUNCTION city_update() RETURNS trigger LANGUAGE plpgsql AS $$ -declare - ctry_id int; -begin - if NEW.country_name IS DISTINCT FROM OLD.country_name then - SELECT country_id, continent INTO ctry_id, NEW.continent - FROM country_table WHERE country_name = NEW.country_name; - if NOT FOUND then - raise exception 'No such country: "%"', NEW.country_name; - end if; - - UPDATE city_table SET city_name = NEW.city_name, - population = NEW.population, - country_id = ctry_id - WHERE city_id = OLD.city_id; - else - UPDATE city_table SET city_name = NEW.city_name, - population = NEW.population - WHERE city_id = OLD.city_id; - NEW.continent := OLD.continent; - end if; - - if NOT FOUND then RETURN NULL; end if; - RETURN NEW; -end; -$$; - -CREATE TRIGGER city_update_trig INSTEAD OF UPDATE ON city_view -FOR EACH ROW EXECUTE PROCEDURE city_update(); - -\set QUIET false - --- INSERT .. RETURNING -INSERT INTO city_view(city_name) VALUES('Tokyo') RETURNING *; -INSERT INTO city_view(city_name, population) VALUES('London', 7556900) RETURNING *; -INSERT INTO city_view(city_name, country_name) VALUES('Washington DC', 'USA') RETURNING *; -INSERT INTO city_view(city_id, city_name) VALUES(123456, 'New York') RETURNING *; -INSERT INTO city_view VALUES(234567, 'Birmingham', 1016800, 'UK', 'EU') RETURNING *; - --- UPDATE .. RETURNING -UPDATE city_view SET country_name = 'Japon' WHERE city_name = 'Tokyo'; -- error -UPDATE city_view SET country_name = 'Japan' WHERE city_name = 'Takyo'; -- no match -UPDATE city_view SET country_name = 'Japan' WHERE city_name = 'Tokyo' RETURNING *; -- OK - -UPDATE city_view SET population = 13010279 WHERE city_name = 'Tokyo' RETURNING *; -UPDATE city_view SET country_name = 'UK' WHERE city_name = 'New York' RETURNING *; -UPDATE city_view SET country_name = 'USA', population = 8391881 WHERE city_name = 'New York' RETURNING *; -UPDATE city_view SET continent = 'EU' WHERE continent = 'Europe' RETURNING *; -UPDATE city_view v1 SET country_name = v2.country_name FROM city_view v2 - WHERE v2.city_name = 'Birmingham' AND v1.city_name = 'London' RETURNING *; - --- DELETE .. RETURNING -DELETE FROM city_view WHERE city_name = 'Birmingham' RETURNING *; - -\set QUIET true - --- read-only view with WHERE clause -CREATE VIEW european_city_view AS - SELECT * FROM city_view WHERE continent = 'Europe'; -SELECT count(*) FROM european_city_view; - -CREATE FUNCTION no_op_trig_fn() RETURNS trigger LANGUAGE plpgsql -AS 'begin RETURN NULL; end'; - -CREATE TRIGGER no_op_trig INSTEAD OF INSERT OR UPDATE OR DELETE -ON european_city_view FOR EACH ROW EXECUTE PROCEDURE no_op_trig_fn(); - -\set QUIET false - -INSERT INTO european_city_view VALUES (0, 'x', 10000, 'y', 'z'); -UPDATE european_city_view SET population = 10000; -DELETE FROM european_city_view; - -\set QUIET true - --- rules bypassing no-op triggers -CREATE RULE european_city_insert_rule AS ON INSERT TO european_city_view -DO INSTEAD INSERT INTO city_view -VALUES (NEW.city_id, NEW.city_name, NEW.population, NEW.country_name, NEW.continent) -RETURNING *; - -CREATE RULE european_city_update_rule AS ON UPDATE TO european_city_view -DO INSTEAD UPDATE city_view SET - city_name = NEW.city_name, - population = NEW.population, - country_name = NEW.country_name -WHERE city_id = OLD.city_id -RETURNING NEW.*; - -CREATE RULE european_city_delete_rule AS ON DELETE TO european_city_view -DO INSTEAD DELETE FROM city_view WHERE city_id = OLD.city_id RETURNING *; - -\set QUIET false - --- INSERT not limited by view's WHERE clause, but UPDATE AND DELETE are -INSERT INTO european_city_view(city_name, country_name) - VALUES ('Cambridge', 'USA') RETURNING *; -UPDATE european_city_view SET country_name = 'UK' - WHERE city_name = 'Cambridge'; -DELETE FROM european_city_view WHERE city_name = 'Cambridge'; - --- UPDATE and DELETE via rule and trigger -UPDATE city_view SET country_name = 'UK' - WHERE city_name = 'Cambridge' RETURNING *; -UPDATE european_city_view SET population = 122800 - WHERE city_name = 'Cambridge' RETURNING *; -DELETE FROM european_city_view WHERE city_name = 'Cambridge' RETURNING *; - --- join UPDATE test -UPDATE city_view v SET population = 599657 - FROM city_table ci, country_table co - WHERE ci.city_name = 'Washington DC' and co.country_name = 'USA' - AND v.city_id = ci.city_id AND v.country_name = co.country_name - RETURNING co.country_id, v.country_name, - v.city_id, v.city_name, v.population; - -\set QUIET true - -SELECT * FROM city_view; - -DROP TABLE city_table CASCADE; -DROP TABLE country_table; - - --- Test pg_trigger_depth() - -create table depth_a (id int not null primary key); -create table depth_b (id int not null primary key); -create table depth_c (id int not null primary key); - -create function depth_a_tf() returns trigger - language plpgsql as $$ -begin - raise notice '%: depth = %', tg_name, pg_trigger_depth(); - insert into depth_b values (new.id); - raise notice '%: depth = %', tg_name, pg_trigger_depth(); - return new; -end; -$$; -create trigger depth_a_tr before insert on depth_a - for each row execute procedure depth_a_tf(); - -create function depth_b_tf() returns trigger - language plpgsql as $$ -begin - raise notice '%: depth = %', tg_name, pg_trigger_depth(); - begin - execute 'insert into depth_c values (' || new.id::text || ')'; - exception - when sqlstate 'U9999' then - raise notice 'SQLSTATE = U9999: depth = %', pg_trigger_depth(); - end; - raise notice '%: depth = %', tg_name, pg_trigger_depth(); - if new.id = 1 then - execute 'insert into depth_c values (' || new.id::text || ')'; - end if; - return new; -end; -$$; -create trigger depth_b_tr before insert on depth_b - for each row execute procedure depth_b_tf(); - -create function depth_c_tf() returns trigger - language plpgsql as $$ -begin - raise notice '%: depth = %', tg_name, pg_trigger_depth(); - if new.id = 1 then - raise exception sqlstate 'U9999'; - end if; - raise notice '%: depth = %', tg_name, pg_trigger_depth(); - return new; -end; -$$; -create trigger depth_c_tr before insert on depth_c - for each row execute procedure depth_c_tf(); - -select pg_trigger_depth(); -insert into depth_a values (1); -select pg_trigger_depth(); -insert into depth_a values (2); -select pg_trigger_depth(); - -drop table depth_a, depth_b, depth_c; -drop function depth_a_tf(); -drop function depth_b_tf(); -drop function depth_c_tf(); - --- --- Test updates to rows during firing of BEFORE ROW triggers. --- As of 9.2, such cases should be rejected (see bug #6123). --- - -create temp table parent ( - aid int not null primary key, - val1 text, - val2 text, - val3 text, - val4 text, - bcnt int not null default 0); -create temp table child ( - bid int not null primary key, - aid int not null, - val1 text); - -create function parent_upd_func() - returns trigger language plpgsql as -$$ -begin - if old.val1 <> new.val1 then - new.val2 = new.val1; - delete from child where child.aid = new.aid and child.val1 = new.val1; - end if; - return new; -end; -$$; -create trigger parent_upd_trig before update on parent - for each row execute procedure parent_upd_func(); - -create function parent_del_func() - returns trigger language plpgsql as -$$ -begin - delete from child where aid = old.aid; - return old; -end; -$$; -create trigger parent_del_trig before delete on parent - for each row execute procedure parent_del_func(); - -create function child_ins_func() - returns trigger language plpgsql as -$$ -begin - update parent set bcnt = bcnt + 1 where aid = new.aid; - return new; -end; -$$; -create trigger child_ins_trig after insert on child - for each row execute procedure child_ins_func(); - -create function child_del_func() - returns trigger language plpgsql as -$$ -begin - update parent set bcnt = bcnt - 1 where aid = old.aid; - return old; -end; -$$; -create trigger child_del_trig after delete on child - for each row execute procedure child_del_func(); - -insert into parent values (1, 'a', 'a', 'a', 'a', 0); -insert into child values (10, 1, 'b'); -select * from parent; select * from child; - -update parent set val1 = 'b' where aid = 1; -- should fail -select * from parent; select * from child; - -delete from parent where aid = 1; -- should fail -select * from parent; select * from child; - --- replace the trigger function with one that restarts the deletion after --- having modified a child -create or replace function parent_del_func() - returns trigger language plpgsql as -$$ -begin - delete from child where aid = old.aid; - if found then - delete from parent where aid = old.aid; - return null; -- cancel outer deletion - end if; - return old; -end; -$$; - -delete from parent where aid = 1; -select * from parent; select * from child; - -drop table parent, child; - -drop function parent_upd_func(); -drop function parent_del_func(); -drop function child_ins_func(); -drop function child_del_func(); - --- similar case, but with a self-referencing FK so that parent and child --- rows can be affected by a single operation - -create temp table self_ref_trigger ( - id int primary key, - parent int references self_ref_trigger, - data text, - nchildren int not null default 0 -); - -create function self_ref_trigger_ins_func() - returns trigger language plpgsql as -$$ -begin - if new.parent is not null then - update self_ref_trigger set nchildren = nchildren + 1 - where id = new.parent; - end if; - return new; -end; -$$; -create trigger self_ref_trigger_ins_trig before insert on self_ref_trigger - for each row execute procedure self_ref_trigger_ins_func(); - -create function self_ref_trigger_del_func() - returns trigger language plpgsql as -$$ -begin - if old.parent is not null then - update self_ref_trigger set nchildren = nchildren - 1 - where id = old.parent; - end if; - return old; -end; -$$; -create trigger self_ref_trigger_del_trig before delete on self_ref_trigger - for each row execute procedure self_ref_trigger_del_func(); - -insert into self_ref_trigger values (1, null, 'root'); -insert into self_ref_trigger values (2, 1, 'root child A'); -insert into self_ref_trigger values (3, 1, 'root child B'); -insert into self_ref_trigger values (4, 2, 'grandchild 1'); -insert into self_ref_trigger values (5, 3, 'grandchild 2'); - -update self_ref_trigger set data = 'root!' where id = 1; - -select * from self_ref_trigger; - -delete from self_ref_trigger; - -select * from self_ref_trigger; - -drop table self_ref_trigger; -drop function self_ref_trigger_ins_func(); -drop function self_ref_trigger_del_func(); - --- --- Check that statement triggers work correctly even with all children excluded --- - -create table stmt_trig_on_empty_upd (a int); -create table stmt_trig_on_empty_upd1 () inherits (stmt_trig_on_empty_upd); -create function update_stmt_notice() returns trigger as $$ -begin - raise notice 'updating %', TG_TABLE_NAME; - return null; -end; -$$ language plpgsql; -create trigger before_stmt_trigger - before update on stmt_trig_on_empty_upd - execute procedure update_stmt_notice(); -create trigger before_stmt_trigger - before update on stmt_trig_on_empty_upd1 - execute procedure update_stmt_notice(); - --- inherited no-op update -update stmt_trig_on_empty_upd set a = a where false returning a+1 as aa; --- simple no-op update -update stmt_trig_on_empty_upd1 set a = a where false returning a+1 as aa; - -drop table stmt_trig_on_empty_upd cascade; -drop function update_stmt_notice(); - --- --- Check that index creation (or DDL in general) is prohibited in a trigger --- - -create table trigger_ddl_table ( - col1 integer, - col2 integer -); - -create function trigger_ddl_func() returns trigger as $$ -begin - alter table trigger_ddl_table add primary key (col1); - return new; -end$$ language plpgsql; - -create trigger trigger_ddl_func before insert on trigger_ddl_table for each row - execute procedure trigger_ddl_func(); - -insert into trigger_ddl_table values (1, 42); -- fail - -create or replace function trigger_ddl_func() returns trigger as $$ -begin - create index on trigger_ddl_table (col2); - return new; -end$$ language plpgsql; - -insert into trigger_ddl_table values (1, 42); -- fail - -drop table trigger_ddl_table; -drop function trigger_ddl_func(); - --- --- Verify behavior of before and after triggers with INSERT...ON CONFLICT --- DO UPDATE --- -create table upsert (key int4 primary key, color text); - -create function upsert_before_func() - returns trigger language plpgsql as -$$ -begin - if (TG_OP = 'UPDATE') then - raise warning 'before update (old): %', old.*::text; - raise warning 'before update (new): %', new.*::text; - elsif (TG_OP = 'INSERT') then - raise warning 'before insert (new): %', new.*::text; - if new.key % 2 = 0 then - new.key := new.key + 1; - new.color := new.color || ' trig modified'; - raise warning 'before insert (new, modified): %', new.*::text; - end if; - end if; - return new; -end; -$$; -create trigger upsert_before_trig before insert or update on upsert - for each row execute procedure upsert_before_func(); - -create function upsert_after_func() - returns trigger language plpgsql as -$$ -begin - if (TG_OP = 'UPDATE') then - raise warning 'after update (old): %', old.*::text; - raise warning 'after update (new): %', new.*::text; - elsif (TG_OP = 'INSERT') then - raise warning 'after insert (new): %', new.*::text; - end if; - return null; -end; -$$; -create trigger upsert_after_trig after insert or update on upsert - for each row execute procedure upsert_after_func(); - -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; - -select * from upsert; - -drop table upsert; -drop function upsert_before_func(); -drop function upsert_after_func(); - --- --- Verify that triggers with transition tables are not allowed on --- views --- - -create table my_table (i int); -create view my_view as select * from my_table; -create function my_trigger_function() returns trigger as $$ begin end; $$ language plpgsql; -create trigger my_trigger after update on my_view referencing old table as old_table - for each statement execute procedure my_trigger_function(); -drop function my_trigger_function(); -drop view my_view; -drop table my_table; - --- --- Verify cases that are unsupported with partitioned tables --- -create table parted_trig (a int) partition by list (a); -create function trigger_nothing() returns trigger - language plpgsql as $$ begin end; $$; -create trigger failed instead of update on parted_trig - for each row execute procedure trigger_nothing(); -create trigger failed after update on parted_trig - referencing old table as old_table - for each row execute procedure trigger_nothing(); -drop table parted_trig; - --- --- Verify trigger creation for partitioned tables, and drop behavior --- -create table trigpart (a int, b int) partition by range (a); -create table trigpart1 partition of trigpart for values from (0) to (1000); -create trigger trg1 after insert on trigpart for each row execute procedure trigger_nothing(); -create table trigpart2 partition of trigpart for values from (1000) to (2000); -create table trigpart3 (like trigpart); -alter table trigpart attach partition trigpart3 for values from (2000) to (3000); -create table trigpart4 partition of trigpart for values from (3000) to (4000) partition by range (a); -create table trigpart41 partition of trigpart4 for values from (3000) to (3500); -create table trigpart42 (like trigpart); -alter table trigpart4 attach partition trigpart42 for values from (3500) to (4000); -select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger - where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text; -drop trigger trg1 on trigpart1; -- fail -drop trigger trg1 on trigpart2; -- fail -drop trigger trg1 on trigpart3; -- fail -drop table trigpart2; -- ok, trigger should be gone in that partition -select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger - where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text; -drop trigger trg1 on trigpart; -- ok, all gone -select tgrelid::regclass, tgname, tgfoid::regproc from pg_trigger - where tgrelid::regclass::text like 'trigpart%' order by tgrelid::regclass::text; - --- check detach behavior -create trigger trg1 after insert on trigpart for each row execute procedure trigger_nothing(); -\d trigpart3 -alter table trigpart detach partition trigpart3; -drop trigger trg1 on trigpart3; -- fail due to "does not exist" -alter table trigpart detach partition trigpart4; -drop trigger trg1 on trigpart41; -- fail due to "does not exist" -drop table trigpart4; -alter table trigpart attach partition trigpart3 for values from (2000) to (3000); -alter table trigpart detach partition trigpart3; -alter table trigpart attach partition trigpart3 for values from (2000) to (3000); -drop table trigpart3; - -select tgrelid::regclass::text, tgname, tgfoid::regproc, tgenabled, tgisinternal from pg_trigger - where tgname ~ '^trg1' order by 1; -create table trigpart3 (like trigpart); -create trigger trg1 after insert on trigpart3 for each row execute procedure trigger_nothing(); -\d trigpart3 -alter table trigpart attach partition trigpart3 FOR VALUES FROM (2000) to (3000); -- fail -drop table trigpart3; - --- check display of unrelated triggers -create trigger samename after delete on trigpart execute function trigger_nothing(); -create trigger samename after delete on trigpart1 execute function trigger_nothing(); -\d trigpart1 - -drop table trigpart; -drop function trigger_nothing(); - --- --- Verify that triggers are fired for partitioned tables --- -create table parted_stmt_trig (a int) partition by list (a); -create table parted_stmt_trig1 partition of parted_stmt_trig for values in (1); -create table parted_stmt_trig2 partition of parted_stmt_trig for values in (2); - -create table parted2_stmt_trig (a int) partition by list (a); -create table parted2_stmt_trig1 partition of parted2_stmt_trig for values in (1); -create table parted2_stmt_trig2 partition of parted2_stmt_trig for values in (2); - -create or replace function trigger_notice() returns trigger as $$ - begin - raise notice 'trigger % on % % % for %', TG_NAME, TG_TABLE_NAME, TG_WHEN, TG_OP, TG_LEVEL; - if TG_LEVEL = 'ROW' then - return NEW; - end if; - return null; - end; - $$ language plpgsql; - --- insert/update/delete statement-level triggers on the parent -create trigger trig_ins_before before insert on parted_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_ins_after after insert on parted_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_upd_before before update on parted_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_upd_after after update on parted_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_del_before before delete on parted_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_del_after after delete on parted_stmt_trig - for each statement execute procedure trigger_notice(); - --- insert/update/delete row-level triggers on the parent -create trigger trig_ins_after_parent after insert on parted_stmt_trig - for each row execute procedure trigger_notice(); -create trigger trig_upd_after_parent after update on parted_stmt_trig - for each row execute procedure trigger_notice(); -create trigger trig_del_after_parent after delete on parted_stmt_trig - for each row execute procedure trigger_notice(); - --- insert/update/delete row-level triggers on the first partition -create trigger trig_ins_before_child before insert on parted_stmt_trig1 - for each row execute procedure trigger_notice(); -create trigger trig_ins_after_child after insert on parted_stmt_trig1 - for each row execute procedure trigger_notice(); -create trigger trig_upd_before_child before update on parted_stmt_trig1 - for each row execute procedure trigger_notice(); -create trigger trig_upd_after_child after update on parted_stmt_trig1 - for each row execute procedure trigger_notice(); -create trigger trig_del_before_child before delete on parted_stmt_trig1 - for each row execute procedure trigger_notice(); -create trigger trig_del_after_child after delete on parted_stmt_trig1 - for each row execute procedure trigger_notice(); - --- insert/update/delete statement-level triggers on the parent -create trigger trig_ins_before_3 before insert on parted2_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_ins_after_3 after insert on parted2_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_upd_before_3 before update on parted2_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_upd_after_3 after update on parted2_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_del_before_3 before delete on parted2_stmt_trig - for each statement execute procedure trigger_notice(); -create trigger trig_del_after_3 after delete on parted2_stmt_trig - for each statement execute procedure trigger_notice(); - -with ins (a) as ( - insert into parted2_stmt_trig values (1), (2) returning a -) insert into parted_stmt_trig select a from ins returning tableoid::regclass, a; - -with upd as ( - update parted2_stmt_trig set a = a -) update parted_stmt_trig set a = a; - -delete from parted_stmt_trig; - --- insert via copy on the parent -copy parted_stmt_trig(a) from stdin; -1 -2 -\. - --- insert via copy on the first partition -copy parted_stmt_trig1(a) from stdin; -1 -\. - --- Disabling a trigger in the parent table should disable children triggers too -alter table parted_stmt_trig disable trigger trig_ins_after_parent; -insert into parted_stmt_trig values (1); -alter table parted_stmt_trig enable trigger trig_ins_after_parent; -insert into parted_stmt_trig values (1); - -drop table parted_stmt_trig, parted2_stmt_trig; - --- Verify that triggers fire in alphabetical order -create table parted_trig (a int) partition by range (a); -create table parted_trig_1 partition of parted_trig for values from (0) to (1000) - partition by range (a); -create table parted_trig_1_1 partition of parted_trig_1 for values from (0) to (100); -create table parted_trig_2 partition of parted_trig for values from (1000) to (2000); -create trigger zzz after insert on parted_trig for each row execute procedure trigger_notice(); -create trigger mmm after insert on parted_trig_1_1 for each row execute procedure trigger_notice(); -create trigger aaa after insert on parted_trig_1 for each row execute procedure trigger_notice(); -create trigger bbb after insert on parted_trig for each row execute procedure trigger_notice(); -create trigger qqq after insert on parted_trig_1_1 for each row execute procedure trigger_notice(); -insert into parted_trig values (50), (1500); -drop table parted_trig; - --- Verify propagation of trigger arguments to partitions -create table parted_trig (a int) partition by list (a); -create table parted_trig1 partition of parted_trig for values in (1); -create or replace function trigger_notice() returns trigger as $$ - declare - arg1 text = TG_ARGV[0]; - arg2 integer = TG_ARGV[1]; - begin - raise notice 'trigger % on % % % for % args % %', - TG_NAME, TG_TABLE_NAME, TG_WHEN, TG_OP, TG_LEVEL, arg1, arg2; - return null; - end; - $$ language plpgsql; -create trigger aaa after insert on parted_trig - for each row execute procedure trigger_notice('quirky', 1); - --- Verify propagation of trigger arguments to partitions attached after creating trigger -create table parted_trig2 partition of parted_trig for values in (2); -create table parted_trig3 (like parted_trig); -alter table parted_trig attach partition parted_trig3 for values in (3); -insert into parted_trig values (1), (2), (3); -drop table parted_trig; - --- test irregular partitions (i.e., different column definitions), --- including that the WHEN clause works -create function bark(text) returns bool language plpgsql immutable - as $$ begin raise notice '% <- woof!', $1; return true; end; $$; -create or replace function trigger_notice_ab() returns trigger as $$ - begin - raise notice 'trigger % on % % % for %: (a,b)=(%,%)', - TG_NAME, TG_TABLE_NAME, TG_WHEN, TG_OP, TG_LEVEL, - NEW.a, NEW.b; - if TG_LEVEL = 'ROW' then - return NEW; - end if; - return null; - end; - $$ language plpgsql; -create table parted_irreg_ancestor (fd text, b text, fd2 int, fd3 int, a int) - partition by range (b); -alter table parted_irreg_ancestor drop column fd, - drop column fd2, drop column fd3; -create table parted_irreg (fd int, a int, fd2 int, b text) - partition by range (b); -alter table parted_irreg drop column fd, drop column fd2; -alter table parted_irreg_ancestor attach partition parted_irreg - for values from ('aaaa') to ('zzzz'); -create table parted1_irreg (b text, fd int, a int); -alter table parted1_irreg drop column fd; -alter table parted_irreg attach partition parted1_irreg - for values from ('aaaa') to ('bbbb'); -create trigger parted_trig after insert on parted_irreg - for each row execute procedure trigger_notice_ab(); -create trigger parted_trig_odd after insert on parted_irreg for each row - when (bark(new.b) AND new.a % 2 = 1) execute procedure trigger_notice_ab(); --- we should hear barking for every insert, but parted_trig_odd only emits --- noise for odd values of a. parted_trig does it for all inserts. -insert into parted_irreg values (1, 'aardvark'), (2, 'aanimals'); -insert into parted1_irreg values ('aardwolf', 2); -insert into parted_irreg_ancestor values ('aasvogel', 3); -drop table parted_irreg_ancestor; - --- Before triggers and partitions -create table parted (a int, b int, c text) partition by list (a); -create table parted_1 partition of parted for values in (1) - partition by list (b); -create table parted_1_1 partition of parted_1 for values in (1); -create function parted_trigfunc() returns trigger language plpgsql as $$ -begin - new.a = new.a + 1; - return new; -end; -$$; -insert into parted values (1, 1, 'uno uno v1'); -- works -create trigger t before insert or update or delete on parted - for each row execute function parted_trigfunc(); -insert into parted values (1, 1, 'uno uno v2'); -- fail -update parted set c = c || 'v3'; -- fail -create or replace function parted_trigfunc() returns trigger language plpgsql as $$ -begin - new.b = new.b + 1; - return new; -end; -$$; -insert into parted values (1, 1, 'uno uno v4'); -- fail -update parted set c = c || 'v5'; -- fail -create or replace function parted_trigfunc() returns trigger language plpgsql as $$ -begin - new.c = new.c || ' did '|| TG_OP; - return new; -end; -$$; -insert into parted values (1, 1, 'uno uno'); -- works -update parted set c = c || ' v6'; -- works -select tableoid::regclass, * from parted; - --- update itself moves tuple to new partition; trigger still works -truncate table parted; -create table parted_2 partition of parted for values in (2); -insert into parted values (1, 1, 'uno uno v5'); -update parted set a = 2; -select tableoid::regclass, * from parted; - --- both trigger and update change the partition -create or replace function parted_trigfunc2() returns trigger language plpgsql as $$ -begin - new.a = new.a + 1; - return new; -end; -$$; -create trigger t2 before update on parted - for each row execute function parted_trigfunc2(); -truncate table parted; -insert into parted values (1, 1, 'uno uno v6'); -create table parted_3 partition of parted for values in (3); -update parted set a = a + 1; -select tableoid::regclass, * from parted; --- there's no partition for a=0, but this update works anyway because --- the trigger causes the tuple to be routed to another partition -update parted set a = 0; -select tableoid::regclass, * from parted; - -drop table parted; -create table parted (a int, b int, c text) partition by list ((a + b)); -create or replace function parted_trigfunc() returns trigger language plpgsql as $$ -begin - new.a = new.a + new.b; - return new; -end; -$$; -create table parted_1 partition of parted for values in (1, 2); -create table parted_2 partition of parted for values in (3, 4); -create trigger t before insert or update on parted - for each row execute function parted_trigfunc(); -insert into parted values (0, 1, 'zero win'); -insert into parted values (1, 1, 'one fail'); -insert into parted values (1, 2, 'two fail'); -select * from parted; -drop table parted; -drop function parted_trigfunc(); - --- --- Constraint triggers and partitioned tables -create table parted_constr_ancestor (a int, b text) - partition by range (b); -create table parted_constr (a int, b text) - partition by range (b); -alter table parted_constr_ancestor attach partition parted_constr - for values from ('aaaa') to ('zzzz'); -create table parted1_constr (a int, b text); -alter table parted_constr attach partition parted1_constr - for values from ('aaaa') to ('bbbb'); -create constraint trigger parted_trig after insert on parted_constr_ancestor - deferrable - for each row execute procedure trigger_notice_ab(); -create constraint trigger parted_trig_two after insert on parted_constr - deferrable initially deferred - for each row when (bark(new.b) AND new.a % 2 = 1) - execute procedure trigger_notice_ab(); - --- The immediate constraint is fired immediately; the WHEN clause of the --- deferred constraint is also called immediately. The deferred constraint --- is fired at commit time. -begin; -insert into parted_constr values (1, 'aardvark'); -insert into parted1_constr values (2, 'aardwolf'); -insert into parted_constr_ancestor values (3, 'aasvogel'); -commit; - --- The WHEN clause is immediate, and both constraint triggers are fired at --- commit time. -begin; -set constraints parted_trig deferred; -insert into parted_constr values (1, 'aardvark'); -insert into parted1_constr values (2, 'aardwolf'), (3, 'aasvogel'); -commit; -drop table parted_constr_ancestor; -drop function bark(text); - --- Test that the WHEN clause is set properly to partitions -create table parted_trigger (a int, b text) partition by range (a); -create table parted_trigger_1 partition of parted_trigger for values from (0) to (1000); -create table parted_trigger_2 (drp int, a int, b text); -alter table parted_trigger_2 drop column drp; -alter table parted_trigger attach partition parted_trigger_2 for values from (1000) to (2000); -create trigger parted_trigger after update on parted_trigger - for each row when (new.a % 2 = 1 and length(old.b) >= 2) execute procedure trigger_notice_ab(); -create table parted_trigger_3 (b text, a int) partition by range (length(b)); -create table parted_trigger_3_1 partition of parted_trigger_3 for values from (1) to (3); -create table parted_trigger_3_2 partition of parted_trigger_3 for values from (3) to (5); -alter table parted_trigger attach partition parted_trigger_3 for values from (2000) to (3000); -insert into parted_trigger values - (0, 'a'), (1, 'bbb'), (2, 'bcd'), (3, 'c'), - (1000, 'c'), (1001, 'ddd'), (1002, 'efg'), (1003, 'f'), - (2000, 'e'), (2001, 'fff'), (2002, 'ghi'), (2003, 'h'); -update parted_trigger set a = a + 2; -- notice for odd 'a' values, long 'b' values -drop table parted_trigger; - --- try a constraint trigger, also -create table parted_referenced (a int); -create table unparted_trigger (a int, b text); -- for comparison purposes -create table parted_trigger (a int, b text) partition by range (a); -create table parted_trigger_1 partition of parted_trigger for values from (0) to (1000); -create table parted_trigger_2 (drp int, a int, b text); -alter table parted_trigger_2 drop column drp; -alter table parted_trigger attach partition parted_trigger_2 for values from (1000) to (2000); -create constraint trigger parted_trigger after update on parted_trigger - from parted_referenced - for each row execute procedure trigger_notice_ab(); -create constraint trigger parted_trigger after update on unparted_trigger - from parted_referenced - for each row execute procedure trigger_notice_ab(); -create table parted_trigger_3 (b text, a int) partition by range (length(b)); -create table parted_trigger_3_1 partition of parted_trigger_3 for values from (1) to (3); -create table parted_trigger_3_2 partition of parted_trigger_3 for values from (3) to (5); -alter table parted_trigger attach partition parted_trigger_3 for values from (2000) to (3000); -select tgname, conname, t.tgrelid::regclass, t.tgconstrrelid::regclass, - c.conrelid::regclass, c.confrelid::regclass - from pg_trigger t join pg_constraint c on (t.tgconstraint = c.oid) - where tgname = 'parted_trigger' - order by t.tgrelid::regclass::text; -drop table parted_referenced, parted_trigger, unparted_trigger; - --- verify that the "AFTER UPDATE OF columns" event is propagated correctly -create table parted_trigger (a int, b text) partition by range (a); -create table parted_trigger_1 partition of parted_trigger for values from (0) to (1000); -create table parted_trigger_2 (drp int, a int, b text); -alter table parted_trigger_2 drop column drp; -alter table parted_trigger attach partition parted_trigger_2 for values from (1000) to (2000); -create trigger parted_trigger after update of b on parted_trigger - for each row execute procedure trigger_notice_ab(); -create table parted_trigger_3 (b text, a int) partition by range (length(b)); -create table parted_trigger_3_1 partition of parted_trigger_3 for values from (1) to (4); -create table parted_trigger_3_2 partition of parted_trigger_3 for values from (4) to (8); -alter table parted_trigger attach partition parted_trigger_3 for values from (2000) to (3000); -insert into parted_trigger values (0, 'a'), (1000, 'c'), (2000, 'e'), (2001, 'eeee'); -update parted_trigger set a = a + 2; -- no notices here -update parted_trigger set b = b || 'b'; -- all triggers should fire -drop table parted_trigger; - -drop function trigger_notice_ab(); - --- Make sure we don't end up with unnecessary copies of triggers, when --- cloning them. -create table trg_clone (a int) partition by range (a); -create table trg_clone1 partition of trg_clone for values from (0) to (1000); -alter table trg_clone add constraint uniq unique (a) deferrable; -create table trg_clone2 partition of trg_clone for values from (1000) to (2000); -create table trg_clone3 partition of trg_clone for values from (2000) to (3000) - partition by range (a); -create table trg_clone_3_3 partition of trg_clone3 for values from (2000) to (2100); -select tgrelid::regclass, count(*) from pg_trigger - where tgrelid::regclass in ('trg_clone', 'trg_clone1', 'trg_clone2', - 'trg_clone3', 'trg_clone_3_3') - group by tgrelid::regclass order by tgrelid::regclass; -drop table trg_clone; - --- Test the interaction between ALTER TABLE .. DISABLE TRIGGER and --- both kinds of inheritance. Historically, legacy inheritance has --- not recursed to children, so that behavior is preserved. -create table parent (a int); -create table child1 () inherits (parent); -create function trig_nothing() returns trigger language plpgsql - as $$ begin return null; end $$; -create trigger tg after insert on parent - for each row execute function trig_nothing(); -create trigger tg after insert on child1 - for each row execute function trig_nothing(); -alter table parent disable trigger tg; -select tgrelid::regclass, tgname, tgenabled from pg_trigger - where tgrelid in ('parent'::regclass, 'child1'::regclass) - order by tgrelid::regclass::text; -alter table only parent enable always trigger tg; -select tgrelid::regclass, tgname, tgenabled from pg_trigger - where tgrelid in ('parent'::regclass, 'child1'::regclass) - order by tgrelid::regclass::text; -drop table parent, child1; - -create table parent (a int) partition by list (a); -create table child1 partition of parent for values in (1); -create trigger tg after insert on parent - for each row execute procedure trig_nothing(); -select tgrelid::regclass, tgname, tgenabled from pg_trigger - where tgrelid in ('parent'::regclass, 'child1'::regclass) - order by tgrelid::regclass::text; -alter table only parent enable always trigger tg; -select tgrelid::regclass, tgname, tgenabled from pg_trigger - where tgrelid in ('parent'::regclass, 'child1'::regclass) - order by tgrelid::regclass::text; -drop table parent, child1; - --- Verify that firing state propagates correctly on creation, too -CREATE TABLE trgfire (i int) PARTITION BY RANGE (i); -CREATE TABLE trgfire1 PARTITION OF trgfire FOR VALUES FROM (1) TO (10); -CREATE OR REPLACE FUNCTION tgf() RETURNS trigger LANGUAGE plpgsql - AS $$ begin raise exception 'except'; end $$; -CREATE TRIGGER tg AFTER INSERT ON trgfire FOR EACH ROW EXECUTE FUNCTION tgf(); -INSERT INTO trgfire VALUES (1); -ALTER TABLE trgfire DISABLE TRIGGER tg; -INSERT INTO trgfire VALUES (1); -CREATE TABLE trgfire2 PARTITION OF trgfire FOR VALUES FROM (10) TO (20); -INSERT INTO trgfire VALUES (11); -CREATE TABLE trgfire3 (LIKE trgfire); -ALTER TABLE trgfire ATTACH PARTITION trgfire3 FOR VALUES FROM (20) TO (30); -INSERT INTO trgfire VALUES (21); -CREATE TABLE trgfire4 PARTITION OF trgfire FOR VALUES FROM (30) TO (40) PARTITION BY LIST (i); -CREATE TABLE trgfire4_30 PARTITION OF trgfire4 FOR VALUES IN (30); -INSERT INTO trgfire VALUES (30); -CREATE TABLE trgfire5 (LIKE trgfire) PARTITION BY LIST (i); -CREATE TABLE trgfire5_40 PARTITION OF trgfire5 FOR VALUES IN (40); -ALTER TABLE trgfire ATTACH PARTITION trgfire5 FOR VALUES FROM (40) TO (50); -INSERT INTO trgfire VALUES (40); -SELECT tgrelid::regclass, tgenabled FROM pg_trigger - WHERE tgrelid::regclass IN (SELECT oid from pg_class where relname LIKE 'trgfire%') - ORDER BY tgrelid::regclass::text; -ALTER TABLE trgfire ENABLE TRIGGER tg; -INSERT INTO trgfire VALUES (1); -INSERT INTO trgfire VALUES (11); -INSERT INTO trgfire VALUES (21); -INSERT INTO trgfire VALUES (30); -INSERT INTO trgfire VALUES (40); -DROP TABLE trgfire; -DROP FUNCTION tgf(); - --- --- Test the interaction between transition tables and both kinds of --- inheritance. We'll dump the contents of the transition tables in a --- format that shows the attribute order, so that we can distinguish --- tuple formats (though not dropped attributes). --- - -create or replace function dump_insert() returns trigger language plpgsql as -$$ - begin - raise notice 'trigger = %, new table = %', - TG_NAME, - (select string_agg(new_table::text, ', ' order by a) from new_table); - return null; - end; -$$; - -create or replace function dump_update() returns trigger language plpgsql as -$$ - begin - raise notice 'trigger = %, old table = %, new table = %', - TG_NAME, - (select string_agg(old_table::text, ', ' order by a) from old_table), - (select string_agg(new_table::text, ', ' order by a) from new_table); - return null; - end; -$$; - -create or replace function dump_delete() returns trigger language plpgsql as -$$ - begin - raise notice 'trigger = %, old table = %', - TG_NAME, - (select string_agg(old_table::text, ', ' order by a) from old_table); - return null; - end; -$$; - --- --- Verify behavior of statement triggers on partition hierarchy with --- transition tables. Tuples should appear to each trigger in the --- format of the relation the trigger is attached to. --- - --- set up a partition hierarchy with some different TupleDescriptors -create table parent (a text, b int) partition by list (a); - --- a child matching parent -create table child1 partition of parent for values in ('AAA'); - --- a child with a dropped column -create table child2 (x int, a text, b int); -alter table child2 drop column x; -alter table parent attach partition child2 for values in ('BBB'); - --- a child with a different column order -create table child3 (b int, a text); -alter table parent attach partition child3 for values in ('CCC'); - -create trigger parent_insert_trig - after insert on parent referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger parent_update_trig - after update on parent referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger parent_delete_trig - after delete on parent referencing old table as old_table - for each statement execute procedure dump_delete(); - -create trigger child1_insert_trig - after insert on child1 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger child1_update_trig - after update on child1 referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger child1_delete_trig - after delete on child1 referencing old table as old_table - for each statement execute procedure dump_delete(); - -create trigger child2_insert_trig - after insert on child2 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger child2_update_trig - after update on child2 referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger child2_delete_trig - after delete on child2 referencing old table as old_table - for each statement execute procedure dump_delete(); - -create trigger child3_insert_trig - after insert on child3 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger child3_update_trig - after update on child3 referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger child3_delete_trig - after delete on child3 referencing old table as old_table - for each statement execute procedure dump_delete(); - -SELECT trigger_name, event_manipulation, event_object_schema, event_object_table, - action_order, action_condition, action_orientation, action_timing, - action_reference_old_table, action_reference_new_table - FROM information_schema.triggers - WHERE event_object_table IN ('parent', 'child1', 'child2', 'child3') - ORDER BY trigger_name COLLATE "C", 2; - --- insert directly into children sees respective child-format tuples -insert into child1 values ('AAA', 42); -insert into child2 values ('BBB', 42); -insert into child3 values (42, 'CCC'); - --- update via parent sees parent-format tuples -update parent set b = b + 1; - --- delete via parent sees parent-format tuples -delete from parent; - --- insert into parent sees parent-format tuples -insert into parent values ('AAA', 42); -insert into parent values ('BBB', 42); -insert into parent values ('CCC', 42); - --- delete from children sees respective child-format tuples -delete from child1; -delete from child2; -delete from child3; - --- copy into parent sees parent-format tuples -copy parent (a, b) from stdin; -AAA 42 -BBB 42 -CCC 42 -\. - --- DML affecting parent sees tuples collected from children even if --- there is no transition table trigger on the children -drop trigger child1_insert_trig on child1; -drop trigger child1_update_trig on child1; -drop trigger child1_delete_trig on child1; -drop trigger child2_insert_trig on child2; -drop trigger child2_update_trig on child2; -drop trigger child2_delete_trig on child2; -drop trigger child3_insert_trig on child3; -drop trigger child3_update_trig on child3; -drop trigger child3_delete_trig on child3; -delete from parent; - --- copy into parent sees tuples collected from children even if there --- is no transition-table trigger on the children -copy parent (a, b) from stdin; -AAA 42 -BBB 42 -CCC 42 -\. - --- insert into parent with a before trigger on a child tuple before --- insertion, and we capture the newly modified row in parent format -create or replace function intercept_insert() returns trigger language plpgsql as -$$ - begin - new.b = new.b + 1000; - return new; - end; -$$; - -create trigger intercept_insert_child3 - before insert on child3 - for each row execute procedure intercept_insert(); - - --- insert, parent trigger sees post-modification parent-format tuple -insert into parent values ('AAA', 42), ('BBB', 42), ('CCC', 66); - --- copy, parent trigger sees post-modification parent-format tuple -copy parent (a, b) from stdin; -AAA 42 -BBB 42 -CCC 234 -\. - -drop table child1, child2, child3, parent; -drop function intercept_insert(); - --- --- Verify prohibition of row triggers with transition triggers on --- partitions --- -create table parent (a text, b int) partition by list (a); -create table child partition of parent for values in ('AAA'); - --- adding row trigger with transition table fails -create trigger child_row_trig - after insert on child referencing new table as new_table - for each row execute procedure dump_insert(); - --- detaching it first works -alter table parent detach partition child; - -create trigger child_row_trig - after insert on child referencing new table as new_table - for each row execute procedure dump_insert(); - --- but now we're not allowed to reattach it -alter table parent attach partition child for values in ('AAA'); - --- drop the trigger, and now we're allowed to attach it again -drop trigger child_row_trig on child; -alter table parent attach partition child for values in ('AAA'); - -drop table child, parent; - --- --- Verify behavior of statement triggers on (non-partition) --- inheritance hierarchy with transition tables; similar to the --- partition case, except there is no rerouting on insertion and child --- tables can have extra columns --- - --- set up inheritance hierarchy with different TupleDescriptors -create table parent (a text, b int); - --- a child matching parent -create table child1 () inherits (parent); - --- a child with a different column order -create table child2 (b int, a text); -alter table child2 inherit parent; - --- a child with an extra column -create table child3 (c text) inherits (parent); - -create trigger parent_insert_trig - after insert on parent referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger parent_update_trig - after update on parent referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger parent_delete_trig - after delete on parent referencing old table as old_table - for each statement execute procedure dump_delete(); - -create trigger child1_insert_trig - after insert on child1 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger child1_update_trig - after update on child1 referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger child1_delete_trig - after delete on child1 referencing old table as old_table - for each statement execute procedure dump_delete(); - -create trigger child2_insert_trig - after insert on child2 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger child2_update_trig - after update on child2 referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger child2_delete_trig - after delete on child2 referencing old table as old_table - for each statement execute procedure dump_delete(); - -create trigger child3_insert_trig - after insert on child3 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger child3_update_trig - after update on child3 referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger child3_delete_trig - after delete on child3 referencing old table as old_table - for each statement execute procedure dump_delete(); - --- insert directly into children sees respective child-format tuples -insert into child1 values ('AAA', 42); -insert into child2 values (42, 'BBB'); -insert into child3 values ('CCC', 42, 'foo'); - --- update via parent sees parent-format tuples -update parent set b = b + 1; - --- delete via parent sees parent-format tuples -delete from parent; - --- reinsert values into children for next test... -insert into child1 values ('AAA', 42); -insert into child2 values (42, 'BBB'); -insert into child3 values ('CCC', 42, 'foo'); - --- delete from children sees respective child-format tuples -delete from child1; -delete from child2; -delete from child3; - --- copy into parent sees parent-format tuples (no rerouting, so these --- are really inserted into the parent) -copy parent (a, b) from stdin; -AAA 42 -BBB 42 -CCC 42 -\. - --- same behavior for copy if there is an index (interesting because rows are --- captured by a different code path in copyfrom.c if there are indexes) -create index on parent(b); -copy parent (a, b) from stdin; -DDD 42 -\. - --- DML affecting parent sees tuples collected from children even if --- there is no transition table trigger on the children -drop trigger child1_insert_trig on child1; -drop trigger child1_update_trig on child1; -drop trigger child1_delete_trig on child1; -drop trigger child2_insert_trig on child2; -drop trigger child2_update_trig on child2; -drop trigger child2_delete_trig on child2; -drop trigger child3_insert_trig on child3; -drop trigger child3_update_trig on child3; -drop trigger child3_delete_trig on child3; -delete from parent; - -drop table child1, child2, child3, parent; - --- --- Verify prohibition of row triggers with transition triggers on --- inheritance children --- -create table parent (a text, b int); -create table child () inherits (parent); - --- adding row trigger with transition table fails -create trigger child_row_trig - after insert on child referencing new table as new_table - for each row execute procedure dump_insert(); - --- disinheriting it first works -alter table child no inherit parent; - -create trigger child_row_trig - after insert on child referencing new table as new_table - for each row execute procedure dump_insert(); - --- but now we're not allowed to make it inherit anymore -alter table child inherit parent; - --- drop the trigger, and now we're allowed to make it inherit again -drop trigger child_row_trig on child; -alter table child inherit parent; - -drop table child, parent; - --- --- Verify behavior of queries with wCTEs, where multiple transition --- tuplestores can be active at the same time because there are --- multiple DML statements that might fire triggers with transition --- tables --- -create table table1 (a int); -create table table2 (a text); -create trigger table1_trig - after insert on table1 referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger table2_trig - after insert on table2 referencing new table as new_table - for each statement execute procedure dump_insert(); - -with wcte as (insert into table1 values (42)) - insert into table2 values ('hello world'); - -with wcte as (insert into table1 values (43)) - insert into table1 values (44); - -select * from table1; -select * from table2; - -drop table table1; -drop table table2; - --- --- Verify behavior of INSERT ... ON CONFLICT DO UPDATE ... with --- transition tables. --- - -create table my_table (a int primary key, b text); -create trigger my_table_insert_trig - after insert on my_table referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger my_table_update_trig - after update on my_table referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); - --- inserts only -insert into my_table values (1, 'AAA'), (2, 'BBB') - on conflict (a) do - update set b = my_table.b || ':' || excluded.b; - --- mixture of inserts and updates -insert into my_table values (1, 'AAA'), (2, 'BBB'), (3, 'CCC'), (4, 'DDD') - on conflict (a) do - update set b = my_table.b || ':' || excluded.b; - --- updates only -insert into my_table values (3, 'CCC'), (4, 'DDD') - on conflict (a) do - update set b = my_table.b || ':' || excluded.b; - --- --- now using a partitioned table --- - -create table iocdu_tt_parted (a int primary key, b text) partition by list (a); -create table iocdu_tt_parted1 partition of iocdu_tt_parted for values in (1); -create table iocdu_tt_parted2 partition of iocdu_tt_parted for values in (2); -create table iocdu_tt_parted3 partition of iocdu_tt_parted for values in (3); -create table iocdu_tt_parted4 partition of iocdu_tt_parted for values in (4); -create trigger iocdu_tt_parted_insert_trig - after insert on iocdu_tt_parted referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger iocdu_tt_parted_update_trig - after update on iocdu_tt_parted referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); - --- inserts only -insert into iocdu_tt_parted values (1, 'AAA'), (2, 'BBB') - on conflict (a) do - update set b = iocdu_tt_parted.b || ':' || excluded.b; - --- mixture of inserts and updates -insert into iocdu_tt_parted values (1, 'AAA'), (2, 'BBB'), (3, 'CCC'), (4, 'DDD') - on conflict (a) do - update set b = iocdu_tt_parted.b || ':' || excluded.b; - --- updates only -insert into iocdu_tt_parted values (3, 'CCC'), (4, 'DDD') - on conflict (a) do - update set b = iocdu_tt_parted.b || ':' || excluded.b; - -drop table iocdu_tt_parted; - --- --- Verify that you can't create a trigger with transition tables for --- more than one event. --- - -create trigger my_table_multievent_trig - after insert or update on my_table referencing new table as new_table - for each statement execute procedure dump_insert(); - --- --- Verify that you can't create a trigger with transition tables with --- a column list. --- - -create trigger my_table_col_update_trig - after update of b on my_table referencing new table as new_table - for each statement execute procedure dump_insert(); - -drop table my_table; - --- --- Test firing of triggers with transition tables by foreign key cascades --- - -create table refd_table (a int primary key, b text); -create table trig_table (a int, b text, - foreign key (a) references refd_table on update cascade on delete cascade -); - -create trigger trig_table_before_trig - before insert or update or delete on trig_table - for each statement execute procedure trigger_func('trig_table'); -create trigger trig_table_insert_trig - after insert on trig_table referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger trig_table_update_trig - after update on trig_table referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger trig_table_delete_trig - after delete on trig_table referencing old table as old_table - for each statement execute procedure dump_delete(); - -insert into refd_table values - (1, 'one'), - (2, 'two'), - (3, 'three'); -insert into trig_table values - (1, 'one a'), - (1, 'one b'), - (2, 'two a'), - (2, 'two b'), - (3, 'three a'), - (3, 'three b'); - -update refd_table set a = 11 where b = 'one'; - -select * from trig_table; - -delete from refd_table where length(b) = 3; - -select * from trig_table; - -drop table refd_table, trig_table; - --- --- self-referential FKs are even more fun --- - -create table self_ref (a int primary key, - b int references self_ref(a) on delete cascade); - -create trigger self_ref_before_trig - before delete on self_ref - for each statement execute procedure trigger_func('self_ref'); -create trigger self_ref_r_trig - after delete on self_ref referencing old table as old_table - for each row execute procedure dump_delete(); -create trigger self_ref_s_trig - after delete on self_ref referencing old table as old_table - for each statement execute procedure dump_delete(); - -insert into self_ref values (1, null), (2, 1), (3, 2); - -delete from self_ref where a = 1; - --- without AR trigger, cascaded deletes all end up in one transition table -drop trigger self_ref_r_trig on self_ref; - -insert into self_ref values (1, null), (2, 1), (3, 2), (4, 3); - -delete from self_ref where a = 1; - -drop table self_ref; - --- --- test transition tables with MERGE --- -create table merge_target_table (a int primary key, b text); -create trigger merge_target_table_insert_trig - after insert on merge_target_table referencing new table as new_table - for each statement execute procedure dump_insert(); -create trigger merge_target_table_update_trig - after update on merge_target_table referencing old table as old_table new table as new_table - for each statement execute procedure dump_update(); -create trigger merge_target_table_delete_trig - after delete on merge_target_table referencing old table as old_table - for each statement execute procedure dump_delete(); - -create table merge_source_table (a int, b text); -insert into merge_source_table - values (1, 'initial1'), (2, 'initial2'), - (3, 'initial3'), (4, 'initial4'); - -merge into merge_target_table t -using merge_source_table s -on t.a = s.a -when not matched then - insert values (a, b); - -merge into merge_target_table t -using merge_source_table s -on t.a = s.a -when matched and s.a <= 2 then - update set b = t.b || ' updated by merge' -when matched and s.a > 2 then - delete -when not matched then - insert values (a, b); - -merge into merge_target_table t -using merge_source_table s -on t.a = s.a -when matched and s.a <= 2 then - update set b = t.b || ' updated again by merge' -when matched and s.a > 2 then - delete -when not matched then - insert values (a, b); - -drop table merge_source_table, merge_target_table; - --- cleanup -drop function dump_insert(); -drop function dump_update(); -drop function dump_delete(); - --- --- Tests for CREATE OR REPLACE TRIGGER --- -create table my_table (id integer); - -create function funcA() returns trigger as $$ -begin - raise notice 'hello from funcA'; - return null; -end; $$ language plpgsql; - -create function funcB() returns trigger as $$ -begin - raise notice 'hello from funcB'; - return null; -end; $$ language plpgsql; - -create trigger my_trig - after insert on my_table - for each row execute procedure funcA(); - -create trigger my_trig - before insert on my_table - for each row execute procedure funcB(); -- should fail - -insert into my_table values (1); - -create or replace trigger my_trig - before insert on my_table - for each row execute procedure funcB(); -- OK - -insert into my_table values (2); -- this insert should become a no-op - -table my_table; - -drop table my_table; - --- test CREATE OR REPLACE TRIGGER on partition table -create table parted_trig (a int) partition by range (a); -create table parted_trig_1 partition of parted_trig - for values from (0) to (1000) partition by range (a); -create table parted_trig_1_1 partition of parted_trig_1 for values from (0) to (100); -create table parted_trig_2 partition of parted_trig for values from (1000) to (2000); -create table default_parted_trig partition of parted_trig default; - --- test that trigger can be replaced by another one --- at the same level of partition table -create or replace trigger my_trig - after insert on parted_trig - for each row execute procedure funcA(); -insert into parted_trig (a) values (50); -create or replace trigger my_trig - after insert on parted_trig - for each row execute procedure funcB(); -insert into parted_trig (a) values (50); - --- test that child trigger cannot be replaced directly -create or replace trigger my_trig - after insert on parted_trig - for each row execute procedure funcA(); -insert into parted_trig (a) values (50); -create or replace trigger my_trig - after insert on parted_trig_1 - for each row execute procedure funcB(); -- should fail -insert into parted_trig (a) values (50); -drop trigger my_trig on parted_trig; -insert into parted_trig (a) values (50); - --- test that user trigger can be overwritten by one defined at upper level -create trigger my_trig - after insert on parted_trig_1 - for each row execute procedure funcA(); -insert into parted_trig (a) values (50); -create trigger my_trig - after insert on parted_trig - for each row execute procedure funcB(); -- should fail -insert into parted_trig (a) values (50); -create or replace trigger my_trig - after insert on parted_trig - for each row execute procedure funcB(); -insert into parted_trig (a) values (50); - --- cleanup -drop table parted_trig; -drop function funcA(); -drop function funcB(); - --- Leave around some objects for other tests -create table trigger_parted (a int primary key) partition by list (a); -create function trigger_parted_trigfunc() returns trigger language plpgsql as - $$ begin end; $$; -create trigger aft_row after insert or update on trigger_parted - for each row execute function trigger_parted_trigfunc(); -create table trigger_parted_p1 partition of trigger_parted for values in (1) - partition by list (a); -create table trigger_parted_p1_1 partition of trigger_parted_p1 for values in (1); -create table trigger_parted_p2 partition of trigger_parted for values in (2) - partition by list (a); -create table trigger_parted_p2_2 partition of trigger_parted_p2 for values in (2); -alter table only trigger_parted_p2 disable trigger aft_row; -alter table trigger_parted_p2_2 enable always trigger aft_row; - --- verify transition table conversion slot's lifetime --- https://postgr.es/m/39a71864-b120-5a5c-8cc5-c632b6f16761@amazon.com -create table convslot_test_parent (col1 text primary key); -create table convslot_test_child (col1 text primary key, - foreign key (col1) references convslot_test_parent(col1) on delete cascade on update cascade -); - -alter table convslot_test_child add column col2 text not null default 'tutu'; -insert into convslot_test_parent(col1) values ('1'); -insert into convslot_test_child(col1) values ('1'); -insert into convslot_test_parent(col1) values ('3'); -insert into convslot_test_child(col1) values ('3'); - -create or replace function trigger_function1() -returns trigger -language plpgsql -AS $$ -begin -raise notice 'trigger = %, old_table = %', - TG_NAME, - (select string_agg(old_table::text, ', ' order by col1) from old_table); -return null; -end; $$; - -create or replace function trigger_function2() -returns trigger -language plpgsql -AS $$ -begin -raise notice 'trigger = %, new table = %', - TG_NAME, - (select string_agg(new_table::text, ', ' order by col1) from new_table); -return null; -end; $$; - -create trigger but_trigger after update on convslot_test_child -referencing new table as new_table -for each statement execute function trigger_function2(); - -update convslot_test_parent set col1 = col1 || '1'; - -create or replace function trigger_function3() -returns trigger -language plpgsql -AS $$ -begin -raise notice 'trigger = %, old_table = %, new table = %', - TG_NAME, - (select string_agg(old_table::text, ', ' order by col1) from old_table), - (select string_agg(new_table::text, ', ' order by col1) from new_table); -return null; -end; $$; - -create trigger but_trigger2 after update on convslot_test_child -referencing old table as old_table new table as new_table -for each statement execute function trigger_function3(); -update convslot_test_parent set col1 = col1 || '1'; - -create trigger bdt_trigger after delete on convslot_test_child -referencing old table as old_table -for each statement execute function trigger_function1(); -delete from convslot_test_parent; - -drop table convslot_test_child, convslot_test_parent; - --- Test trigger renaming on partitioned tables -create table grandparent (id int, primary key (id)) partition by range (id); -create table middle partition of grandparent for values from (1) to (10) -partition by range (id); -create table chi partition of middle for values from (1) to (5); -create table cho partition of middle for values from (6) to (10); -create function f () returns trigger as -$$ begin return new; end; $$ -language plpgsql; -create trigger a after insert on grandparent -for each row execute procedure f(); - -alter trigger a on grandparent rename to b; -select tgrelid::regclass, tgname, -(select tgname from pg_trigger tr where tr.oid = pg_trigger.tgparentid) parent_tgname -from pg_trigger where tgrelid in (select relid from pg_partition_tree('grandparent')) -order by tgname, tgrelid::regclass::text COLLATE "C"; -alter trigger a on only grandparent rename to b; -- ONLY not supported -alter trigger b on middle rename to c; -- can't rename trigger on partition -create trigger c after insert on middle -for each row execute procedure f(); -alter trigger b on grandparent rename to c; - --- Rename cascading does not affect statement triggers -create trigger p after insert on grandparent for each statement execute function f(); -create trigger p after insert on middle for each statement execute function f(); -alter trigger p on grandparent rename to q; -select tgrelid::regclass, tgname, -(select tgname from pg_trigger tr where tr.oid = pg_trigger.tgparentid) parent_tgname -from pg_trigger where tgrelid in (select relid from pg_partition_tree('grandparent')) -order by tgname, tgrelid::regclass::text COLLATE "C"; - -drop table grandparent; - --- Trigger renaming does not recurse on legacy inheritance -create table parent (a int); -create table child () inherits (parent); -create trigger parenttrig after insert on parent -for each row execute procedure f(); -create trigger parenttrig after insert on child -for each row execute procedure f(); -alter trigger parenttrig on parent rename to anothertrig; -\d+ child - -drop table parent, child; -drop function f(); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftruncate.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftruncate.sql deleted file mode 100644 index 54f26e3077..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftruncate.sql +++ /dev/null @@ -1,329 +0,0 @@ --- Test basic TRUNCATE functionality. -CREATE TABLE truncate_a (col1 integer primary key); -INSERT INTO truncate_a VALUES (1); -INSERT INTO truncate_a VALUES (2); -SELECT * FROM truncate_a; --- Roll truncate back -BEGIN; -TRUNCATE truncate_a; -ROLLBACK; -SELECT * FROM truncate_a; --- Commit the truncate this time -BEGIN; -TRUNCATE truncate_a; -COMMIT; -SELECT * FROM truncate_a; - --- Test foreign-key checks -CREATE TABLE trunc_b (a int REFERENCES truncate_a); -CREATE TABLE trunc_c (a serial PRIMARY KEY); -CREATE TABLE trunc_d (a int REFERENCES trunc_c); -CREATE TABLE trunc_e (a int REFERENCES truncate_a, b int REFERENCES trunc_c); - -TRUNCATE TABLE truncate_a; -- fail -TRUNCATE TABLE truncate_a,trunc_b; -- fail -TRUNCATE TABLE truncate_a,trunc_b,trunc_e; -- ok -TRUNCATE TABLE truncate_a,trunc_e; -- fail -TRUNCATE TABLE trunc_c; -- fail -TRUNCATE TABLE trunc_c,trunc_d; -- fail -TRUNCATE TABLE trunc_c,trunc_d,trunc_e; -- ok -TRUNCATE TABLE trunc_c,trunc_d,trunc_e,truncate_a; -- fail -TRUNCATE TABLE trunc_c,trunc_d,trunc_e,truncate_a,trunc_b; -- ok - -TRUNCATE TABLE truncate_a RESTRICT; -- fail -TRUNCATE TABLE truncate_a CASCADE; -- ok - --- circular references -ALTER TABLE truncate_a ADD FOREIGN KEY (col1) REFERENCES trunc_c; - --- Add some data to verify that truncating actually works ... -INSERT INTO trunc_c VALUES (1); -INSERT INTO truncate_a VALUES (1); -INSERT INTO trunc_b VALUES (1); -INSERT INTO trunc_d VALUES (1); -INSERT INTO trunc_e VALUES (1,1); -TRUNCATE TABLE trunc_c; -TRUNCATE TABLE trunc_c,truncate_a; -TRUNCATE TABLE trunc_c,truncate_a,trunc_d; -TRUNCATE TABLE trunc_c,truncate_a,trunc_d,trunc_e; -TRUNCATE TABLE trunc_c,truncate_a,trunc_d,trunc_e,trunc_b; - --- Verify that truncating did actually work -SELECT * FROM truncate_a - UNION ALL - SELECT * FROM trunc_c - UNION ALL - SELECT * FROM trunc_b - UNION ALL - SELECT * FROM trunc_d; -SELECT * FROM trunc_e; - --- Add data again to test TRUNCATE ... CASCADE -INSERT INTO trunc_c VALUES (1); -INSERT INTO truncate_a VALUES (1); -INSERT INTO trunc_b VALUES (1); -INSERT INTO trunc_d VALUES (1); -INSERT INTO trunc_e VALUES (1,1); - -TRUNCATE TABLE trunc_c CASCADE; -- ok - -SELECT * FROM truncate_a - UNION ALL - SELECT * FROM trunc_c - UNION ALL - SELECT * FROM trunc_b - UNION ALL - SELECT * FROM trunc_d; -SELECT * FROM trunc_e; - -DROP TABLE truncate_a,trunc_c,trunc_b,trunc_d,trunc_e CASCADE; - --- Test TRUNCATE with inheritance - -CREATE TABLE trunc_f (col1 integer primary key); -INSERT INTO trunc_f VALUES (1); -INSERT INTO trunc_f VALUES (2); - -CREATE TABLE trunc_fa (col2a text) INHERITS (trunc_f); -INSERT INTO trunc_fa VALUES (3, 'three'); - -CREATE TABLE trunc_fb (col2b int) INHERITS (trunc_f); -INSERT INTO trunc_fb VALUES (4, 444); - -CREATE TABLE trunc_faa (col3 text) INHERITS (trunc_fa); -INSERT INTO trunc_faa VALUES (5, 'five', 'FIVE'); - -BEGIN; -SELECT * FROM trunc_f; -TRUNCATE trunc_f; -SELECT * FROM trunc_f; -ROLLBACK; - -BEGIN; -SELECT * FROM trunc_f; -TRUNCATE ONLY trunc_f; -SELECT * FROM trunc_f; -ROLLBACK; - -BEGIN; -SELECT * FROM trunc_f; -SELECT * FROM trunc_fa; -SELECT * FROM trunc_faa; -TRUNCATE ONLY trunc_fb, ONLY trunc_fa; -SELECT * FROM trunc_f; -SELECT * FROM trunc_fa; -SELECT * FROM trunc_faa; -ROLLBACK; - -BEGIN; -SELECT * FROM trunc_f; -SELECT * FROM trunc_fa; -SELECT * FROM trunc_faa; -TRUNCATE ONLY trunc_fb, trunc_fa; -SELECT * FROM trunc_f; -SELECT * FROM trunc_fa; -SELECT * FROM trunc_faa; -ROLLBACK; - -DROP TABLE trunc_f CASCADE; - --- Test ON TRUNCATE triggers - -CREATE TABLE trunc_trigger_test (f1 int, f2 text, f3 text); -CREATE TABLE trunc_trigger_log (tgop text, tglevel text, tgwhen text, - tgargv text, tgtable name, rowcount bigint); - -CREATE FUNCTION trunctrigger() RETURNS trigger as $$ -declare c bigint; -begin - execute 'select count(*) from ' || quote_ident(tg_table_name) into c; - insert into trunc_trigger_log values - (TG_OP, TG_LEVEL, TG_WHEN, TG_ARGV[0], tg_table_name, c); - return null; -end; -$$ LANGUAGE plpgsql; - --- basic before trigger -INSERT INTO trunc_trigger_test VALUES(1, 'foo', 'bar'), (2, 'baz', 'quux'); - -CREATE TRIGGER t -BEFORE TRUNCATE ON trunc_trigger_test -FOR EACH STATEMENT -EXECUTE PROCEDURE trunctrigger('before trigger truncate'); - -SELECT count(*) as "Row count in test table" FROM trunc_trigger_test; -SELECT * FROM trunc_trigger_log; -TRUNCATE trunc_trigger_test; -SELECT count(*) as "Row count in test table" FROM trunc_trigger_test; -SELECT * FROM trunc_trigger_log; - -DROP TRIGGER t ON trunc_trigger_test; - -truncate trunc_trigger_log; - --- same test with an after trigger -INSERT INTO trunc_trigger_test VALUES(1, 'foo', 'bar'), (2, 'baz', 'quux'); - -CREATE TRIGGER tt -AFTER TRUNCATE ON trunc_trigger_test -FOR EACH STATEMENT -EXECUTE PROCEDURE trunctrigger('after trigger truncate'); - -SELECT count(*) as "Row count in test table" FROM trunc_trigger_test; -SELECT * FROM trunc_trigger_log; -TRUNCATE trunc_trigger_test; -SELECT count(*) as "Row count in test table" FROM trunc_trigger_test; -SELECT * FROM trunc_trigger_log; - -DROP TABLE trunc_trigger_test; -DROP TABLE trunc_trigger_log; - -DROP FUNCTION trunctrigger(); - --- test TRUNCATE ... RESTART IDENTITY -CREATE SEQUENCE truncate_a_id1 START WITH 33; -CREATE TABLE truncate_a (id serial, - id1 integer default nextval('truncate_a_id1')); -ALTER SEQUENCE truncate_a_id1 OWNED BY truncate_a.id1; - -INSERT INTO truncate_a DEFAULT VALUES; -INSERT INTO truncate_a DEFAULT VALUES; -SELECT * FROM truncate_a; - -TRUNCATE truncate_a; - -INSERT INTO truncate_a DEFAULT VALUES; -INSERT INTO truncate_a DEFAULT VALUES; -SELECT * FROM truncate_a; - -TRUNCATE truncate_a RESTART IDENTITY; - -INSERT INTO truncate_a DEFAULT VALUES; -INSERT INTO truncate_a DEFAULT VALUES; -SELECT * FROM truncate_a; - -CREATE TABLE truncate_b (id int GENERATED ALWAYS AS IDENTITY (START WITH 44)); - -INSERT INTO truncate_b DEFAULT VALUES; -INSERT INTO truncate_b DEFAULT VALUES; -SELECT * FROM truncate_b; - -TRUNCATE truncate_b; - -INSERT INTO truncate_b DEFAULT VALUES; -INSERT INTO truncate_b DEFAULT VALUES; -SELECT * FROM truncate_b; - -TRUNCATE truncate_b RESTART IDENTITY; - -INSERT INTO truncate_b DEFAULT VALUES; -INSERT INTO truncate_b DEFAULT VALUES; -SELECT * FROM truncate_b; - --- check rollback of a RESTART IDENTITY operation -BEGIN; -TRUNCATE truncate_a RESTART IDENTITY; -INSERT INTO truncate_a DEFAULT VALUES; -SELECT * FROM truncate_a; -ROLLBACK; -INSERT INTO truncate_a DEFAULT VALUES; -INSERT INTO truncate_a DEFAULT VALUES; -SELECT * FROM truncate_a; - -DROP TABLE truncate_a; - -SELECT nextval('truncate_a_id1'); -- fail, seq should have been dropped - --- partitioned table -CREATE TABLE truncparted (a int, b char) PARTITION BY LIST (a); --- error, can't truncate a partitioned table -TRUNCATE ONLY truncparted; -CREATE TABLE truncparted1 PARTITION OF truncparted FOR VALUES IN (1); -INSERT INTO truncparted VALUES (1, 'a'); --- error, must truncate partitions -TRUNCATE ONLY truncparted; -TRUNCATE truncparted; -DROP TABLE truncparted; - --- foreign key on partitioned table: partition key is referencing column. --- Make sure truncate did execute on all tables -CREATE FUNCTION tp_ins_data() RETURNS void LANGUAGE plpgsql AS $$ - BEGIN - INSERT INTO truncprim VALUES (1), (100), (150); - INSERT INTO truncpart VALUES (1), (100), (150); - END -$$; -CREATE FUNCTION tp_chk_data(OUT pktb regclass, OUT pkval int, OUT fktb regclass, OUT fkval int) - RETURNS SETOF record LANGUAGE plpgsql AS $$ - BEGIN - RETURN QUERY SELECT - pk.tableoid::regclass, pk.a, fk.tableoid::regclass, fk.a - FROM truncprim pk FULL JOIN truncpart fk USING (a) - ORDER BY 2, 4; - END -$$; -CREATE TABLE truncprim (a int PRIMARY KEY); -CREATE TABLE truncpart (a int REFERENCES truncprim) - PARTITION BY RANGE (a); -CREATE TABLE truncpart_1 PARTITION OF truncpart FOR VALUES FROM (0) TO (100); -CREATE TABLE truncpart_2 PARTITION OF truncpart FOR VALUES FROM (100) TO (200) - PARTITION BY RANGE (a); -CREATE TABLE truncpart_2_1 PARTITION OF truncpart_2 FOR VALUES FROM (100) TO (150); -CREATE TABLE truncpart_2_d PARTITION OF truncpart_2 DEFAULT; - -TRUNCATE TABLE truncprim; -- should fail - -select tp_ins_data(); --- should truncate everything -TRUNCATE TABLE truncprim, truncpart; -select * from tp_chk_data(); - -select tp_ins_data(); --- should truncate everything -TRUNCATE TABLE truncprim CASCADE; -SELECT * FROM tp_chk_data(); - -SELECT tp_ins_data(); --- should truncate all partitions -TRUNCATE TABLE truncpart; -SELECT * FROM tp_chk_data(); -DROP TABLE truncprim, truncpart; -DROP FUNCTION tp_ins_data(), tp_chk_data(); - --- test cascade when referencing a partitioned table -CREATE TABLE trunc_a (a INT PRIMARY KEY) PARTITION BY RANGE (a); -CREATE TABLE trunc_a1 PARTITION OF trunc_a FOR VALUES FROM (0) TO (10); -CREATE TABLE trunc_a2 PARTITION OF trunc_a FOR VALUES FROM (10) TO (20) - PARTITION BY RANGE (a); -CREATE TABLE trunc_a21 PARTITION OF trunc_a2 FOR VALUES FROM (10) TO (12); -CREATE TABLE trunc_a22 PARTITION OF trunc_a2 FOR VALUES FROM (12) TO (16); -CREATE TABLE trunc_a2d PARTITION OF trunc_a2 DEFAULT; -CREATE TABLE trunc_a3 PARTITION OF trunc_a FOR VALUES FROM (20) TO (30); -INSERT INTO trunc_a VALUES (0), (5), (10), (15), (20), (25); - --- truncate a partition cascading to a table -CREATE TABLE ref_b ( - b INT PRIMARY KEY, - a INT REFERENCES trunc_a(a) ON DELETE CASCADE -); -INSERT INTO ref_b VALUES (10, 0), (50, 5), (100, 10), (150, 15); - -TRUNCATE TABLE trunc_a1 CASCADE; -SELECT a FROM ref_b; - -DROP TABLE ref_b; - --- truncate a partition cascading to a partitioned table -CREATE TABLE ref_c ( - c INT PRIMARY KEY, - a INT REFERENCES trunc_a(a) ON DELETE CASCADE -) PARTITION BY RANGE (c); -CREATE TABLE ref_c1 PARTITION OF ref_c FOR VALUES FROM (100) TO (200); -CREATE TABLE ref_c2 PARTITION OF ref_c FOR VALUES FROM (200) TO (300); -INSERT INTO ref_c VALUES (100, 10), (150, 15), (200, 20), (250, 25); - -TRUNCATE TABLE trunc_a21 CASCADE; -SELECT a as "from table ref_c" FROM ref_c; -SELECT a as "from table trunc_a" FROM trunc_a ORDER BY a; - -DROP TABLE trunc_a, ref_c; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftuplesort.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftuplesort.sql deleted file mode 100644 index 846484d561..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftuplesort.sql +++ /dev/null @@ -1,298 +0,0 @@ --- only use parallelism when explicitly intending to do so -SET max_parallel_maintenance_workers = 0; -SET max_parallel_workers = 0; - --- A table with contents that, when sorted, triggers abbreviated --- key aborts. One easy way to achieve that is to use uuids that all --- have the same prefix, as abbreviated keys for uuids just use the --- first sizeof(Datum) bytes. -CREATE TEMP TABLE abbrev_abort_uuids ( - id serial not null, - abort_increasing uuid, - abort_decreasing uuid, - noabort_increasing uuid, - noabort_decreasing uuid); - -INSERT INTO abbrev_abort_uuids (abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing) - SELECT - ('00000000-0000-0000-0000-'||to_char(g.i, '000000000000FM'))::uuid abort_increasing, - ('00000000-0000-0000-0000-'||to_char(20000 - g.i, '000000000000FM'))::uuid abort_decreasing, - (to_char(g.i % 10009, '00000000FM')||'-0000-0000-0000-'||to_char(g.i, '000000000000FM'))::uuid noabort_increasing, - (to_char(((20000 - g.i) % 10009), '00000000FM')||'-0000-0000-0000-'||to_char(20000 - g.i, '000000000000FM'))::uuid noabort_decreasing - FROM generate_series(0, 20000, 1) g(i); - --- and a few NULLs -INSERT INTO abbrev_abort_uuids(id) VALUES(0); -INSERT INTO abbrev_abort_uuids DEFAULT VALUES; -INSERT INTO abbrev_abort_uuids DEFAULT VALUES; - --- add just a few duplicates -INSERT INTO abbrev_abort_uuids (abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing) - SELECT abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing - FROM abbrev_abort_uuids - WHERE (id < 10 OR id > 19990) AND id % 3 = 0 AND abort_increasing is not null; - ----- --- Check sort node uses of tuplesort wrt. abbreviated keys ----- - --- plain sort triggering abbreviated abort -SELECT abort_increasing, abort_decreasing FROM abbrev_abort_uuids ORDER BY abort_increasing OFFSET 20000 - 4; -SELECT abort_increasing, abort_decreasing FROM abbrev_abort_uuids ORDER BY abort_decreasing NULLS FIRST OFFSET 20000 - 4; - --- plain sort not triggering abbreviated abort -SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_increasing OFFSET 20000 - 4; -SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing NULLS FIRST OFFSET 20000 - 4; - --- bounded sort (disables abbreviated keys) -SELECT abort_increasing, noabort_increasing FROM abbrev_abort_uuids ORDER BY abort_increasing LIMIT 5; -SELECT abort_increasing, noabort_increasing FROM abbrev_abort_uuids ORDER BY noabort_increasing NULLS FIRST LIMIT 5; - - ----- --- Check index creation uses of tuplesort wrt. abbreviated keys ----- - --- index creation using abbreviated keys successfully -CREATE INDEX abbrev_abort_uuids__noabort_increasing_idx ON abbrev_abort_uuids (noabort_increasing); -CREATE INDEX abbrev_abort_uuids__noabort_decreasing_idx ON abbrev_abort_uuids (noabort_decreasing); - --- verify -EXPLAIN (COSTS OFF) -SELECT id, noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_increasing LIMIT 5; -SELECT id, noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_increasing LIMIT 5; -EXPLAIN (COSTS OFF) -SELECT id, noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing LIMIT 5; -SELECT id, noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing LIMIT 5; - --- index creation using abbreviated keys, hitting abort -CREATE INDEX abbrev_abort_uuids__abort_increasing_idx ON abbrev_abort_uuids (abort_increasing); -CREATE INDEX abbrev_abort_uuids__abort_decreasing_idx ON abbrev_abort_uuids (abort_decreasing); - --- verify -EXPLAIN (COSTS OFF) -SELECT id, abort_increasing, abort_decreasing FROM abbrev_abort_uuids ORDER BY abort_increasing LIMIT 5; -SELECT id, abort_increasing, abort_decreasing FROM abbrev_abort_uuids ORDER BY abort_increasing LIMIT 5; -EXPLAIN (COSTS OFF) -SELECT id, abort_increasing, abort_decreasing FROM abbrev_abort_uuids ORDER BY abort_decreasing LIMIT 5; -SELECT id, abort_increasing, abort_decreasing FROM abbrev_abort_uuids ORDER BY abort_decreasing LIMIT 5; - - ----- --- Check CLUSTER uses of tuplesort wrt. abbreviated keys ----- - --- when aborting, increasing order -BEGIN; -SET LOCAL enable_indexscan = false; -CLUSTER abbrev_abort_uuids USING abbrev_abort_uuids__abort_increasing_idx; - --- head -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid LIMIT 5; - --- tail -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid DESC LIMIT 5; -ROLLBACK; - --- when aborting, decreasing order -BEGIN; -SET LOCAL enable_indexscan = false; -CLUSTER abbrev_abort_uuids USING abbrev_abort_uuids__abort_decreasing_idx; - --- head -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid LIMIT 5; - --- tail -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid DESC LIMIT 5; -ROLLBACK; - --- when not aborting, increasing order -BEGIN; -SET LOCAL enable_indexscan = false; -CLUSTER abbrev_abort_uuids USING abbrev_abort_uuids__noabort_increasing_idx; - --- head -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid LIMIT 5; - --- tail -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid DESC LIMIT 5; -ROLLBACK; - --- when no aborting, decreasing order -BEGIN; -SET LOCAL enable_indexscan = false; -CLUSTER abbrev_abort_uuids USING abbrev_abort_uuids__noabort_decreasing_idx; - --- head -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid LIMIT 5; - --- tail -SELECT id, abort_increasing, abort_decreasing, noabort_increasing, noabort_decreasing -FROM abbrev_abort_uuids -ORDER BY ctid DESC LIMIT 5; -ROLLBACK; - ----- --- test forward and backward scans for in-memory and disk based tuplesort ----- - --- in-memory -BEGIN; -SET LOCAL enable_indexscan = false; --- unfortunately can't show analyze output confirming sort method, --- the memory used output wouldn't be stable -EXPLAIN (COSTS OFF) DECLARE c SCROLL CURSOR FOR SELECT noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing; -DECLARE c SCROLL CURSOR FOR SELECT noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing; - --- first and second -FETCH NEXT FROM c; -FETCH NEXT FROM c; - --- scroll beyond beginning -FETCH BACKWARD FROM c; -FETCH BACKWARD FROM c; -FETCH BACKWARD FROM c; -FETCH BACKWARD FROM c; -FETCH NEXT FROM c; - --- scroll beyond end end -FETCH LAST FROM c; -FETCH BACKWARD FROM c; -FETCH NEXT FROM c; -FETCH NEXT FROM c; -FETCH NEXT FROM c; -FETCH BACKWARD FROM c; -FETCH NEXT FROM c; - -COMMIT; - --- disk based -BEGIN; -SET LOCAL enable_indexscan = false; -SET LOCAL work_mem = '100kB'; --- unfortunately can't show analyze output confirming sort method, --- the memory used output wouldn't be stable -EXPLAIN (COSTS OFF) DECLARE c SCROLL CURSOR FOR SELECT noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing; -DECLARE c SCROLL CURSOR FOR SELECT noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing; - --- first and second -FETCH NEXT FROM c; -FETCH NEXT FROM c; - --- scroll beyond beginning -FETCH BACKWARD FROM c; -FETCH BACKWARD FROM c; -FETCH BACKWARD FROM c; -FETCH BACKWARD FROM c; -FETCH NEXT FROM c; - --- scroll beyond end end -FETCH LAST FROM c; -FETCH BACKWARD FROM c; -FETCH NEXT FROM c; -FETCH NEXT FROM c; -FETCH NEXT FROM c; -FETCH BACKWARD FROM c; -FETCH NEXT FROM c; - -COMMIT; - - ----- --- test tuplesort using both in-memory and disk sort ---- - --- memory based -SELECT - -- fixed-width by-value datum - (array_agg(id ORDER BY id DESC NULLS FIRST))[0:5], - -- fixed-width by-ref datum - (array_agg(abort_increasing ORDER BY abort_increasing DESC NULLS LAST))[0:5], - -- variable-width datum - (array_agg(id::text ORDER BY id::text DESC NULLS LAST))[0:5], - -- fixed width by-value datum tuplesort - percentile_disc(0.99) WITHIN GROUP (ORDER BY id), - -- ensure state is shared - percentile_disc(0.01) WITHIN GROUP (ORDER BY id), - -- fixed width by-ref datum tuplesort - percentile_disc(0.8) WITHIN GROUP (ORDER BY abort_increasing), - -- variable width by-ref datum tuplesort - percentile_disc(0.2) WITHIN GROUP (ORDER BY id::text), - -- multi-column tuplesort - rank('00000000-0000-0000-0000-000000000000', '2', '2') WITHIN GROUP (ORDER BY noabort_increasing, id, id::text) -FROM ( - SELECT * FROM abbrev_abort_uuids - UNION ALL - SELECT NULL, NULL, NULL, NULL, NULL) s; - --- disk based (see also above) -BEGIN; -SET LOCAL work_mem = '100kB'; - -SELECT - (array_agg(id ORDER BY id DESC NULLS FIRST))[0:5], - (array_agg(abort_increasing ORDER BY abort_increasing DESC NULLS LAST))[0:5], - (array_agg(id::text ORDER BY id::text DESC NULLS LAST))[0:5], - percentile_disc(0.99) WITHIN GROUP (ORDER BY id), - percentile_disc(0.01) WITHIN GROUP (ORDER BY id), - percentile_disc(0.8) WITHIN GROUP (ORDER BY abort_increasing), - percentile_disc(0.2) WITHIN GROUP (ORDER BY id::text), - rank('00000000-0000-0000-0000-000000000000', '2', '2') WITHIN GROUP (ORDER BY noabort_increasing, id, id::text) -FROM ( - SELECT * FROM abbrev_abort_uuids - UNION ALL - SELECT NULL, NULL, NULL, NULL, NULL) s; - -ROLLBACK; - - ----- --- test tuplesort mark/restore ---- - -CREATE TEMP TABLE test_mark_restore(col1 int, col2 int, col12 int); --- need a few duplicates for mark/restore to matter -INSERT INTO test_mark_restore(col1, col2, col12) - SELECT a.i, b.i, a.i * b.i FROM generate_series(1, 500) a(i), generate_series(1, 5) b(i); - -BEGIN; - -SET LOCAL enable_nestloop = off; -SET LOCAL enable_hashjoin = off; -SET LOCAL enable_material = off; - --- set query into variable once, to avoid repetition of the fairly long query -SELECT $$ - SELECT col12, count(distinct a.col1), count(distinct a.col2), count(distinct b.col1), count(distinct b.col2), count(*) - FROM test_mark_restore a - JOIN test_mark_restore b USING(col12) - GROUP BY 1 - HAVING count(*) > 1 - ORDER BY 2 DESC, 1 DESC, 3 DESC, 4 DESC, 5 DESC, 6 DESC - LIMIT 10 -$$ AS qry \gset - --- test mark/restore with in-memory sorts -EXPLAIN (COSTS OFF) :qry; -:qry; - --- test mark/restore with on-disk sorts -SET LOCAL work_mem = '100kB'; -EXPLAIN (COSTS OFF) :qry; -:qry; - -COMMIT; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftxid.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftxid.sql deleted file mode 100644 index 8d5ac98a89..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftxid.sql +++ /dev/null @@ -1,102 +0,0 @@ --- txid_snapshot data type and related functions --- Note: these are backward-compatibility functions and types, and have been --- replaced by new xid8-based variants. See xid.sql. The txid variants will --- be removed in a future release. - --- i/o -select '12:13:'::txid_snapshot; -select '12:18:14,16'::txid_snapshot; -select '12:16:14,14'::txid_snapshot; - --- errors -select '31:12:'::txid_snapshot; -select '0:1:'::txid_snapshot; -select '12:13:0'::txid_snapshot; -select '12:16:14,13'::txid_snapshot; - -create temp table snapshot_test ( - nr integer, - snap txid_snapshot -); - -insert into snapshot_test values (1, '12:13:'); -insert into snapshot_test values (2, '12:20:13,15,18'); -insert into snapshot_test values (3, '100001:100009:100005,100007,100008'); -insert into snapshot_test values (4, '100:150:101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131'); -select snap from snapshot_test order by nr; - -select txid_snapshot_xmin(snap), - txid_snapshot_xmax(snap), - txid_snapshot_xip(snap) -from snapshot_test order by nr; - -select id, txid_visible_in_snapshot(id, snap) -from snapshot_test, generate_series(11, 21) id -where nr = 2; - --- test bsearch -select id, txid_visible_in_snapshot(id, snap) -from snapshot_test, generate_series(90, 160) id -where nr = 4; - --- test current values also -select txid_current() >= txid_snapshot_xmin(txid_current_snapshot()); - --- we can't assume current is always less than xmax, however - -select txid_visible_in_snapshot(txid_current(), txid_current_snapshot()); - --- test 64bitness - -select txid_snapshot '1000100010001000:1000100010001100:1000100010001012,1000100010001013'; -select txid_visible_in_snapshot('1000100010001012', '1000100010001000:1000100010001100:1000100010001012,1000100010001013'); -select txid_visible_in_snapshot('1000100010001015', '1000100010001000:1000100010001100:1000100010001012,1000100010001013'); - --- test 64bit overflow -SELECT txid_snapshot '1:9223372036854775807:3'; -SELECT txid_snapshot '1:9223372036854775808:3'; - --- test txid_current_if_assigned -BEGIN; -SELECT txid_current_if_assigned() IS NULL; -SELECT txid_current() \gset -SELECT txid_current_if_assigned() IS NOT DISTINCT FROM BIGINT :'txid_current'; -COMMIT; - --- test xid status functions -BEGIN; -SELECT txid_current() AS committed \gset -COMMIT; - -BEGIN; -SELECT txid_current() AS rolledback \gset -ROLLBACK; - -BEGIN; -SELECT txid_current() AS inprogress \gset - -SELECT txid_status(:committed) AS committed; -SELECT txid_status(:rolledback) AS rolledback; -SELECT txid_status(:inprogress) AS inprogress; -SELECT txid_status(1); -- BootstrapTransactionId is always committed -SELECT txid_status(2); -- FrozenTransactionId is always committed -SELECT txid_status(3); -- in regress testing FirstNormalTransactionId will always be behind oldestXmin - -COMMIT; - -BEGIN; -CREATE FUNCTION test_future_xid_status(bigint) -RETURNS void -LANGUAGE plpgsql -AS -$$ -BEGIN - PERFORM txid_status($1); - RAISE EXCEPTION 'didn''t ERROR at xid in the future as expected'; -EXCEPTION - WHEN invalid_parameter_value THEN - RAISE NOTICE 'Got expected error for xid in the future'; -END; -$$; -SELECT test_future_xid_status(:inprogress + 10000); -ROLLBACK; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftyped_table.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftyped_table.sql deleted file mode 100644 index 9ef0cdfcc7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftyped_table.sql +++ /dev/null @@ -1,75 +0,0 @@ -CREATE TABLE ttable1 OF nothing; - -CREATE TYPE person_type AS (id int, name text); -CREATE TABLE persons OF person_type; -CREATE TABLE IF NOT EXISTS persons OF person_type; -SELECT * FROM persons; -\d persons - -CREATE FUNCTION get_all_persons() RETURNS SETOF person_type -LANGUAGE SQL -AS $$ - SELECT * FROM persons; -$$; - -SELECT * FROM get_all_persons(); - --- certain ALTER TABLE operations on typed tables are not allowed -ALTER TABLE persons ADD COLUMN comment text; -ALTER TABLE persons DROP COLUMN name; -ALTER TABLE persons RENAME COLUMN id TO num; -ALTER TABLE persons ALTER COLUMN name TYPE varchar; -CREATE TABLE stuff (id int); -ALTER TABLE persons INHERIT stuff; - -CREATE TABLE personsx OF person_type (myname WITH OPTIONS NOT NULL); -- error - -CREATE TABLE persons2 OF person_type ( - id WITH OPTIONS PRIMARY KEY, - UNIQUE (name) -); - -\d persons2 - -CREATE TABLE persons3 OF person_type ( - PRIMARY KEY (id), - name WITH OPTIONS DEFAULT '' -); - -\d persons3 - -CREATE TABLE persons4 OF person_type ( - name WITH OPTIONS NOT NULL, - name WITH OPTIONS DEFAULT '' -- error, specified more than once -); - -DROP TYPE person_type RESTRICT; -DROP TYPE person_type CASCADE; - -CREATE TABLE persons5 OF stuff; -- only CREATE TYPE AS types may be used - -DROP TABLE stuff; - - --- implicit casting - -CREATE TYPE person_type AS (id int, name text); -CREATE TABLE persons OF person_type; -INSERT INTO persons VALUES (1, 'test'); - -CREATE FUNCTION namelen(person_type) RETURNS int LANGUAGE SQL AS $$ SELECT length($1.name) $$; -SELECT id, namelen(persons) FROM persons; - -CREATE TABLE persons2 OF person_type ( - id WITH OPTIONS PRIMARY KEY, - UNIQUE (name) -); - -\d persons2 - -CREATE TABLE persons3 OF person_type ( - PRIMARY KEY (id), - name NOT NULL DEFAULT '' -); - -\d persons3 diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Funion.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Funion.sql deleted file mode 100644 index ca8c9b4d12..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Funion.sql +++ /dev/null @@ -1,542 +0,0 @@ --- --- UNION (also INTERSECT, EXCEPT) --- - --- Simple UNION constructs - -SELECT 1 AS two UNION SELECT 2 ORDER BY 1; - -SELECT 1 AS one UNION SELECT 1 ORDER BY 1; - -SELECT 1 AS two UNION ALL SELECT 2; - -SELECT 1 AS two UNION ALL SELECT 1; - -SELECT 1 AS three UNION SELECT 2 UNION SELECT 3 ORDER BY 1; - -SELECT 1 AS two UNION SELECT 2 UNION SELECT 2 ORDER BY 1; - -SELECT 1 AS three UNION SELECT 2 UNION ALL SELECT 2 ORDER BY 1; - -SELECT 1.1 AS two UNION SELECT 2.2 ORDER BY 1; - --- Mixed types - -SELECT 1.1 AS two UNION SELECT 2 ORDER BY 1; - -SELECT 1 AS two UNION SELECT 2.2 ORDER BY 1; - -SELECT 1 AS one UNION SELECT 1.0::float8 ORDER BY 1; - -SELECT 1.1 AS two UNION ALL SELECT 2 ORDER BY 1; - -SELECT 1.0::float8 AS two UNION ALL SELECT 1 ORDER BY 1; - -SELECT 1.1 AS three UNION SELECT 2 UNION SELECT 3 ORDER BY 1; - -SELECT 1.1::float8 AS two UNION SELECT 2 UNION SELECT 2.0::float8 ORDER BY 1; - -SELECT 1.1 AS three UNION SELECT 2 UNION ALL SELECT 2 ORDER BY 1; - -SELECT 1.1 AS two UNION (SELECT 2 UNION ALL SELECT 2) ORDER BY 1; - --- --- Try testing from tables... --- - -SELECT f1 AS five FROM FLOAT8_TBL -UNION -SELECT f1 FROM FLOAT8_TBL -ORDER BY 1; - -SELECT f1 AS ten FROM FLOAT8_TBL -UNION ALL -SELECT f1 FROM FLOAT8_TBL; - -SELECT f1 AS nine FROM FLOAT8_TBL -UNION -SELECT f1 FROM INT4_TBL -ORDER BY 1; - -SELECT f1 AS ten FROM FLOAT8_TBL -UNION ALL -SELECT f1 FROM INT4_TBL; - -SELECT f1 AS five FROM FLOAT8_TBL - WHERE f1 BETWEEN -1e6 AND 1e6 -UNION -SELECT f1 FROM INT4_TBL - WHERE f1 BETWEEN 0 AND 1000000 -ORDER BY 1; - -SELECT CAST(f1 AS char(4)) AS three FROM VARCHAR_TBL -UNION -SELECT f1 FROM CHAR_TBL -ORDER BY 1; - -SELECT f1 AS three FROM VARCHAR_TBL -UNION -SELECT CAST(f1 AS varchar) FROM CHAR_TBL -ORDER BY 1; - -SELECT f1 AS eight FROM VARCHAR_TBL -UNION ALL -SELECT f1 FROM CHAR_TBL; - -SELECT f1 AS five FROM TEXT_TBL -UNION -SELECT f1 FROM VARCHAR_TBL -UNION -SELECT TRIM(TRAILING FROM f1) FROM CHAR_TBL -ORDER BY 1; - --- --- INTERSECT and EXCEPT --- - -SELECT q2 FROM int8_tbl INTERSECT SELECT q1 FROM int8_tbl ORDER BY 1; - -SELECT q2 FROM int8_tbl INTERSECT ALL SELECT q1 FROM int8_tbl ORDER BY 1; - -SELECT q2 FROM int8_tbl EXCEPT SELECT q1 FROM int8_tbl ORDER BY 1; - -SELECT q2 FROM int8_tbl EXCEPT ALL SELECT q1 FROM int8_tbl ORDER BY 1; - -SELECT q2 FROM int8_tbl EXCEPT ALL SELECT DISTINCT q1 FROM int8_tbl ORDER BY 1; - -SELECT q1 FROM int8_tbl EXCEPT SELECT q2 FROM int8_tbl ORDER BY 1; - -SELECT q1 FROM int8_tbl EXCEPT ALL SELECT q2 FROM int8_tbl ORDER BY 1; - -SELECT q1 FROM int8_tbl EXCEPT ALL SELECT DISTINCT q2 FROM int8_tbl ORDER BY 1; - -SELECT q1 FROM int8_tbl EXCEPT ALL SELECT q1 FROM int8_tbl FOR NO KEY UPDATE; - --- nested cases -(SELECT 1,2,3 UNION SELECT 4,5,6) INTERSECT SELECT 4,5,6; -(SELECT 1,2,3 UNION SELECT 4,5,6 ORDER BY 1,2) INTERSECT SELECT 4,5,6; -(SELECT 1,2,3 UNION SELECT 4,5,6) EXCEPT SELECT 4,5,6; -(SELECT 1,2,3 UNION SELECT 4,5,6 ORDER BY 1,2) EXCEPT SELECT 4,5,6; - --- exercise both hashed and sorted implementations of UNION/INTERSECT/EXCEPT - -set enable_hashagg to on; - -explain (costs off) -select count(*) from - ( select unique1 from tenk1 union select fivethous from tenk1 ) ss; -select count(*) from - ( select unique1 from tenk1 union select fivethous from tenk1 ) ss; - -explain (costs off) -select count(*) from - ( select unique1 from tenk1 intersect select fivethous from tenk1 ) ss; -select count(*) from - ( select unique1 from tenk1 intersect select fivethous from tenk1 ) ss; - -explain (costs off) -select unique1 from tenk1 except select unique2 from tenk1 where unique2 != 10; -select unique1 from tenk1 except select unique2 from tenk1 where unique2 != 10; - -set enable_hashagg to off; - -explain (costs off) -select count(*) from - ( select unique1 from tenk1 union select fivethous from tenk1 ) ss; -select count(*) from - ( select unique1 from tenk1 union select fivethous from tenk1 ) ss; - -explain (costs off) -select count(*) from - ( select unique1 from tenk1 intersect select fivethous from tenk1 ) ss; -select count(*) from - ( select unique1 from tenk1 intersect select fivethous from tenk1 ) ss; - -explain (costs off) -select unique1 from tenk1 except select unique2 from tenk1 where unique2 != 10; -select unique1 from tenk1 except select unique2 from tenk1 where unique2 != 10; - -reset enable_hashagg; - --- non-hashable type -set enable_hashagg to on; - -explain (costs off) -select x from (values (100::money), (200::money)) _(x) union select x from (values (100::money), (300::money)) _(x); - -set enable_hashagg to off; - -explain (costs off) -select x from (values (100::money), (200::money)) _(x) union select x from (values (100::money), (300::money)) _(x); - -reset enable_hashagg; - --- arrays -set enable_hashagg to on; - -explain (costs off) -select x from (values (array[1, 2]), (array[1, 3])) _(x) union select x from (values (array[1, 2]), (array[1, 4])) _(x); -select x from (values (array[1, 2]), (array[1, 3])) _(x) union select x from (values (array[1, 2]), (array[1, 4])) _(x); -explain (costs off) -select x from (values (array[1, 2]), (array[1, 3])) _(x) intersect select x from (values (array[1, 2]), (array[1, 4])) _(x); -select x from (values (array[1, 2]), (array[1, 3])) _(x) intersect select x from (values (array[1, 2]), (array[1, 4])) _(x); -explain (costs off) -select x from (values (array[1, 2]), (array[1, 3])) _(x) except select x from (values (array[1, 2]), (array[1, 4])) _(x); -select x from (values (array[1, 2]), (array[1, 3])) _(x) except select x from (values (array[1, 2]), (array[1, 4])) _(x); - --- non-hashable type -explain (costs off) -select x from (values (array[100::money]), (array[200::money])) _(x) union select x from (values (array[100::money]), (array[300::money])) _(x); -select x from (values (array[100::money]), (array[200::money])) _(x) union select x from (values (array[100::money]), (array[300::money])) _(x); - -set enable_hashagg to off; - -explain (costs off) -select x from (values (array[1, 2]), (array[1, 3])) _(x) union select x from (values (array[1, 2]), (array[1, 4])) _(x); -select x from (values (array[1, 2]), (array[1, 3])) _(x) union select x from (values (array[1, 2]), (array[1, 4])) _(x); -explain (costs off) -select x from (values (array[1, 2]), (array[1, 3])) _(x) intersect select x from (values (array[1, 2]), (array[1, 4])) _(x); -select x from (values (array[1, 2]), (array[1, 3])) _(x) intersect select x from (values (array[1, 2]), (array[1, 4])) _(x); -explain (costs off) -select x from (values (array[1, 2]), (array[1, 3])) _(x) except select x from (values (array[1, 2]), (array[1, 4])) _(x); -select x from (values (array[1, 2]), (array[1, 3])) _(x) except select x from (values (array[1, 2]), (array[1, 4])) _(x); - -reset enable_hashagg; - --- records -set enable_hashagg to on; - -explain (costs off) -select x from (values (row(1, 2)), (row(1, 3))) _(x) union select x from (values (row(1, 2)), (row(1, 4))) _(x); -select x from (values (row(1, 2)), (row(1, 3))) _(x) union select x from (values (row(1, 2)), (row(1, 4))) _(x); -explain (costs off) -select x from (values (row(1, 2)), (row(1, 3))) _(x) intersect select x from (values (row(1, 2)), (row(1, 4))) _(x); -select x from (values (row(1, 2)), (row(1, 3))) _(x) intersect select x from (values (row(1, 2)), (row(1, 4))) _(x); -explain (costs off) -select x from (values (row(1, 2)), (row(1, 3))) _(x) except select x from (values (row(1, 2)), (row(1, 4))) _(x); -select x from (values (row(1, 2)), (row(1, 3))) _(x) except select x from (values (row(1, 2)), (row(1, 4))) _(x); - --- non-hashable type - --- With an anonymous row type, the typcache does not report that the --- type is hashable. (Otherwise, this would fail at execution time.) -explain (costs off) -select x from (values (row(100::money)), (row(200::money))) _(x) union select x from (values (row(100::money)), (row(300::money))) _(x); -select x from (values (row(100::money)), (row(200::money))) _(x) union select x from (values (row(100::money)), (row(300::money))) _(x); - --- With a defined row type, the typcache can inspect the type's fields --- for hashability. -create type ct1 as (f1 money); -explain (costs off) -select x from (values (row(100::money)::ct1), (row(200::money)::ct1)) _(x) union select x from (values (row(100::money)::ct1), (row(300::money)::ct1)) _(x); -select x from (values (row(100::money)::ct1), (row(200::money)::ct1)) _(x) union select x from (values (row(100::money)::ct1), (row(300::money)::ct1)) _(x); -drop type ct1; - -set enable_hashagg to off; - -explain (costs off) -select x from (values (row(1, 2)), (row(1, 3))) _(x) union select x from (values (row(1, 2)), (row(1, 4))) _(x); -select x from (values (row(1, 2)), (row(1, 3))) _(x) union select x from (values (row(1, 2)), (row(1, 4))) _(x); -explain (costs off) -select x from (values (row(1, 2)), (row(1, 3))) _(x) intersect select x from (values (row(1, 2)), (row(1, 4))) _(x); -select x from (values (row(1, 2)), (row(1, 3))) _(x) intersect select x from (values (row(1, 2)), (row(1, 4))) _(x); -explain (costs off) -select x from (values (row(1, 2)), (row(1, 3))) _(x) except select x from (values (row(1, 2)), (row(1, 4))) _(x); -select x from (values (row(1, 2)), (row(1, 3))) _(x) except select x from (values (row(1, 2)), (row(1, 4))) _(x); - -reset enable_hashagg; - --- --- Mixed types --- - -SELECT f1 FROM float8_tbl INTERSECT SELECT f1 FROM int4_tbl ORDER BY 1; - -SELECT f1 FROM float8_tbl EXCEPT SELECT f1 FROM int4_tbl ORDER BY 1; - --- --- Operator precedence and (((((extra))))) parentheses --- - -SELECT q1 FROM int8_tbl INTERSECT SELECT q2 FROM int8_tbl UNION ALL SELECT q2 FROM int8_tbl ORDER BY 1; - -SELECT q1 FROM int8_tbl INTERSECT (((SELECT q2 FROM int8_tbl UNION ALL SELECT q2 FROM int8_tbl))) ORDER BY 1; - -(((SELECT q1 FROM int8_tbl INTERSECT SELECT q2 FROM int8_tbl ORDER BY 1))) UNION ALL SELECT q2 FROM int8_tbl; - -SELECT q1 FROM int8_tbl UNION ALL SELECT q2 FROM int8_tbl EXCEPT SELECT q1 FROM int8_tbl ORDER BY 1; - -SELECT q1 FROM int8_tbl UNION ALL (((SELECT q2 FROM int8_tbl EXCEPT SELECT q1 FROM int8_tbl ORDER BY 1))); - -(((SELECT q1 FROM int8_tbl UNION ALL SELECT q2 FROM int8_tbl))) EXCEPT SELECT q1 FROM int8_tbl ORDER BY 1; - --- --- Subqueries with ORDER BY & LIMIT clauses --- - --- In this syntax, ORDER BY/LIMIT apply to the result of the EXCEPT -SELECT q1,q2 FROM int8_tbl EXCEPT SELECT q2,q1 FROM int8_tbl -ORDER BY q2,q1; - --- This should fail, because q2 isn't a name of an EXCEPT output column -SELECT q1 FROM int8_tbl EXCEPT SELECT q2 FROM int8_tbl ORDER BY q2 LIMIT 1; - --- But this should work: -SELECT q1 FROM int8_tbl EXCEPT (((SELECT q2 FROM int8_tbl ORDER BY q2 LIMIT 1))) ORDER BY 1; - --- --- New syntaxes (7.1) permit new tests --- - -(((((select * from int8_tbl))))); - --- --- Check behavior with empty select list (allowed since 9.4) --- - -select union select; -select intersect select; -select except select; - --- check hashed implementation -set enable_hashagg = true; -set enable_sort = false; - -explain (costs off) -select from generate_series(1,5) union select from generate_series(1,3); -explain (costs off) -select from generate_series(1,5) intersect select from generate_series(1,3); - -select from generate_series(1,5) union select from generate_series(1,3); -select from generate_series(1,5) union all select from generate_series(1,3); -select from generate_series(1,5) intersect select from generate_series(1,3); -select from generate_series(1,5) intersect all select from generate_series(1,3); -select from generate_series(1,5) except select from generate_series(1,3); -select from generate_series(1,5) except all select from generate_series(1,3); - --- check sorted implementation -set enable_hashagg = false; -set enable_sort = true; - -explain (costs off) -select from generate_series(1,5) union select from generate_series(1,3); -explain (costs off) -select from generate_series(1,5) intersect select from generate_series(1,3); - -select from generate_series(1,5) union select from generate_series(1,3); -select from generate_series(1,5) union all select from generate_series(1,3); -select from generate_series(1,5) intersect select from generate_series(1,3); -select from generate_series(1,5) intersect all select from generate_series(1,3); -select from generate_series(1,5) except select from generate_series(1,3); -select from generate_series(1,5) except all select from generate_series(1,3); - -reset enable_hashagg; -reset enable_sort; - --- --- Check handling of a case with unknown constants. We don't guarantee --- an undecorated constant will work in all cases, but historically this --- usage has worked, so test we don't break it. --- - -SELECT a.f1 FROM (SELECT 'test' AS f1 FROM varchar_tbl) a -UNION -SELECT b.f1 FROM (SELECT f1 FROM varchar_tbl) b -ORDER BY 1; - --- This should fail, but it should produce an error cursor -SELECT '3.4'::numeric UNION SELECT 'foo'; - --- --- Test that expression-index constraints can be pushed down through --- UNION or UNION ALL --- - -CREATE TEMP TABLE t1 (a text, b text); -CREATE INDEX t1_ab_idx on t1 ((a || b)); -CREATE TEMP TABLE t2 (ab text primary key); -INSERT INTO t1 VALUES ('a', 'b'), ('x', 'y'); -INSERT INTO t2 VALUES ('ab'), ('xy'); - -set enable_seqscan = off; -set enable_indexscan = on; -set enable_bitmapscan = off; - -explain (costs off) - SELECT * FROM - (SELECT a || b AS ab FROM t1 - UNION ALL - SELECT * FROM t2) t - WHERE ab = 'ab'; - -explain (costs off) - SELECT * FROM - (SELECT a || b AS ab FROM t1 - UNION - SELECT * FROM t2) t - WHERE ab = 'ab'; - --- --- Test that ORDER BY for UNION ALL can be pushed down to inheritance --- children. --- - -CREATE TEMP TABLE t1c (b text, a text); -ALTER TABLE t1c INHERIT t1; -CREATE TEMP TABLE t2c (primary key (ab)) INHERITS (t2); -INSERT INTO t1c VALUES ('v', 'w'), ('c', 'd'), ('m', 'n'), ('e', 'f'); -INSERT INTO t2c VALUES ('vw'), ('cd'), ('mn'), ('ef'); -CREATE INDEX t1c_ab_idx on t1c ((a || b)); - -set enable_seqscan = on; -set enable_indexonlyscan = off; - -explain (costs off) - SELECT * FROM - (SELECT a || b AS ab FROM t1 - UNION ALL - SELECT ab FROM t2) t - ORDER BY 1 LIMIT 8; - - SELECT * FROM - (SELECT a || b AS ab FROM t1 - UNION ALL - SELECT ab FROM t2) t - ORDER BY 1 LIMIT 8; - -reset enable_seqscan; -reset enable_indexscan; -reset enable_bitmapscan; - --- This simpler variant of the above test has been observed to fail differently - -create table events (event_id int primary key); -create table other_events (event_id int primary key); -create table events_child () inherits (events); - -explain (costs off) -select event_id - from (select event_id from events - union all - select event_id from other_events) ss - order by event_id; - -drop table events_child, events, other_events; - -reset enable_indexonlyscan; - --- Test constraint exclusion of UNION ALL subqueries -explain (costs off) - SELECT * FROM - (SELECT 1 AS t, * FROM tenk1 a - UNION ALL - SELECT 2 AS t, * FROM tenk1 b) c - WHERE t = 2; - --- Test that we push quals into UNION sub-selects only when it's safe -explain (costs off) -SELECT * FROM - (SELECT 1 AS t, 2 AS x - UNION - SELECT 2 AS t, 4 AS x) ss -WHERE x < 4 -ORDER BY x; - -SELECT * FROM - (SELECT 1 AS t, 2 AS x - UNION - SELECT 2 AS t, 4 AS x) ss -WHERE x < 4 -ORDER BY x; - -explain (costs off) -SELECT * FROM - (SELECT 1 AS t, generate_series(1,10) AS x - UNION - SELECT 2 AS t, 4 AS x) ss -WHERE x < 4 -ORDER BY x; - -SELECT * FROM - (SELECT 1 AS t, generate_series(1,10) AS x - UNION - SELECT 2 AS t, 4 AS x) ss -WHERE x < 4 -ORDER BY x; - -explain (costs off) -SELECT * FROM - (SELECT 1 AS t, (random()*3)::int AS x - UNION - SELECT 2 AS t, 4 AS x) ss -WHERE x > 3 -ORDER BY x; - -SELECT * FROM - (SELECT 1 AS t, (random()*3)::int AS x - UNION - SELECT 2 AS t, 4 AS x) ss -WHERE x > 3 -ORDER BY x; - --- Test cases where the native ordering of a sub-select has more pathkeys --- than the outer query cares about -explain (costs off) -select distinct q1 from - (select distinct * from int8_tbl i81 - union all - select distinct * from int8_tbl i82) ss -where q2 = q2; - -select distinct q1 from - (select distinct * from int8_tbl i81 - union all - select distinct * from int8_tbl i82) ss -where q2 = q2; - -explain (costs off) -select distinct q1 from - (select distinct * from int8_tbl i81 - union all - select distinct * from int8_tbl i82) ss -where -q1 = q2; - -select distinct q1 from - (select distinct * from int8_tbl i81 - union all - select distinct * from int8_tbl i82) ss -where -q1 = q2; - --- Test proper handling of parameterized appendrel paths when the --- potential join qual is expensive -create function expensivefunc(int) returns int -language plpgsql immutable strict cost 10000 -as $$begin return $1; end$$; - -create temp table t3 as select generate_series(-1000,1000) as x; -create index t3i on t3 (expensivefunc(x)); -analyze t3; - -explain (costs off) -select * from - (select * from t3 a union all select * from t3 b) ss - join int4_tbl on f1 = expensivefunc(x); -select * from - (select * from t3 a union all select * from t3 b) ss - join int4_tbl on f1 = expensivefunc(x); - -drop table t3; -drop function expensivefunc(int); - --- Test handling of appendrel quals that const-simplify into an AND -explain (costs off) -select * from - (select *, 0 as x from int8_tbl a - union all - select *, 1 as x from int8_tbl b) ss -where (x = 0) or (q1 >= q2 and q1 <= q2); -select * from - (select *, 0 as x from int8_tbl a - union all - select *, 1 as x from int8_tbl b) ss -where (x = 0) or (q1 >= q2 and q1 <= q2); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fupdatable_views.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fupdatable_views.sql deleted file mode 100644 index fa206a8fe7..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fupdatable_views.sql +++ /dev/null @@ -1,1714 +0,0 @@ --- --- UPDATABLE VIEWS --- - --- avoid bit-exact output here because operations may not be bit-exact. -SET extra_float_digits = 0; - --- check that non-updatable views and columns are rejected with useful error --- messages - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i); - -CREATE VIEW ro_view1 AS SELECT DISTINCT a, b FROM base_tbl; -- DISTINCT not supported -CREATE VIEW ro_view2 AS SELECT a, b FROM base_tbl GROUP BY a, b; -- GROUP BY not supported -CREATE VIEW ro_view3 AS SELECT 1 FROM base_tbl HAVING max(a) > 0; -- HAVING not supported -CREATE VIEW ro_view4 AS SELECT count(*) FROM base_tbl; -- Aggregate functions not supported -CREATE VIEW ro_view5 AS SELECT a, rank() OVER() FROM base_tbl; -- Window functions not supported -CREATE VIEW ro_view6 AS SELECT a, b FROM base_tbl UNION SELECT -a, b FROM base_tbl; -- Set ops not supported -CREATE VIEW ro_view7 AS WITH t AS (SELECT a, b FROM base_tbl) SELECT * FROM t; -- WITH not supported -CREATE VIEW ro_view8 AS SELECT a, b FROM base_tbl ORDER BY a OFFSET 1; -- OFFSET not supported -CREATE VIEW ro_view9 AS SELECT a, b FROM base_tbl ORDER BY a LIMIT 1; -- LIMIT not supported -CREATE VIEW ro_view10 AS SELECT 1 AS a; -- No base relations -CREATE VIEW ro_view11 AS SELECT b1.a, b2.b FROM base_tbl b1, base_tbl b2; -- Multiple base relations -CREATE VIEW ro_view12 AS SELECT * FROM generate_series(1, 10) AS g(a); -- SRF in rangetable -CREATE VIEW ro_view13 AS SELECT a, b FROM (SELECT * FROM base_tbl) AS t; -- Subselect in rangetable -CREATE VIEW rw_view14 AS SELECT ctid, a, b FROM base_tbl; -- System columns may be part of an updatable view -CREATE VIEW rw_view15 AS SELECT a, upper(b) FROM base_tbl; -- Expression/function may be part of an updatable view -CREATE VIEW rw_view16 AS SELECT a, b, a AS aa FROM base_tbl; -- Repeated column may be part of an updatable view -CREATE VIEW ro_view17 AS SELECT * FROM ro_view1; -- Base relation not updatable -CREATE VIEW ro_view18 AS SELECT * FROM (VALUES(1)) AS tmp(a); -- VALUES in rangetable -CREATE SEQUENCE uv_seq; -CREATE VIEW ro_view19 AS SELECT * FROM uv_seq; -- View based on a sequence -CREATE VIEW ro_view20 AS SELECT a, b, generate_series(1, a) g FROM base_tbl; -- SRF in targetlist not supported - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE E'r_\\_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name LIKE E'r_\\_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE E'r_\\_view%' - ORDER BY table_name, ordinal_position; - --- Read-only views -DELETE FROM ro_view1; -DELETE FROM ro_view2; -DELETE FROM ro_view3; -DELETE FROM ro_view4; -DELETE FROM ro_view5; -DELETE FROM ro_view6; -UPDATE ro_view7 SET a=a+1; -UPDATE ro_view8 SET a=a+1; -UPDATE ro_view9 SET a=a+1; -UPDATE ro_view10 SET a=a+1; -UPDATE ro_view11 SET a=a+1; -UPDATE ro_view12 SET a=a+1; -INSERT INTO ro_view13 VALUES (3, 'Row 3'); --- Partially updatable view -INSERT INTO rw_view14 VALUES (null, 3, 'Row 3'); -- should fail -INSERT INTO rw_view14 (a, b) VALUES (3, 'Row 3'); -- should be OK -UPDATE rw_view14 SET ctid=null WHERE a=3; -- should fail -UPDATE rw_view14 SET b='ROW 3' WHERE a=3; -- should be OK -SELECT * FROM base_tbl; -DELETE FROM rw_view14 WHERE a=3; -- should be OK --- Partially updatable view -INSERT INTO rw_view15 VALUES (3, 'ROW 3'); -- should fail -INSERT INTO rw_view15 (a) VALUES (3); -- should be OK -INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT DO NOTHING; -- succeeds -SELECT * FROM rw_view15; -INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO NOTHING; -- succeeds -SELECT * FROM rw_view15; -INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO UPDATE set a = excluded.a; -- succeeds -SELECT * FROM rw_view15; -INSERT INTO rw_view15 (a) VALUES (3) ON CONFLICT (a) DO UPDATE set upper = 'blarg'; -- fails -SELECT * FROM rw_view15; -SELECT * FROM rw_view15; -ALTER VIEW rw_view15 ALTER COLUMN upper SET DEFAULT 'NOT SET'; -INSERT INTO rw_view15 (a) VALUES (4); -- should fail -UPDATE rw_view15 SET upper='ROW 3' WHERE a=3; -- should fail -UPDATE rw_view15 SET upper=DEFAULT WHERE a=3; -- should fail -UPDATE rw_view15 SET a=4 WHERE a=3; -- should be OK -SELECT * FROM base_tbl; -DELETE FROM rw_view15 WHERE a=4; -- should be OK --- Partially updatable view -INSERT INTO rw_view16 VALUES (3, 'Row 3', 3); -- should fail -INSERT INTO rw_view16 (a, b) VALUES (3, 'Row 3'); -- should be OK -UPDATE rw_view16 SET a=3, aa=-3 WHERE a=3; -- should fail -UPDATE rw_view16 SET aa=-3 WHERE a=3; -- should be OK -SELECT * FROM base_tbl; -DELETE FROM rw_view16 WHERE a=-3; -- should be OK --- Read-only views -INSERT INTO ro_view17 VALUES (3, 'ROW 3'); -DELETE FROM ro_view18; -UPDATE ro_view19 SET last_value=1000; -UPDATE ro_view20 SET b=upper(b); - --- A view with a conditional INSTEAD rule but no unconditional INSTEAD rules --- or INSTEAD OF triggers should be non-updatable and generate useful error --- messages with appropriate detail -CREATE RULE rw_view16_ins_rule AS ON INSERT TO rw_view16 - WHERE NEW.a > 0 DO INSTEAD INSERT INTO base_tbl VALUES (NEW.a, NEW.b); -CREATE RULE rw_view16_upd_rule AS ON UPDATE TO rw_view16 - WHERE OLD.a > 0 DO INSTEAD UPDATE base_tbl SET b=NEW.b WHERE a=OLD.a; -CREATE RULE rw_view16_del_rule AS ON DELETE TO rw_view16 - WHERE OLD.a > 0 DO INSTEAD DELETE FROM base_tbl WHERE a=OLD.a; - -INSERT INTO rw_view16 (a, b) VALUES (3, 'Row 3'); -- should fail -UPDATE rw_view16 SET b='ROW 2' WHERE a=2; -- should fail -DELETE FROM rw_view16 WHERE a=2; -- should fail - -DROP TABLE base_tbl CASCADE; -DROP VIEW ro_view10, ro_view12, ro_view18; -DROP SEQUENCE uv_seq CASCADE; - --- simple updatable view - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a>0; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name = 'rw_view1'; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name = 'rw_view1'; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name = 'rw_view1' - ORDER BY ordinal_position; - -INSERT INTO rw_view1 VALUES (3, 'Row 3'); -INSERT INTO rw_view1 (a) VALUES (4); -UPDATE rw_view1 SET a=5 WHERE a=4; -DELETE FROM rw_view1 WHERE b='Row 2'; -SELECT * FROM base_tbl; - -EXPLAIN (costs off) UPDATE rw_view1 SET a=6 WHERE a=5; -EXPLAIN (costs off) DELETE FROM rw_view1 WHERE a=5; - -DROP TABLE base_tbl CASCADE; - --- view on top of view - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i); - -CREATE VIEW rw_view1 AS SELECT b AS bb, a AS aa FROM base_tbl WHERE a>0; -CREATE VIEW rw_view2 AS SELECT aa AS aaa, bb AS bbb FROM rw_view1 WHERE aa<10; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name = 'rw_view2'; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name = 'rw_view2'; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name = 'rw_view2' - ORDER BY ordinal_position; - -INSERT INTO rw_view2 VALUES (3, 'Row 3'); -INSERT INTO rw_view2 (aaa) VALUES (4); -SELECT * FROM rw_view2; -UPDATE rw_view2 SET bbb='Row 4' WHERE aaa=4; -DELETE FROM rw_view2 WHERE aaa=2; -SELECT * FROM rw_view2; - -EXPLAIN (costs off) UPDATE rw_view2 SET aaa=5 WHERE aaa=4; -EXPLAIN (costs off) DELETE FROM rw_view2 WHERE aaa=4; - -DROP TABLE base_tbl CASCADE; - --- view on top of view with rules - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a>0 OFFSET 0; -- not updatable without rules/triggers -CREATE VIEW rw_view2 AS SELECT * FROM rw_view1 WHERE a<10; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -CREATE RULE rw_view1_ins_rule AS ON INSERT TO rw_view1 - DO INSTEAD INSERT INTO base_tbl VALUES (NEW.a, NEW.b) RETURNING *; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -CREATE RULE rw_view1_upd_rule AS ON UPDATE TO rw_view1 - DO INSTEAD UPDATE base_tbl SET b=NEW.b WHERE a=OLD.a RETURNING NEW.*; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -CREATE RULE rw_view1_del_rule AS ON DELETE TO rw_view1 - DO INSTEAD DELETE FROM base_tbl WHERE a=OLD.a RETURNING OLD.*; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -INSERT INTO rw_view2 VALUES (3, 'Row 3') RETURNING *; -UPDATE rw_view2 SET b='Row three' WHERE a=3 RETURNING *; -SELECT * FROM rw_view2; -DELETE FROM rw_view2 WHERE a=3 RETURNING *; -SELECT * FROM rw_view2; - -EXPLAIN (costs off) UPDATE rw_view2 SET a=3 WHERE a=2; -EXPLAIN (costs off) DELETE FROM rw_view2 WHERE a=2; - -DROP TABLE base_tbl CASCADE; - --- view on top of view with triggers - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a>0 OFFSET 0; -- not updatable without rules/triggers -CREATE VIEW rw_view2 AS SELECT * FROM rw_view1 WHERE a<10; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into, - is_trigger_updatable, is_trigger_deletable, - is_trigger_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -CREATE FUNCTION rw_view1_trig_fn() -RETURNS trigger AS -$$ -BEGIN - IF TG_OP = 'INSERT' THEN - INSERT INTO base_tbl VALUES (NEW.a, NEW.b); - RETURN NEW; - ELSIF TG_OP = 'UPDATE' THEN - UPDATE base_tbl SET b=NEW.b WHERE a=OLD.a; - RETURN NEW; - ELSIF TG_OP = 'DELETE' THEN - DELETE FROM base_tbl WHERE a=OLD.a; - RETURN OLD; - END IF; -END; -$$ -LANGUAGE plpgsql; - -CREATE TRIGGER rw_view1_ins_trig INSTEAD OF INSERT ON rw_view1 - FOR EACH ROW EXECUTE PROCEDURE rw_view1_trig_fn(); - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into, - is_trigger_updatable, is_trigger_deletable, - is_trigger_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -CREATE TRIGGER rw_view1_upd_trig INSTEAD OF UPDATE ON rw_view1 - FOR EACH ROW EXECUTE PROCEDURE rw_view1_trig_fn(); - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into, - is_trigger_updatable, is_trigger_deletable, - is_trigger_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -CREATE TRIGGER rw_view1_del_trig INSTEAD OF DELETE ON rw_view1 - FOR EACH ROW EXECUTE PROCEDURE rw_view1_trig_fn(); - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into, - is_trigger_updatable, is_trigger_deletable, - is_trigger_insertable_into - FROM information_schema.views - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE 'rw_view%' - ORDER BY table_name, ordinal_position; - -INSERT INTO rw_view2 VALUES (3, 'Row 3') RETURNING *; -UPDATE rw_view2 SET b='Row three' WHERE a=3 RETURNING *; -SELECT * FROM rw_view2; -DELETE FROM rw_view2 WHERE a=3 RETURNING *; -SELECT * FROM rw_view2; - -EXPLAIN (costs off) UPDATE rw_view2 SET a=3 WHERE a=2; -EXPLAIN (costs off) DELETE FROM rw_view2 WHERE a=2; - -DROP TABLE base_tbl CASCADE; -DROP FUNCTION rw_view1_trig_fn(); - --- update using whole row from view - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl SELECT i, 'Row ' || i FROM generate_series(-2, 2) g(i); - -CREATE VIEW rw_view1 AS SELECT b AS bb, a AS aa FROM base_tbl; - -CREATE FUNCTION rw_view1_aa(x rw_view1) - RETURNS int AS $$ SELECT x.aa $$ LANGUAGE sql; - -UPDATE rw_view1 v SET bb='Updated row 2' WHERE rw_view1_aa(v)=2 - RETURNING rw_view1_aa(v), v.bb; -SELECT * FROM base_tbl; - -EXPLAIN (costs off) -UPDATE rw_view1 v SET bb='Updated row 2' WHERE rw_view1_aa(v)=2 - RETURNING rw_view1_aa(v), v.bb; - -DROP TABLE base_tbl CASCADE; - --- permissions checks - -CREATE USER regress_view_user1; -CREATE USER regress_view_user2; -CREATE USER regress_view_user3; - -SET SESSION AUTHORIZATION regress_view_user1; -CREATE TABLE base_tbl(a int, b text, c float); -INSERT INTO base_tbl VALUES (1, 'Row 1', 1.0); -CREATE VIEW rw_view1 AS SELECT b AS bb, c AS cc, a AS aa FROM base_tbl; -INSERT INTO rw_view1 VALUES ('Row 2', 2.0, 2); - -GRANT SELECT ON base_tbl TO regress_view_user2; -GRANT SELECT ON rw_view1 TO regress_view_user2; -GRANT UPDATE (a,c) ON base_tbl TO regress_view_user2; -GRANT UPDATE (bb,cc) ON rw_view1 TO regress_view_user2; -RESET SESSION AUTHORIZATION; - -SET SESSION AUTHORIZATION regress_view_user2; -CREATE VIEW rw_view2 AS SELECT b AS bb, c AS cc, a AS aa FROM base_tbl; -SELECT * FROM base_tbl; -- ok -SELECT * FROM rw_view1; -- ok -SELECT * FROM rw_view2; -- ok - -INSERT INTO base_tbl VALUES (3, 'Row 3', 3.0); -- not allowed -INSERT INTO rw_view1 VALUES ('Row 3', 3.0, 3); -- not allowed -INSERT INTO rw_view2 VALUES ('Row 3', 3.0, 3); -- not allowed - -UPDATE base_tbl SET a=a, c=c; -- ok -UPDATE base_tbl SET b=b; -- not allowed -UPDATE rw_view1 SET bb=bb, cc=cc; -- ok -UPDATE rw_view1 SET aa=aa; -- not allowed -UPDATE rw_view2 SET aa=aa, cc=cc; -- ok -UPDATE rw_view2 SET bb=bb; -- not allowed - -DELETE FROM base_tbl; -- not allowed -DELETE FROM rw_view1; -- not allowed -DELETE FROM rw_view2; -- not allowed -RESET SESSION AUTHORIZATION; - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT INSERT, DELETE ON base_tbl TO regress_view_user2; -RESET SESSION AUTHORIZATION; - -SET SESSION AUTHORIZATION regress_view_user2; -INSERT INTO base_tbl VALUES (3, 'Row 3', 3.0); -- ok -INSERT INTO rw_view1 VALUES ('Row 4', 4.0, 4); -- not allowed -INSERT INTO rw_view2 VALUES ('Row 4', 4.0, 4); -- ok -DELETE FROM base_tbl WHERE a=1; -- ok -DELETE FROM rw_view1 WHERE aa=2; -- not allowed -DELETE FROM rw_view2 WHERE aa=2; -- ok -SELECT * FROM base_tbl; -RESET SESSION AUTHORIZATION; - -SET SESSION AUTHORIZATION regress_view_user1; -REVOKE INSERT, DELETE ON base_tbl FROM regress_view_user2; -GRANT INSERT, DELETE ON rw_view1 TO regress_view_user2; -RESET SESSION AUTHORIZATION; - -SET SESSION AUTHORIZATION regress_view_user2; -INSERT INTO base_tbl VALUES (5, 'Row 5', 5.0); -- not allowed -INSERT INTO rw_view1 VALUES ('Row 5', 5.0, 5); -- ok -INSERT INTO rw_view2 VALUES ('Row 6', 6.0, 6); -- not allowed -DELETE FROM base_tbl WHERE a=3; -- not allowed -DELETE FROM rw_view1 WHERE aa=3; -- ok -DELETE FROM rw_view2 WHERE aa=4; -- not allowed -SELECT * FROM base_tbl; -RESET SESSION AUTHORIZATION; - -DROP TABLE base_tbl CASCADE; - --- nested-view permissions - -CREATE TABLE base_tbl(a int, b text, c float); -INSERT INTO base_tbl VALUES (1, 'Row 1', 1.0); - -SET SESSION AUTHORIZATION regress_view_user1; -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl; -SELECT * FROM rw_view1; -- not allowed -SELECT * FROM rw_view1 FOR UPDATE; -- not allowed -UPDATE rw_view1 SET b = 'foo' WHERE a = 1; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user2; -CREATE VIEW rw_view2 AS SELECT * FROM rw_view1; -SELECT * FROM rw_view2; -- not allowed -SELECT * FROM rw_view2 FOR UPDATE; -- not allowed -UPDATE rw_view2 SET b = 'bar' WHERE a = 1; -- not allowed - -RESET SESSION AUTHORIZATION; -GRANT SELECT ON base_tbl TO regress_view_user1; - -SET SESSION AUTHORIZATION regress_view_user1; -SELECT * FROM rw_view1; -SELECT * FROM rw_view1 FOR UPDATE; -- not allowed -UPDATE rw_view1 SET b = 'foo' WHERE a = 1; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -- not allowed -SELECT * FROM rw_view2 FOR UPDATE; -- not allowed -UPDATE rw_view2 SET b = 'bar' WHERE a = 1; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT SELECT ON rw_view1 TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -SELECT * FROM rw_view2 FOR UPDATE; -- not allowed -UPDATE rw_view2 SET b = 'bar' WHERE a = 1; -- not allowed - -RESET SESSION AUTHORIZATION; -GRANT UPDATE ON base_tbl TO regress_view_user1; - -SET SESSION AUTHORIZATION regress_view_user1; -SELECT * FROM rw_view1; -SELECT * FROM rw_view1 FOR UPDATE; -UPDATE rw_view1 SET b = 'foo' WHERE a = 1; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -SELECT * FROM rw_view2 FOR UPDATE; -- not allowed -UPDATE rw_view2 SET b = 'bar' WHERE a = 1; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT UPDATE ON rw_view1 TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -SELECT * FROM rw_view2 FOR UPDATE; -UPDATE rw_view2 SET b = 'bar' WHERE a = 1; - -RESET SESSION AUTHORIZATION; -REVOKE UPDATE ON base_tbl FROM regress_view_user1; - -SET SESSION AUTHORIZATION regress_view_user1; -SELECT * FROM rw_view1; -SELECT * FROM rw_view1 FOR UPDATE; -- not allowed -UPDATE rw_view1 SET b = 'foo' WHERE a = 1; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -SELECT * FROM rw_view2 FOR UPDATE; -- not allowed -UPDATE rw_view2 SET b = 'bar' WHERE a = 1; -- not allowed - -RESET SESSION AUTHORIZATION; - -DROP TABLE base_tbl CASCADE; - --- security invoker view permissions - -SET SESSION AUTHORIZATION regress_view_user1; -CREATE TABLE base_tbl(a int, b text, c float); -INSERT INTO base_tbl VALUES (1, 'Row 1', 1.0); -CREATE VIEW rw_view1 AS SELECT b AS bb, c AS cc, a AS aa FROM base_tbl; -ALTER VIEW rw_view1 SET (security_invoker = true); -INSERT INTO rw_view1 VALUES ('Row 2', 2.0, 2); -GRANT SELECT ON rw_view1 TO regress_view_user2; -GRANT UPDATE (bb,cc) ON rw_view1 TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM base_tbl; -- not allowed -SELECT * FROM rw_view1; -- not allowed -INSERT INTO base_tbl VALUES (3, 'Row 3', 3.0); -- not allowed -INSERT INTO rw_view1 VALUES ('Row 3', 3.0, 3); -- not allowed -UPDATE base_tbl SET a=a; -- not allowed -UPDATE rw_view1 SET bb=bb, cc=cc; -- not allowed -DELETE FROM base_tbl; -- not allowed -DELETE FROM rw_view1; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT SELECT ON base_tbl TO regress_view_user2; -GRANT UPDATE (a,c) ON base_tbl TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM base_tbl; -- ok -SELECT * FROM rw_view1; -- ok -UPDATE base_tbl SET a=a, c=c; -- ok -UPDATE base_tbl SET b=b; -- not allowed -UPDATE rw_view1 SET cc=cc; -- ok -UPDATE rw_view1 SET aa=aa; -- not allowed -UPDATE rw_view1 SET bb=bb; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT INSERT, DELETE ON base_tbl TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -INSERT INTO base_tbl VALUES (3, 'Row 3', 3.0); -- ok -INSERT INTO rw_view1 VALUES ('Row 4', 4.0, 4); -- not allowed -DELETE FROM base_tbl WHERE a=1; -- ok -DELETE FROM rw_view1 WHERE aa=2; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -REVOKE INSERT, DELETE ON base_tbl FROM regress_view_user2; -GRANT INSERT, DELETE ON rw_view1 TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -INSERT INTO rw_view1 VALUES ('Row 4', 4.0, 4); -- not allowed -DELETE FROM rw_view1 WHERE aa=2; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT INSERT, DELETE ON base_tbl TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -INSERT INTO rw_view1 VALUES ('Row 4', 4.0, 4); -- ok -DELETE FROM rw_view1 WHERE aa=2; -- ok -SELECT * FROM base_tbl; -- ok - -RESET SESSION AUTHORIZATION; - -DROP TABLE base_tbl CASCADE; - --- ordinary view on top of security invoker view permissions - -CREATE TABLE base_tbl(a int, b text, c float); -INSERT INTO base_tbl VALUES (1, 'Row 1', 1.0); - -SET SESSION AUTHORIZATION regress_view_user1; -CREATE VIEW rw_view1 AS SELECT b AS bb, c AS cc, a AS aa FROM base_tbl; -ALTER VIEW rw_view1 SET (security_invoker = true); -SELECT * FROM rw_view1; -- not allowed -UPDATE rw_view1 SET aa=aa; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user2; -CREATE VIEW rw_view2 AS SELECT cc AS ccc, aa AS aaa, bb AS bbb FROM rw_view1; -GRANT SELECT, UPDATE ON rw_view2 TO regress_view_user3; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET aaa=aaa; -- not allowed - -RESET SESSION AUTHORIZATION; - -GRANT SELECT ON base_tbl TO regress_view_user1; -GRANT UPDATE (a, b) ON base_tbl TO regress_view_user1; - -SET SESSION AUTHORIZATION regress_view_user1; -SELECT * FROM rw_view1; -- ok -UPDATE rw_view1 SET aa=aa, bb=bb; -- ok -UPDATE rw_view1 SET cc=cc; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET aaa=aaa; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user3; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET aaa=aaa; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user1; -GRANT SELECT ON rw_view1 TO regress_view_user2; -GRANT UPDATE (bb, cc) ON rw_view1 TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user3; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed - -RESET SESSION AUTHORIZATION; - -GRANT SELECT ON base_tbl TO regress_view_user2; -GRANT UPDATE (a, c) ON base_tbl TO regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -- ok -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- ok - -SET SESSION AUTHORIZATION regress_view_user3; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- not allowed - -RESET SESSION AUTHORIZATION; - -GRANT SELECT ON base_tbl TO regress_view_user3; -GRANT UPDATE (a, c) ON base_tbl TO regress_view_user3; - -SET SESSION AUTHORIZATION regress_view_user3; -SELECT * FROM rw_view2; -- ok -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- ok - -RESET SESSION AUTHORIZATION; - -REVOKE SELECT, UPDATE ON base_tbl FROM regress_view_user1; - -SET SESSION AUTHORIZATION regress_view_user1; -SELECT * FROM rw_view1; -- not allowed -UPDATE rw_view1 SET aa=aa; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -- ok -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- ok - -SET SESSION AUTHORIZATION regress_view_user3; -SELECT * FROM rw_view2; -- ok -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- ok - -RESET SESSION AUTHORIZATION; - -REVOKE SELECT, UPDATE ON base_tbl FROM regress_view_user2; - -SET SESSION AUTHORIZATION regress_view_user2; -SELECT * FROM rw_view2; -- not allowed -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- not allowed - -SET SESSION AUTHORIZATION regress_view_user3; -SELECT * FROM rw_view2; -- ok -UPDATE rw_view2 SET aaa=aaa; -- not allowed -UPDATE rw_view2 SET bbb=bbb; -- not allowed -UPDATE rw_view2 SET ccc=ccc; -- ok - -RESET SESSION AUTHORIZATION; - -DROP TABLE base_tbl CASCADE; - -DROP USER regress_view_user1; -DROP USER regress_view_user2; -DROP USER regress_view_user3; - --- column defaults - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified', c serial); -INSERT INTO base_tbl VALUES (1, 'Row 1'); -INSERT INTO base_tbl VALUES (2, 'Row 2'); -INSERT INTO base_tbl VALUES (3); - -CREATE VIEW rw_view1 AS SELECT a AS aa, b AS bb FROM base_tbl; -ALTER VIEW rw_view1 ALTER COLUMN bb SET DEFAULT 'View default'; - -INSERT INTO rw_view1 VALUES (4, 'Row 4'); -INSERT INTO rw_view1 (aa) VALUES (5); - -SELECT * FROM base_tbl; - -DROP TABLE base_tbl CASCADE; - --- Table having triggers - -CREATE TABLE base_tbl (a int PRIMARY KEY, b text DEFAULT 'Unspecified'); -INSERT INTO base_tbl VALUES (1, 'Row 1'); -INSERT INTO base_tbl VALUES (2, 'Row 2'); - -CREATE FUNCTION rw_view1_trig_fn() -RETURNS trigger AS -$$ -BEGIN - IF TG_OP = 'INSERT' THEN - UPDATE base_tbl SET b=NEW.b WHERE a=1; - RETURN NULL; - END IF; - RETURN NULL; -END; -$$ -LANGUAGE plpgsql; - -CREATE TRIGGER rw_view1_ins_trig AFTER INSERT ON base_tbl - FOR EACH ROW EXECUTE PROCEDURE rw_view1_trig_fn(); - -CREATE VIEW rw_view1 AS SELECT a AS aa, b AS bb FROM base_tbl; - -INSERT INTO rw_view1 VALUES (3, 'Row 3'); -select * from base_tbl; - -DROP VIEW rw_view1; -DROP TRIGGER rw_view1_ins_trig on base_tbl; -DROP FUNCTION rw_view1_trig_fn(); -DROP TABLE base_tbl; - --- view with ORDER BY - -CREATE TABLE base_tbl (a int, b int); -INSERT INTO base_tbl VALUES (1,2), (4,5), (3,-3); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl ORDER BY a+b; - -SELECT * FROM rw_view1; - -INSERT INTO rw_view1 VALUES (7,-8); -SELECT * FROM rw_view1; - -EXPLAIN (verbose, costs off) UPDATE rw_view1 SET b = b + 1 RETURNING *; -UPDATE rw_view1 SET b = b + 1 RETURNING *; -SELECT * FROM rw_view1; - -DROP TABLE base_tbl CASCADE; - --- multiple array-column updates - -CREATE TABLE base_tbl (a int, arr int[]); -INSERT INTO base_tbl VALUES (1,ARRAY[2]), (3,ARRAY[4]); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl; - -UPDATE rw_view1 SET arr[1] = 42, arr[2] = 77 WHERE a = 3; - -SELECT * FROM rw_view1; - -DROP TABLE base_tbl CASCADE; - --- views with updatable and non-updatable columns - -CREATE TABLE base_tbl(a float); -INSERT INTO base_tbl SELECT i/10.0 FROM generate_series(1,10) g(i); - -CREATE VIEW rw_view1 AS - SELECT ctid, sin(a) s, a, cos(a) c - FROM base_tbl - WHERE a != 0 - ORDER BY abs(a); - -INSERT INTO rw_view1 VALUES (null, null, 1.1, null); -- should fail -INSERT INTO rw_view1 (s, c, a) VALUES (null, null, 1.1); -- should fail -INSERT INTO rw_view1 (a) VALUES (1.1) RETURNING a, s, c; -- OK -UPDATE rw_view1 SET s = s WHERE a = 1.1; -- should fail -UPDATE rw_view1 SET a = 1.05 WHERE a = 1.1 RETURNING s; -- OK -DELETE FROM rw_view1 WHERE a = 1.05; -- OK - -CREATE VIEW rw_view2 AS - SELECT s, c, s/c t, a base_a, ctid - FROM rw_view1; - -INSERT INTO rw_view2 VALUES (null, null, null, 1.1, null); -- should fail -INSERT INTO rw_view2(s, c, base_a) VALUES (null, null, 1.1); -- should fail -INSERT INTO rw_view2(base_a) VALUES (1.1) RETURNING t; -- OK -UPDATE rw_view2 SET s = s WHERE base_a = 1.1; -- should fail -UPDATE rw_view2 SET t = t WHERE base_a = 1.1; -- should fail -UPDATE rw_view2 SET base_a = 1.05 WHERE base_a = 1.1; -- OK -DELETE FROM rw_view2 WHERE base_a = 1.05 RETURNING base_a, s, c, t; -- OK - -CREATE VIEW rw_view3 AS - SELECT s, c, s/c t, ctid - FROM rw_view1; - -INSERT INTO rw_view3 VALUES (null, null, null, null); -- should fail -INSERT INTO rw_view3(s) VALUES (null); -- should fail -UPDATE rw_view3 SET s = s; -- should fail -DELETE FROM rw_view3 WHERE s = sin(0.1); -- should be OK -SELECT * FROM base_tbl ORDER BY a; - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name LIKE E'r_\\_view%' - ORDER BY table_name; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name LIKE E'r_\\_view%' - ORDER BY table_name; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name LIKE E'r_\\_view%' - ORDER BY table_name, ordinal_position; - -SELECT events & 4 != 0 AS upd, - events & 8 != 0 AS ins, - events & 16 != 0 AS del - FROM pg_catalog.pg_relation_is_updatable('rw_view3'::regclass, false) t(events); - -DROP TABLE base_tbl CASCADE; - --- view on table with GENERATED columns - -CREATE TABLE base_tbl (id int, idplus1 int GENERATED ALWAYS AS (id + 1) STORED); -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl; - -INSERT INTO base_tbl (id) VALUES (1); -INSERT INTO rw_view1 (id) VALUES (2); -INSERT INTO base_tbl (id, idplus1) VALUES (3, DEFAULT); -INSERT INTO rw_view1 (id, idplus1) VALUES (4, DEFAULT); -INSERT INTO base_tbl (id, idplus1) VALUES (5, 6); -- error -INSERT INTO rw_view1 (id, idplus1) VALUES (6, 7); -- error - -SELECT * FROM base_tbl; - -UPDATE base_tbl SET id = 2000 WHERE id = 2; -UPDATE rw_view1 SET id = 3000 WHERE id = 3; - -SELECT * FROM base_tbl; - -DROP TABLE base_tbl CASCADE; - --- inheritance tests - -CREATE TABLE base_tbl_parent (a int); -CREATE TABLE base_tbl_child (CHECK (a > 0)) INHERITS (base_tbl_parent); -INSERT INTO base_tbl_parent SELECT * FROM generate_series(-8, -1); -INSERT INTO base_tbl_child SELECT * FROM generate_series(1, 8); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl_parent; -CREATE VIEW rw_view2 AS SELECT * FROM ONLY base_tbl_parent; - -SELECT * FROM rw_view1 ORDER BY a; -SELECT * FROM ONLY rw_view1 ORDER BY a; -SELECT * FROM rw_view2 ORDER BY a; - -INSERT INTO rw_view1 VALUES (-100), (100); -INSERT INTO rw_view2 VALUES (-200), (200); - -UPDATE rw_view1 SET a = a*10 WHERE a IN (-1, 1); -- Should produce -10 and 10 -UPDATE ONLY rw_view1 SET a = a*10 WHERE a IN (-2, 2); -- Should produce -20 and 20 -UPDATE rw_view2 SET a = a*10 WHERE a IN (-3, 3); -- Should produce -30 only -UPDATE ONLY rw_view2 SET a = a*10 WHERE a IN (-4, 4); -- Should produce -40 only - -DELETE FROM rw_view1 WHERE a IN (-5, 5); -- Should delete -5 and 5 -DELETE FROM ONLY rw_view1 WHERE a IN (-6, 6); -- Should delete -6 and 6 -DELETE FROM rw_view2 WHERE a IN (-7, 7); -- Should delete -7 only -DELETE FROM ONLY rw_view2 WHERE a IN (-8, 8); -- Should delete -8 only - -SELECT * FROM ONLY base_tbl_parent ORDER BY a; -SELECT * FROM base_tbl_child ORDER BY a; - -CREATE TABLE other_tbl_parent (id int); -CREATE TABLE other_tbl_child () INHERITS (other_tbl_parent); -INSERT INTO other_tbl_parent VALUES (7),(200); -INSERT INTO other_tbl_child VALUES (8),(100); - -EXPLAIN (costs off) -UPDATE rw_view1 SET a = a + 1000 FROM other_tbl_parent WHERE a = id; -UPDATE rw_view1 SET a = a + 1000 FROM other_tbl_parent WHERE a = id; - -SELECT * FROM ONLY base_tbl_parent ORDER BY a; -SELECT * FROM base_tbl_child ORDER BY a; - -DROP TABLE base_tbl_parent, base_tbl_child CASCADE; -DROP TABLE other_tbl_parent CASCADE; - --- simple WITH CHECK OPTION - -CREATE TABLE base_tbl (a int, b int DEFAULT 10); -INSERT INTO base_tbl VALUES (1,2), (2,3), (1,-1); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a < b - WITH LOCAL CHECK OPTION; -\d+ rw_view1 -SELECT * FROM information_schema.views WHERE table_name = 'rw_view1'; - -INSERT INTO rw_view1 VALUES(3,4); -- ok -INSERT INTO rw_view1 VALUES(4,3); -- should fail -INSERT INTO rw_view1 VALUES(5,null); -- should fail -UPDATE rw_view1 SET b = 5 WHERE a = 3; -- ok -UPDATE rw_view1 SET b = -5 WHERE a = 3; -- should fail -INSERT INTO rw_view1(a) VALUES (9); -- ok -INSERT INTO rw_view1(a) VALUES (10); -- should fail -SELECT * FROM base_tbl; - -DROP TABLE base_tbl CASCADE; - --- WITH LOCAL/CASCADED CHECK OPTION - -CREATE TABLE base_tbl (a int); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a > 0; -CREATE VIEW rw_view2 AS SELECT * FROM rw_view1 WHERE a < 10 - WITH CHECK OPTION; -- implicitly cascaded -\d+ rw_view2 -SELECT * FROM information_schema.views WHERE table_name = 'rw_view2'; - -INSERT INTO rw_view2 VALUES (-5); -- should fail -INSERT INTO rw_view2 VALUES (5); -- ok -INSERT INTO rw_view2 VALUES (15); -- should fail -SELECT * FROM base_tbl; - -UPDATE rw_view2 SET a = a - 10; -- should fail -UPDATE rw_view2 SET a = a + 10; -- should fail - -CREATE OR REPLACE VIEW rw_view2 AS SELECT * FROM rw_view1 WHERE a < 10 - WITH LOCAL CHECK OPTION; -\d+ rw_view2 -SELECT * FROM information_schema.views WHERE table_name = 'rw_view2'; - -INSERT INTO rw_view2 VALUES (-10); -- ok, but not in view -INSERT INTO rw_view2 VALUES (20); -- should fail -SELECT * FROM base_tbl; - -ALTER VIEW rw_view1 SET (check_option=here); -- invalid -ALTER VIEW rw_view1 SET (check_option=local); - -INSERT INTO rw_view2 VALUES (-20); -- should fail -INSERT INTO rw_view2 VALUES (30); -- should fail - -ALTER VIEW rw_view2 RESET (check_option); -\d+ rw_view2 -SELECT * FROM information_schema.views WHERE table_name = 'rw_view2'; -INSERT INTO rw_view2 VALUES (30); -- ok, but not in view -SELECT * FROM base_tbl; - -DROP TABLE base_tbl CASCADE; - --- WITH CHECK OPTION with no local view qual - -CREATE TABLE base_tbl (a int); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WITH CHECK OPTION; -CREATE VIEW rw_view2 AS SELECT * FROM rw_view1 WHERE a > 0; -CREATE VIEW rw_view3 AS SELECT * FROM rw_view2 WITH CHECK OPTION; -SELECT * FROM information_schema.views WHERE table_name LIKE E'rw\\_view_' ORDER BY table_name; - -INSERT INTO rw_view1 VALUES (-1); -- ok -INSERT INTO rw_view1 VALUES (1); -- ok -INSERT INTO rw_view2 VALUES (-2); -- ok, but not in view -INSERT INTO rw_view2 VALUES (2); -- ok -INSERT INTO rw_view3 VALUES (-3); -- should fail -INSERT INTO rw_view3 VALUES (3); -- ok - -DROP TABLE base_tbl CASCADE; - --- WITH CHECK OPTION with scalar array ops - -CREATE TABLE base_tbl (a int, b int[]); -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a = ANY (b) - WITH CHECK OPTION; - -INSERT INTO rw_view1 VALUES (1, ARRAY[1,2,3]); -- ok -INSERT INTO rw_view1 VALUES (10, ARRAY[4,5]); -- should fail - -UPDATE rw_view1 SET b[2] = -b[2] WHERE a = 1; -- ok -UPDATE rw_view1 SET b[1] = -b[1] WHERE a = 1; -- should fail - -PREPARE ins(int, int[]) AS INSERT INTO rw_view1 VALUES($1, $2); -EXECUTE ins(2, ARRAY[1,2,3]); -- ok -EXECUTE ins(10, ARRAY[4,5]); -- should fail -DEALLOCATE PREPARE ins; - -DROP TABLE base_tbl CASCADE; - --- WITH CHECK OPTION with subquery - -CREATE TABLE base_tbl (a int); -CREATE TABLE ref_tbl (a int PRIMARY KEY); -INSERT INTO ref_tbl SELECT * FROM generate_series(1,10); - -CREATE VIEW rw_view1 AS - SELECT * FROM base_tbl b - WHERE EXISTS(SELECT 1 FROM ref_tbl r WHERE r.a = b.a) - WITH CHECK OPTION; - -INSERT INTO rw_view1 VALUES (5); -- ok -INSERT INTO rw_view1 VALUES (15); -- should fail - -UPDATE rw_view1 SET a = a + 5; -- ok -UPDATE rw_view1 SET a = a + 5; -- should fail - -EXPLAIN (costs off) INSERT INTO rw_view1 VALUES (5); -EXPLAIN (costs off) UPDATE rw_view1 SET a = a + 5; - -DROP TABLE base_tbl, ref_tbl CASCADE; - --- WITH CHECK OPTION with BEFORE trigger on base table - -CREATE TABLE base_tbl (a int, b int); - -CREATE FUNCTION base_tbl_trig_fn() -RETURNS trigger AS -$$ -BEGIN - NEW.b := 10; - RETURN NEW; -END; -$$ -LANGUAGE plpgsql; - -CREATE TRIGGER base_tbl_trig BEFORE INSERT OR UPDATE ON base_tbl - FOR EACH ROW EXECUTE PROCEDURE base_tbl_trig_fn(); - -CREATE VIEW rw_view1 AS SELECT * FROM base_tbl WHERE a < b WITH CHECK OPTION; - -INSERT INTO rw_view1 VALUES (5,0); -- ok -INSERT INTO rw_view1 VALUES (15, 20); -- should fail -UPDATE rw_view1 SET a = 20, b = 30; -- should fail - -DROP TABLE base_tbl CASCADE; -DROP FUNCTION base_tbl_trig_fn(); - --- WITH LOCAL CHECK OPTION with INSTEAD OF trigger on base view - -CREATE TABLE base_tbl (a int, b int); - -CREATE VIEW rw_view1 AS SELECT a FROM base_tbl WHERE a < b; - -CREATE FUNCTION rw_view1_trig_fn() -RETURNS trigger AS -$$ -BEGIN - IF TG_OP = 'INSERT' THEN - INSERT INTO base_tbl VALUES (NEW.a, 10); - RETURN NEW; - ELSIF TG_OP = 'UPDATE' THEN - UPDATE base_tbl SET a=NEW.a WHERE a=OLD.a; - RETURN NEW; - ELSIF TG_OP = 'DELETE' THEN - DELETE FROM base_tbl WHERE a=OLD.a; - RETURN OLD; - END IF; -END; -$$ -LANGUAGE plpgsql; - -CREATE TRIGGER rw_view1_trig - INSTEAD OF INSERT OR UPDATE OR DELETE ON rw_view1 - FOR EACH ROW EXECUTE PROCEDURE rw_view1_trig_fn(); - -CREATE VIEW rw_view2 AS - SELECT * FROM rw_view1 WHERE a > 0 WITH LOCAL CHECK OPTION; - -INSERT INTO rw_view2 VALUES (-5); -- should fail -INSERT INTO rw_view2 VALUES (5); -- ok -INSERT INTO rw_view2 VALUES (50); -- ok, but not in view -UPDATE rw_view2 SET a = a - 10; -- should fail -SELECT * FROM base_tbl; - --- Check option won't cascade down to base view with INSTEAD OF triggers - -ALTER VIEW rw_view2 SET (check_option=cascaded); -INSERT INTO rw_view2 VALUES (100); -- ok, but not in view (doesn't fail rw_view1's check) -UPDATE rw_view2 SET a = 200 WHERE a = 5; -- ok, but not in view (doesn't fail rw_view1's check) -SELECT * FROM base_tbl; - --- Neither local nor cascaded check options work with INSTEAD rules - -DROP TRIGGER rw_view1_trig ON rw_view1; -CREATE RULE rw_view1_ins_rule AS ON INSERT TO rw_view1 - DO INSTEAD INSERT INTO base_tbl VALUES (NEW.a, 10); -CREATE RULE rw_view1_upd_rule AS ON UPDATE TO rw_view1 - DO INSTEAD UPDATE base_tbl SET a=NEW.a WHERE a=OLD.a; -INSERT INTO rw_view2 VALUES (-10); -- ok, but not in view (doesn't fail rw_view2's check) -INSERT INTO rw_view2 VALUES (5); -- ok -INSERT INTO rw_view2 VALUES (20); -- ok, but not in view (doesn't fail rw_view1's check) -UPDATE rw_view2 SET a = 30 WHERE a = 5; -- ok, but not in view (doesn't fail rw_view1's check) -INSERT INTO rw_view2 VALUES (5); -- ok -UPDATE rw_view2 SET a = -5 WHERE a = 5; -- ok, but not in view (doesn't fail rw_view2's check) -SELECT * FROM base_tbl; - -DROP TABLE base_tbl CASCADE; -DROP FUNCTION rw_view1_trig_fn(); - -CREATE TABLE base_tbl (a int); -CREATE VIEW rw_view1 AS SELECT a,10 AS b FROM base_tbl; -CREATE RULE rw_view1_ins_rule AS ON INSERT TO rw_view1 - DO INSTEAD INSERT INTO base_tbl VALUES (NEW.a); -CREATE VIEW rw_view2 AS - SELECT * FROM rw_view1 WHERE a > b WITH LOCAL CHECK OPTION; -INSERT INTO rw_view2 VALUES (2,3); -- ok, but not in view (doesn't fail rw_view2's check) -DROP TABLE base_tbl CASCADE; - --- security barrier view - -CREATE TABLE base_tbl (person text, visibility text); -INSERT INTO base_tbl VALUES ('Tom', 'public'), - ('Dick', 'private'), - ('Harry', 'public'); - -CREATE VIEW rw_view1 AS - SELECT person FROM base_tbl WHERE visibility = 'public'; - -CREATE FUNCTION snoop(anyelement) -RETURNS boolean AS -$$ -BEGIN - RAISE NOTICE 'snooped value: %', $1; - RETURN true; -END; -$$ -LANGUAGE plpgsql COST 0.000001; - -CREATE OR REPLACE FUNCTION leakproof(anyelement) -RETURNS boolean AS -$$ -BEGIN - RETURN true; -END; -$$ -LANGUAGE plpgsql STRICT IMMUTABLE LEAKPROOF; - -SELECT * FROM rw_view1 WHERE snoop(person); -UPDATE rw_view1 SET person=person WHERE snoop(person); -DELETE FROM rw_view1 WHERE NOT snoop(person); - -ALTER VIEW rw_view1 SET (security_barrier = true); - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name = 'rw_view1'; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name = 'rw_view1'; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name = 'rw_view1' - ORDER BY ordinal_position; - -SELECT * FROM rw_view1 WHERE snoop(person); -UPDATE rw_view1 SET person=person WHERE snoop(person); -DELETE FROM rw_view1 WHERE NOT snoop(person); - -EXPLAIN (costs off) SELECT * FROM rw_view1 WHERE snoop(person); -EXPLAIN (costs off) UPDATE rw_view1 SET person=person WHERE snoop(person); -EXPLAIN (costs off) DELETE FROM rw_view1 WHERE NOT snoop(person); - --- security barrier view on top of security barrier view - -CREATE VIEW rw_view2 WITH (security_barrier = true) AS - SELECT * FROM rw_view1 WHERE snoop(person); - -SELECT table_name, is_insertable_into - FROM information_schema.tables - WHERE table_name = 'rw_view2'; - -SELECT table_name, is_updatable, is_insertable_into - FROM information_schema.views - WHERE table_name = 'rw_view2'; - -SELECT table_name, column_name, is_updatable - FROM information_schema.columns - WHERE table_name = 'rw_view2' - ORDER BY ordinal_position; - -SELECT * FROM rw_view2 WHERE snoop(person); -UPDATE rw_view2 SET person=person WHERE snoop(person); -DELETE FROM rw_view2 WHERE NOT snoop(person); - -EXPLAIN (costs off) SELECT * FROM rw_view2 WHERE snoop(person); -EXPLAIN (costs off) UPDATE rw_view2 SET person=person WHERE snoop(person); -EXPLAIN (costs off) DELETE FROM rw_view2 WHERE NOT snoop(person); - -DROP TABLE base_tbl CASCADE; - --- security barrier view on top of table with rules - -CREATE TABLE base_tbl(id int PRIMARY KEY, data text, deleted boolean); -INSERT INTO base_tbl VALUES (1, 'Row 1', false), (2, 'Row 2', true); - -CREATE RULE base_tbl_ins_rule AS ON INSERT TO base_tbl - WHERE EXISTS (SELECT 1 FROM base_tbl t WHERE t.id = new.id) - DO INSTEAD - UPDATE base_tbl SET data = new.data, deleted = false WHERE id = new.id; - -CREATE RULE base_tbl_del_rule AS ON DELETE TO base_tbl - DO INSTEAD - UPDATE base_tbl SET deleted = true WHERE id = old.id; - -CREATE VIEW rw_view1 WITH (security_barrier=true) AS - SELECT id, data FROM base_tbl WHERE NOT deleted; - -SELECT * FROM rw_view1; - -EXPLAIN (costs off) DELETE FROM rw_view1 WHERE id = 1 AND snoop(data); -DELETE FROM rw_view1 WHERE id = 1 AND snoop(data); - -EXPLAIN (costs off) INSERT INTO rw_view1 VALUES (2, 'New row 2'); -INSERT INTO rw_view1 VALUES (2, 'New row 2'); - -SELECT * FROM base_tbl; - -DROP TABLE base_tbl CASCADE; - --- security barrier view based on inheritance set -CREATE TABLE t1 (a int, b float, c text); -CREATE INDEX t1_a_idx ON t1(a); -INSERT INTO t1 -SELECT i,i,'t1' FROM generate_series(1,10) g(i); -ANALYZE t1; - -CREATE TABLE t11 (d text) INHERITS (t1); -CREATE INDEX t11_a_idx ON t11(a); -INSERT INTO t11 -SELECT i,i,'t11','t11d' FROM generate_series(1,10) g(i); -ANALYZE t11; - -CREATE TABLE t12 (e int[]) INHERITS (t1); -CREATE INDEX t12_a_idx ON t12(a); -INSERT INTO t12 -SELECT i,i,'t12','{1,2}'::int[] FROM generate_series(1,10) g(i); -ANALYZE t12; - -CREATE TABLE t111 () INHERITS (t11, t12); -CREATE INDEX t111_a_idx ON t111(a); -INSERT INTO t111 -SELECT i,i,'t111','t111d','{1,1,1}'::int[] FROM generate_series(1,10) g(i); -ANALYZE t111; - -CREATE VIEW v1 WITH (security_barrier=true) AS -SELECT *, (SELECT d FROM t11 WHERE t11.a = t1.a LIMIT 1) AS d -FROM t1 -WHERE a > 5 AND EXISTS(SELECT 1 FROM t12 WHERE t12.a = t1.a); - -SELECT * FROM v1 WHERE a=3; -- should not see anything -SELECT * FROM v1 WHERE a=8; - -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE v1 SET a=100 WHERE snoop(a) AND leakproof(a) AND a < 7 AND a != 6; -UPDATE v1 SET a=100 WHERE snoop(a) AND leakproof(a) AND a < 7 AND a != 6; - -SELECT * FROM v1 WHERE a=100; -- Nothing should have been changed to 100 -SELECT * FROM t1 WHERE a=100; -- Nothing should have been changed to 100 - -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE v1 SET a=a+1 WHERE snoop(a) AND leakproof(a) AND a = 8; -UPDATE v1 SET a=a+1 WHERE snoop(a) AND leakproof(a) AND a = 8; - -SELECT * FROM v1 WHERE b=8; - -DELETE FROM v1 WHERE snoop(a) AND leakproof(a); -- should not delete everything, just where a>5 - -TABLE t1; -- verify all a<=5 are intact - -DROP TABLE t1, t11, t12, t111 CASCADE; -DROP FUNCTION snoop(anyelement); -DROP FUNCTION leakproof(anyelement); - -CREATE TABLE tx1 (a integer); -CREATE TABLE tx2 (b integer); -CREATE TABLE tx3 (c integer); -CREATE VIEW vx1 AS SELECT a FROM tx1 WHERE EXISTS(SELECT 1 FROM tx2 JOIN tx3 ON b=c); -INSERT INTO vx1 values (1); -SELECT * FROM tx1; -SELECT * FROM vx1; - -DROP VIEW vx1; -DROP TABLE tx1; -DROP TABLE tx2; -DROP TABLE tx3; - -CREATE TABLE tx1 (a integer); -CREATE TABLE tx2 (b integer); -CREATE TABLE tx3 (c integer); -CREATE VIEW vx1 AS SELECT a FROM tx1 WHERE EXISTS(SELECT 1 FROM tx2 JOIN tx3 ON b=c); -INSERT INTO vx1 VALUES (1); -INSERT INTO vx1 VALUES (1); -SELECT * FROM tx1; -SELECT * FROM vx1; - -DROP VIEW vx1; -DROP TABLE tx1; -DROP TABLE tx2; -DROP TABLE tx3; - -CREATE TABLE tx1 (a integer, b integer); -CREATE TABLE tx2 (b integer, c integer); -CREATE TABLE tx3 (c integer, d integer); -ALTER TABLE tx1 DROP COLUMN b; -ALTER TABLE tx2 DROP COLUMN c; -ALTER TABLE tx3 DROP COLUMN d; -CREATE VIEW vx1 AS SELECT a FROM tx1 WHERE EXISTS(SELECT 1 FROM tx2 JOIN tx3 ON b=c); -INSERT INTO vx1 VALUES (1); -INSERT INTO vx1 VALUES (1); -SELECT * FROM tx1; -SELECT * FROM vx1; - -DROP VIEW vx1; -DROP TABLE tx1; -DROP TABLE tx2; -DROP TABLE tx3; - --- --- Test handling of vars from correlated subqueries in quals from outer --- security barrier views, per bug #13988 --- -CREATE TABLE t1 (a int, b text, c int); -INSERT INTO t1 VALUES (1, 'one', 10); - -CREATE TABLE t2 (cc int); -INSERT INTO t2 VALUES (10), (20); - -CREATE VIEW v1 WITH (security_barrier = true) AS - SELECT * FROM t1 WHERE (a > 0) - WITH CHECK OPTION; - -CREATE VIEW v2 WITH (security_barrier = true) AS - SELECT * FROM v1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t2.cc = v1.c) - WITH CHECK OPTION; - -INSERT INTO v2 VALUES (2, 'two', 20); -- ok -INSERT INTO v2 VALUES (-2, 'minus two', 20); -- not allowed -INSERT INTO v2 VALUES (3, 'three', 30); -- not allowed - -UPDATE v2 SET b = 'ONE' WHERE a = 1; -- ok -UPDATE v2 SET a = -1 WHERE a = 1; -- not allowed -UPDATE v2 SET c = 30 WHERE a = 1; -- not allowed - -DELETE FROM v2 WHERE a = 2; -- ok -SELECT * FROM v2; - -DROP VIEW v2; -DROP VIEW v1; -DROP TABLE t2; -DROP TABLE t1; - --- --- Test CREATE OR REPLACE VIEW turning a non-updatable view into an --- auto-updatable view and adding check options in a single step --- -CREATE TABLE t1 (a int, b text); -CREATE VIEW v1 AS SELECT null::int AS a; -CREATE OR REPLACE VIEW v1 AS SELECT * FROM t1 WHERE a > 0 WITH CHECK OPTION; - -INSERT INTO v1 VALUES (1, 'ok'); -- ok -INSERT INTO v1 VALUES (-1, 'invalid'); -- should fail - -DROP VIEW v1; -DROP TABLE t1; - --- check that an auto-updatable view on a partitioned table works correctly -create table uv_pt (a int, b int, v varchar) partition by range (a, b); -create table uv_pt1 (b int not null, v varchar, a int not null) partition by range (b); -create table uv_pt11 (like uv_pt1); -alter table uv_pt11 drop a; -alter table uv_pt11 add a int; -alter table uv_pt11 drop a; -alter table uv_pt11 add a int not null; -alter table uv_pt1 attach partition uv_pt11 for values from (2) to (5); -alter table uv_pt attach partition uv_pt1 for values from (1, 2) to (1, 10); - -create view uv_ptv as select * from uv_pt; -select events & 4 != 0 AS upd, - events & 8 != 0 AS ins, - events & 16 != 0 AS del - from pg_catalog.pg_relation_is_updatable('uv_pt'::regclass, false) t(events); -select pg_catalog.pg_column_is_updatable('uv_pt'::regclass, 1::smallint, false); -select pg_catalog.pg_column_is_updatable('uv_pt'::regclass, 2::smallint, false); -select table_name, is_updatable, is_insertable_into - from information_schema.views where table_name = 'uv_ptv'; -select table_name, column_name, is_updatable - from information_schema.columns where table_name = 'uv_ptv' order by column_name; -insert into uv_ptv values (1, 2); -select tableoid::regclass, * from uv_pt; -create view uv_ptv_wco as select * from uv_pt where a = 0 with check option; -insert into uv_ptv_wco values (1, 2); -drop view uv_ptv, uv_ptv_wco; -drop table uv_pt, uv_pt1, uv_pt11; - --- check that wholerow vars appearing in WITH CHECK OPTION constraint expressions --- work fine with partitioned tables -create table wcowrtest (a int) partition by list (a); -create table wcowrtest1 partition of wcowrtest for values in (1); -create view wcowrtest_v as select * from wcowrtest where wcowrtest = '(2)'::wcowrtest with check option; -insert into wcowrtest_v values (1); - -alter table wcowrtest add b text; -create table wcowrtest2 (b text, c int, a int); -alter table wcowrtest2 drop c; -alter table wcowrtest attach partition wcowrtest2 for values in (2); - -create table sometable (a int, b text); -insert into sometable values (1, 'a'), (2, 'b'); -create view wcowrtest_v2 as - select * - from wcowrtest r - where r in (select s from sometable s where r.a = s.a) -with check option; - --- WITH CHECK qual will be processed with wcowrtest2's --- rowtype after tuple-routing -insert into wcowrtest_v2 values (2, 'no such row in sometable'); - -drop view wcowrtest_v, wcowrtest_v2; -drop table wcowrtest, sometable; - --- Check INSERT .. ON CONFLICT DO UPDATE works correctly when the view's --- columns are named and ordered differently than the underlying table's. -create table uv_iocu_tab (a text unique, b float); -insert into uv_iocu_tab values ('xyxyxy', 0); -create view uv_iocu_view as - select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; - -insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; -select * from uv_iocu_tab; -insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; -select * from uv_iocu_tab; - --- OK to access view columns that are not present in underlying base --- relation in the ON CONFLICT portion of the query -insert into uv_iocu_view (a, b) values ('xyxyxy', 3) - on conflict (a) do update set b = cast(excluded.two as float); -select * from uv_iocu_tab; - -explain (costs off) -insert into uv_iocu_view (a, b) values ('xyxyxy', 3) - on conflict (a) do update set b = excluded.b where excluded.c > 0; - -insert into uv_iocu_view (a, b) values ('xyxyxy', 3) - on conflict (a) do update set b = excluded.b where excluded.c > 0; -select * from uv_iocu_tab; - -drop view uv_iocu_view; -drop table uv_iocu_tab; - --- Test whole-row references to the view -create table uv_iocu_tab (a int unique, b text); -create view uv_iocu_view as - select b as bb, a as aa, uv_iocu_tab::text as cc from uv_iocu_tab; - -insert into uv_iocu_view (aa,bb) values (1,'x'); -explain (costs off) -insert into uv_iocu_view (aa,bb) values (1,'y') - on conflict (aa) do update set bb = 'Rejected: '||excluded.* - where excluded.aa > 0 - and excluded.bb != '' - and excluded.cc is not null; -insert into uv_iocu_view (aa,bb) values (1,'y') - on conflict (aa) do update set bb = 'Rejected: '||excluded.* - where excluded.aa > 0 - and excluded.bb != '' - and excluded.cc is not null; -select * from uv_iocu_view; - --- Test omitting a column of the base relation -delete from uv_iocu_view; -insert into uv_iocu_view (aa,bb) values (1,'x'); -insert into uv_iocu_view (aa) values (1) - on conflict (aa) do update set bb = 'Rejected: '||excluded.*; -select * from uv_iocu_view; - -alter table uv_iocu_tab alter column b set default 'table default'; -insert into uv_iocu_view (aa) values (1) - on conflict (aa) do update set bb = 'Rejected: '||excluded.*; -select * from uv_iocu_view; - -alter view uv_iocu_view alter column bb set default 'view default'; -insert into uv_iocu_view (aa) values (1) - on conflict (aa) do update set bb = 'Rejected: '||excluded.*; -select * from uv_iocu_view; - --- Should fail to update non-updatable columns -insert into uv_iocu_view (aa) values (1) - on conflict (aa) do update set cc = 'XXX'; - -drop view uv_iocu_view; -drop table uv_iocu_tab; - --- ON CONFLICT DO UPDATE permissions checks -create user regress_view_user1; -create user regress_view_user2; - -set session authorization regress_view_user1; -create table base_tbl(a int unique, b text, c float); -insert into base_tbl values (1,'xxx',1.0); -create view rw_view1 as select b as bb, c as cc, a as aa from base_tbl; - -grant select (aa,bb) on rw_view1 to regress_view_user2; -grant insert on rw_view1 to regress_view_user2; -grant update (bb) on rw_view1 to regress_view_user2; - -set session authorization regress_view_user2; -insert into rw_view1 values ('yyy',2.0,1) - on conflict (aa) do update set bb = excluded.cc; -- Not allowed -insert into rw_view1 values ('yyy',2.0,1) - on conflict (aa) do update set bb = rw_view1.cc; -- Not allowed -insert into rw_view1 values ('yyy',2.0,1) - on conflict (aa) do update set bb = excluded.bb; -- OK -insert into rw_view1 values ('zzz',2.0,1) - on conflict (aa) do update set bb = rw_view1.bb||'xxx'; -- OK -insert into rw_view1 values ('zzz',2.0,1) - on conflict (aa) do update set cc = 3.0; -- Not allowed -reset session authorization; -select * from base_tbl; - -set session authorization regress_view_user1; -grant select (a,b) on base_tbl to regress_view_user2; -grant insert (a,b) on base_tbl to regress_view_user2; -grant update (a,b) on base_tbl to regress_view_user2; - -set session authorization regress_view_user2; -create view rw_view2 as select b as bb, c as cc, a as aa from base_tbl; -insert into rw_view2 (aa,bb) values (1,'xxx') - on conflict (aa) do update set bb = excluded.bb; -- Not allowed -create view rw_view3 as select b as bb, a as aa from base_tbl; -insert into rw_view3 (aa,bb) values (1,'xxx') - on conflict (aa) do update set bb = excluded.bb; -- OK -reset session authorization; -select * from base_tbl; - -set session authorization regress_view_user2; -create view rw_view4 as select aa, bb, cc FROM rw_view1; -insert into rw_view4 (aa,bb) values (1,'yyy') - on conflict (aa) do update set bb = excluded.bb; -- Not allowed -create view rw_view5 as select aa, bb FROM rw_view1; -insert into rw_view5 (aa,bb) values (1,'yyy') - on conflict (aa) do update set bb = excluded.bb; -- OK -reset session authorization; -select * from base_tbl; - -drop view rw_view5; -drop view rw_view4; -drop view rw_view3; -drop view rw_view2; -drop view rw_view1; -drop table base_tbl; -drop user regress_view_user1; -drop user regress_view_user2; - --- Test single- and multi-row inserts with table and view defaults. --- Table defaults should be used, unless overridden by view defaults. -create table base_tab_def (a int, b text default 'Table default', - c text default 'Table default', d text, e text); -create view base_tab_def_view as select * from base_tab_def; -alter view base_tab_def_view alter b set default 'View default'; -alter view base_tab_def_view alter d set default 'View default'; -insert into base_tab_def values (1); -insert into base_tab_def values (2), (3); -insert into base_tab_def values (4, default, default, default, default); -insert into base_tab_def values (5, default, default, default, default), - (6, default, default, default, default); -insert into base_tab_def_view values (11); -insert into base_tab_def_view values (12), (13); -insert into base_tab_def_view values (14, default, default, default, default); -insert into base_tab_def_view values (15, default, default, default, default), - (16, default, default, default, default); -insert into base_tab_def_view values (17), (default); -select * from base_tab_def order by a; - --- Adding an INSTEAD OF trigger should cause NULLs to be inserted instead of --- table defaults, where there are no view defaults. -create function base_tab_def_view_instrig_func() returns trigger -as -$$ -begin - insert into base_tab_def values (new.a, new.b, new.c, new.d, new.e); - return new; -end; -$$ -language plpgsql; -create trigger base_tab_def_view_instrig instead of insert on base_tab_def_view - for each row execute function base_tab_def_view_instrig_func(); -truncate base_tab_def; -insert into base_tab_def values (1); -insert into base_tab_def values (2), (3); -insert into base_tab_def values (4, default, default, default, default); -insert into base_tab_def values (5, default, default, default, default), - (6, default, default, default, default); -insert into base_tab_def_view values (11); -insert into base_tab_def_view values (12), (13); -insert into base_tab_def_view values (14, default, default, default, default); -insert into base_tab_def_view values (15, default, default, default, default), - (16, default, default, default, default); -insert into base_tab_def_view values (17), (default); -select * from base_tab_def order by a; - --- Using an unconditional DO INSTEAD rule should also cause NULLs to be --- inserted where there are no view defaults. -drop trigger base_tab_def_view_instrig on base_tab_def_view; -drop function base_tab_def_view_instrig_func; -create rule base_tab_def_view_ins_rule as on insert to base_tab_def_view - do instead insert into base_tab_def values (new.a, new.b, new.c, new.d, new.e); -truncate base_tab_def; -insert into base_tab_def values (1); -insert into base_tab_def values (2), (3); -insert into base_tab_def values (4, default, default, default, default); -insert into base_tab_def values (5, default, default, default, default), - (6, default, default, default, default); -insert into base_tab_def_view values (11); -insert into base_tab_def_view values (12), (13); -insert into base_tab_def_view values (14, default, default, default, default); -insert into base_tab_def_view values (15, default, default, default, default), - (16, default, default, default, default); -insert into base_tab_def_view values (17), (default); -select * from base_tab_def order by a; - --- A DO ALSO rule should cause each row to be inserted twice. The first --- insert should behave the same as an auto-updatable view (using table --- defaults, unless overridden by view defaults). The second insert should --- behave the same as a rule-updatable view (inserting NULLs where there are --- no view defaults). -drop rule base_tab_def_view_ins_rule on base_tab_def_view; -create rule base_tab_def_view_ins_rule as on insert to base_tab_def_view - do also insert into base_tab_def values (new.a, new.b, new.c, new.d, new.e); -truncate base_tab_def; -insert into base_tab_def values (1); -insert into base_tab_def values (2), (3); -insert into base_tab_def values (4, default, default, default, default); -insert into base_tab_def values (5, default, default, default, default), - (6, default, default, default, default); -insert into base_tab_def_view values (11); -insert into base_tab_def_view values (12), (13); -insert into base_tab_def_view values (14, default, default, default, default); -insert into base_tab_def_view values (15, default, default, default, default), - (16, default, default, default, default); -insert into base_tab_def_view values (17), (default); -select * from base_tab_def order by a, c NULLS LAST; - -drop view base_tab_def_view; -drop table base_tab_def; - --- Test defaults with array assignments -create table base_tab (a serial, b int[], c text, d text default 'Table default'); -create view base_tab_view as select c, a, b from base_tab; -alter view base_tab_view alter column c set default 'View default'; -insert into base_tab_view (b[1], b[2], c, b[5], b[4], a, b[3]) -values (1, 2, default, 5, 4, default, 3), (10, 11, 'C value', 14, 13, 100, 12); -select * from base_tab order by a; -drop view base_tab_view; -drop table base_tab; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fupdate.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fupdate.sql deleted file mode 100644 index 7a7bee77b9..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fupdate.sql +++ /dev/null @@ -1,669 +0,0 @@ --- --- UPDATE syntax tests --- - -CREATE TABLE update_test ( - a INT DEFAULT 10, - b INT, - c TEXT -); - -CREATE TABLE upsert_test ( - a INT PRIMARY KEY, - b TEXT -); - -INSERT INTO update_test VALUES (5, 10, 'foo'); -INSERT INTO update_test(b, a) VALUES (15, 10); - -SELECT * FROM update_test; - -UPDATE update_test SET a = DEFAULT, b = DEFAULT; - -SELECT * FROM update_test; - --- aliases for the UPDATE target table -UPDATE update_test AS t SET b = 10 WHERE t.a = 10; - -SELECT * FROM update_test; - -UPDATE update_test t SET b = t.b + 10 WHERE t.a = 10; - -SELECT * FROM update_test; - --- --- Test VALUES in FROM --- - -UPDATE update_test SET a=v.i FROM (VALUES(100, 20)) AS v(i, j) - WHERE update_test.b = v.j; - -SELECT * FROM update_test; - --- fail, wrong data type: -UPDATE update_test SET a = v.* FROM (VALUES(100, 20)) AS v(i, j) - WHERE update_test.b = v.j; - --- --- Test multiple-set-clause syntax --- - -INSERT INTO update_test SELECT a,b+1,c FROM update_test; -SELECT * FROM update_test; - -UPDATE update_test SET (c,b,a) = ('bugle', b+11, DEFAULT) WHERE c = 'foo'; -SELECT * FROM update_test; -UPDATE update_test SET (c,b) = ('car', a+b), a = a + 1 WHERE a = 10; -SELECT * FROM update_test; --- fail, multi assignment to same column: -UPDATE update_test SET (c,b) = ('car', a+b), b = a + 1 WHERE a = 10; - --- uncorrelated sub-select: -UPDATE update_test - SET (b,a) = (select a,b from update_test where b = 41 and c = 'car') - WHERE a = 100 AND b = 20; -SELECT * FROM update_test; --- correlated sub-select: -UPDATE update_test o - SET (b,a) = (select a+1,b from update_test i - where i.a=o.a and i.b=o.b and i.c is not distinct from o.c); -SELECT * FROM update_test; --- fail, multiple rows supplied: -UPDATE update_test SET (b,a) = (select a+1,b from update_test); --- set to null if no rows supplied: -UPDATE update_test SET (b,a) = (select a+1,b from update_test where a = 1000) - WHERE a = 11; -SELECT * FROM update_test; --- *-expansion should work in this context: -UPDATE update_test SET (a,b) = ROW(v.*) FROM (VALUES(21, 100)) AS v(i, j) - WHERE update_test.a = v.i; --- you might expect this to work, but syntactically it's not a RowExpr: -UPDATE update_test SET (a,b) = (v.*) FROM (VALUES(21, 101)) AS v(i, j) - WHERE update_test.a = v.i; - --- if an alias for the target table is specified, don't allow references --- to the original table name -UPDATE update_test AS t SET b = update_test.b + 10 WHERE t.a = 10; - --- Make sure that we can update to a TOASTed value. -UPDATE update_test SET c = repeat('x', 10000) WHERE c = 'car'; -SELECT a, b, char_length(c) FROM update_test; - --- Check multi-assignment with a Result node to handle a one-time filter. -EXPLAIN (VERBOSE, COSTS OFF) -UPDATE update_test t - SET (a, b) = (SELECT b, a FROM update_test s WHERE s.a = t.a) - WHERE CURRENT_USER = SESSION_USER; -UPDATE update_test t - SET (a, b) = (SELECT b, a FROM update_test s WHERE s.a = t.a) - WHERE CURRENT_USER = SESSION_USER; -SELECT a, b, char_length(c) FROM update_test; - --- Test ON CONFLICT DO UPDATE - -INSERT INTO upsert_test VALUES(1, 'Boo'), (3, 'Zoo'); --- uncorrelated sub-select: -WITH aaa AS (SELECT 1 AS a, 'Foo' AS b) INSERT INTO upsert_test - VALUES (1, 'Bar') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT b, a FROM aaa) RETURNING *; --- correlated sub-select: -INSERT INTO upsert_test VALUES (1, 'Baz'), (3, 'Zaz') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT b || ', Correlated', a from upsert_test i WHERE i.a = upsert_test.a) - RETURNING *; --- correlated sub-select (EXCLUDED.* alias): -INSERT INTO upsert_test VALUES (1, 'Bat'), (3, 'Zot') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT b || ', Excluded', a from upsert_test i WHERE i.a = excluded.a) - RETURNING *; - --- ON CONFLICT using system attributes in RETURNING, testing both the --- inserting and updating paths. See bug report at: --- https://www.postgresql.org/message-id/73436355-6432-49B1-92ED-1FE4F7E7E100%40finefun.com.au -INSERT INTO upsert_test VALUES (2, 'Beeble') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT b || ', Excluded', a from upsert_test i WHERE i.a = excluded.a) - RETURNING tableoid::regclass, xmin = pg_current_xact_id()::xid AS xmin_correct, xmax = 0 AS xmax_correct; --- currently xmax is set after a conflict - that's probably not good, --- but it seems worthwhile to have to be explicit if that changes. -INSERT INTO upsert_test VALUES (2, 'Brox') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT b || ', Excluded', a from upsert_test i WHERE i.a = excluded.a) - RETURNING tableoid::regclass, xmin = pg_current_xact_id()::xid AS xmin_correct, xmax = pg_current_xact_id()::xid AS xmax_correct; - -DROP TABLE update_test; -DROP TABLE upsert_test; - --- Test ON CONFLICT DO UPDATE with partitioned table and non-identical children - -CREATE TABLE upsert_test ( - a INT PRIMARY KEY, - b TEXT -) PARTITION BY LIST (a); - -CREATE TABLE upsert_test_1 PARTITION OF upsert_test FOR VALUES IN (1); -CREATE TABLE upsert_test_2 (b TEXT, a INT PRIMARY KEY); -ALTER TABLE upsert_test ATTACH PARTITION upsert_test_2 FOR VALUES IN (2); - -INSERT INTO upsert_test VALUES(1, 'Boo'), (2, 'Zoo'); --- uncorrelated sub-select: -WITH aaa AS (SELECT 1 AS a, 'Foo' AS b) INSERT INTO upsert_test - VALUES (1, 'Bar') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT b, a FROM aaa) RETURNING *; --- correlated sub-select: -WITH aaa AS (SELECT 1 AS ctea, ' Foo' AS cteb) INSERT INTO upsert_test - VALUES (1, 'Bar'), (2, 'Baz') ON CONFLICT(a) - DO UPDATE SET (b, a) = (SELECT upsert_test.b||cteb, upsert_test.a FROM aaa) RETURNING *; - -DROP TABLE upsert_test; - - ---------------------------- --- UPDATE with row movement ---------------------------- - --- When a partitioned table receives an UPDATE to the partitioned key and the --- new values no longer meet the partition's bound, the row must be moved to --- the correct partition for the new partition key (if one exists). We must --- also ensure that updatable views on partitioned tables properly enforce any --- WITH CHECK OPTION that is defined. The situation with triggers in this case --- also requires thorough testing as partition key updates causing row --- movement convert UPDATEs into DELETE+INSERT. - -CREATE TABLE range_parted ( - a text, - b bigint, - c numeric, - d int, - e varchar -) PARTITION BY RANGE (a, b); - --- Create partitions intentionally in descending bound order, so as to test --- that update-row-movement works with the leaf partitions not in bound order. -CREATE TABLE part_b_20_b_30 (e varchar, c numeric, a text, b bigint, d int); -ALTER TABLE range_parted ATTACH PARTITION part_b_20_b_30 FOR VALUES FROM ('b', 20) TO ('b', 30); -CREATE TABLE part_b_10_b_20 (e varchar, c numeric, a text, b bigint, d int) PARTITION BY RANGE (c); -CREATE TABLE part_b_1_b_10 PARTITION OF range_parted FOR VALUES FROM ('b', 1) TO ('b', 10); -ALTER TABLE range_parted ATTACH PARTITION part_b_10_b_20 FOR VALUES FROM ('b', 10) TO ('b', 20); -CREATE TABLE part_a_10_a_20 PARTITION OF range_parted FOR VALUES FROM ('a', 10) TO ('a', 20); -CREATE TABLE part_a_1_a_10 PARTITION OF range_parted FOR VALUES FROM ('a', 1) TO ('a', 10); - --- Check that partition-key UPDATE works sanely on a partitioned table that --- does not have any child partitions. -UPDATE part_b_10_b_20 set b = b - 6; - --- Create some more partitions following the above pattern of descending bound --- order, but let's make the situation a bit more complex by having the --- attribute numbers of the columns vary from their parent partition. -CREATE TABLE part_c_100_200 (e varchar, c numeric, a text, b bigint, d int) PARTITION BY range (abs(d)); -ALTER TABLE part_c_100_200 DROP COLUMN e, DROP COLUMN c, DROP COLUMN a; -ALTER TABLE part_c_100_200 ADD COLUMN c numeric, ADD COLUMN e varchar, ADD COLUMN a text; -ALTER TABLE part_c_100_200 DROP COLUMN b; -ALTER TABLE part_c_100_200 ADD COLUMN b bigint; -CREATE TABLE part_d_1_15 PARTITION OF part_c_100_200 FOR VALUES FROM (1) TO (15); -CREATE TABLE part_d_15_20 PARTITION OF part_c_100_200 FOR VALUES FROM (15) TO (20); - -ALTER TABLE part_b_10_b_20 ATTACH PARTITION part_c_100_200 FOR VALUES FROM (100) TO (200); - -CREATE TABLE part_c_1_100 (e varchar, d int, c numeric, b bigint, a text); -ALTER TABLE part_b_10_b_20 ATTACH PARTITION part_c_1_100 FOR VALUES FROM (1) TO (100); - -\set init_range_parted 'truncate range_parted; insert into range_parted VALUES (''a'', 1, 1, 1), (''a'', 10, 200, 1), (''b'', 12, 96, 1), (''b'', 13, 97, 2), (''b'', 15, 105, 16), (''b'', 17, 105, 19)' -\set show_data 'select tableoid::regclass::text COLLATE "C" partname, * from range_parted ORDER BY 1, 2, 3, 4, 5, 6' -:init_range_parted; -:show_data; - --- The order of subplans should be in bound order -EXPLAIN (costs off) UPDATE range_parted set c = c - 50 WHERE c > 97; - --- fail, row movement happens only within the partition subtree. -UPDATE part_c_100_200 set c = c - 20, d = c WHERE c = 105; --- fail, no partition key update, so no attempt to move tuple, --- but "a = 'a'" violates partition constraint enforced by root partition) -UPDATE part_b_10_b_20 set a = 'a'; --- ok, partition key update, no constraint violation -UPDATE range_parted set d = d - 10 WHERE d > 10; --- ok, no partition key update, no constraint violation -UPDATE range_parted set e = d; --- No row found -UPDATE part_c_1_100 set c = c + 20 WHERE c = 98; --- ok, row movement -UPDATE part_b_10_b_20 set c = c + 20 returning c, b, a; -:show_data; - --- fail, row movement happens only within the partition subtree. -UPDATE part_b_10_b_20 set b = b - 6 WHERE c > 116 returning *; --- ok, row movement, with subset of rows moved into different partition. -UPDATE range_parted set b = b - 6 WHERE c > 116 returning a, b + c; - -:show_data; - --- Common table needed for multiple test scenarios. -CREATE TABLE mintab(c1 int); -INSERT into mintab VALUES (120); - --- update partition key using updatable view. -CREATE VIEW upview AS SELECT * FROM range_parted WHERE (select c > c1 FROM mintab) WITH CHECK OPTION; --- ok -UPDATE upview set c = 199 WHERE b = 4; --- fail, check option violation -UPDATE upview set c = 120 WHERE b = 4; --- fail, row movement with check option violation -UPDATE upview set a = 'b', b = 15, c = 120 WHERE b = 4; --- ok, row movement, check option passes -UPDATE upview set a = 'b', b = 15 WHERE b = 4; - -:show_data; - --- cleanup -DROP VIEW upview; - --- RETURNING having whole-row vars. -:init_range_parted; -UPDATE range_parted set c = 95 WHERE a = 'b' and b > 10 and c > 100 returning (range_parted), *; -:show_data; - - --- Transition tables with update row movement -:init_range_parted; - -CREATE FUNCTION trans_updatetrigfunc() RETURNS trigger LANGUAGE plpgsql AS -$$ - begin - raise notice 'trigger = %, old table = %, new table = %', - TG_NAME, - (select string_agg(old_table::text, ', ' ORDER BY a) FROM old_table), - (select string_agg(new_table::text, ', ' ORDER BY a) FROM new_table); - return null; - end; -$$; - -CREATE TRIGGER trans_updatetrig - AFTER UPDATE ON range_parted REFERENCING OLD TABLE AS old_table NEW TABLE AS new_table - FOR EACH STATEMENT EXECUTE PROCEDURE trans_updatetrigfunc(); - -UPDATE range_parted set c = (case when c = 96 then 110 else c + 1 end ) WHERE a = 'b' and b > 10 and c >= 96; -:show_data; -:init_range_parted; - --- Enabling OLD TABLE capture for both DELETE as well as UPDATE stmt triggers --- should not cause DELETEd rows to be captured twice. Similar thing for --- INSERT triggers and inserted rows. -CREATE TRIGGER trans_deletetrig - AFTER DELETE ON range_parted REFERENCING OLD TABLE AS old_table - FOR EACH STATEMENT EXECUTE PROCEDURE trans_updatetrigfunc(); -CREATE TRIGGER trans_inserttrig - AFTER INSERT ON range_parted REFERENCING NEW TABLE AS new_table - FOR EACH STATEMENT EXECUTE PROCEDURE trans_updatetrigfunc(); -UPDATE range_parted set c = c + 50 WHERE a = 'b' and b > 10 and c >= 96; -:show_data; -DROP TRIGGER trans_deletetrig ON range_parted; -DROP TRIGGER trans_inserttrig ON range_parted; --- Don't drop trans_updatetrig yet. It is required below. - --- Test with transition tuple conversion happening for rows moved into the --- new partition. This requires a trigger that references transition table --- (we already have trans_updatetrig). For inserted rows, the conversion --- is not usually needed, because the original tuple is already compatible with --- the desired transition tuple format. But conversion happens when there is a --- BR trigger because the trigger can change the inserted row. So install a --- BR triggers on those child partitions where the rows will be moved. -CREATE FUNCTION func_parted_mod_b() RETURNS trigger AS $$ -BEGIN - NEW.b = NEW.b + 1; - return NEW; -END $$ language plpgsql; -CREATE TRIGGER trig_c1_100 BEFORE UPDATE OR INSERT ON part_c_1_100 - FOR EACH ROW EXECUTE PROCEDURE func_parted_mod_b(); -CREATE TRIGGER trig_d1_15 BEFORE UPDATE OR INSERT ON part_d_1_15 - FOR EACH ROW EXECUTE PROCEDURE func_parted_mod_b(); -CREATE TRIGGER trig_d15_20 BEFORE UPDATE OR INSERT ON part_d_15_20 - FOR EACH ROW EXECUTE PROCEDURE func_parted_mod_b(); -:init_range_parted; -UPDATE range_parted set c = (case when c = 96 then 110 else c + 1 end) WHERE a = 'b' and b > 10 and c >= 96; -:show_data; -:init_range_parted; -UPDATE range_parted set c = c + 50 WHERE a = 'b' and b > 10 and c >= 96; -:show_data; - --- Case where per-partition tuple conversion map array is allocated, but the --- map is not required for the particular tuple that is routed, thanks to --- matching table attributes of the partition and the target table. -:init_range_parted; -UPDATE range_parted set b = 15 WHERE b = 1; -:show_data; - -DROP TRIGGER trans_updatetrig ON range_parted; -DROP TRIGGER trig_c1_100 ON part_c_1_100; -DROP TRIGGER trig_d1_15 ON part_d_1_15; -DROP TRIGGER trig_d15_20 ON part_d_15_20; -DROP FUNCTION func_parted_mod_b(); - --- RLS policies with update-row-movement ------------------------------------------ - -ALTER TABLE range_parted ENABLE ROW LEVEL SECURITY; -CREATE USER regress_range_parted_user; -GRANT ALL ON range_parted, mintab TO regress_range_parted_user; -CREATE POLICY seeall ON range_parted AS PERMISSIVE FOR SELECT USING (true); -CREATE POLICY policy_range_parted ON range_parted for UPDATE USING (true) WITH CHECK (c % 2 = 0); - -:init_range_parted; -SET SESSION AUTHORIZATION regress_range_parted_user; --- This should fail with RLS violation error while moving row from --- part_a_10_a_20 to part_d_1_15, because we are setting 'c' to an odd number. -UPDATE range_parted set a = 'b', c = 151 WHERE a = 'a' and c = 200; - -RESET SESSION AUTHORIZATION; --- Create a trigger on part_d_1_15 -CREATE FUNCTION func_d_1_15() RETURNS trigger AS $$ -BEGIN - NEW.c = NEW.c + 1; -- Make even numbers odd, or vice versa - return NEW; -END $$ LANGUAGE plpgsql; -CREATE TRIGGER trig_d_1_15 BEFORE INSERT ON part_d_1_15 - FOR EACH ROW EXECUTE PROCEDURE func_d_1_15(); - -:init_range_parted; -SET SESSION AUTHORIZATION regress_range_parted_user; - --- Here, RLS checks should succeed while moving row from part_a_10_a_20 to --- part_d_1_15. Even though the UPDATE is setting 'c' to an odd number, the --- trigger at the destination partition again makes it an even number. -UPDATE range_parted set a = 'b', c = 151 WHERE a = 'a' and c = 200; - -RESET SESSION AUTHORIZATION; -:init_range_parted; -SET SESSION AUTHORIZATION regress_range_parted_user; --- This should fail with RLS violation error. Even though the UPDATE is setting --- 'c' to an even number, the trigger at the destination partition again makes --- it an odd number. -UPDATE range_parted set a = 'b', c = 150 WHERE a = 'a' and c = 200; - --- Cleanup -RESET SESSION AUTHORIZATION; -DROP TRIGGER trig_d_1_15 ON part_d_1_15; -DROP FUNCTION func_d_1_15(); - --- Policy expression contains SubPlan -RESET SESSION AUTHORIZATION; -:init_range_parted; -CREATE POLICY policy_range_parted_subplan on range_parted - AS RESTRICTIVE for UPDATE USING (true) - WITH CHECK ((SELECT range_parted.c <= c1 FROM mintab)); -SET SESSION AUTHORIZATION regress_range_parted_user; --- fail, mintab has row with c1 = 120 -UPDATE range_parted set a = 'b', c = 122 WHERE a = 'a' and c = 200; --- ok -UPDATE range_parted set a = 'b', c = 120 WHERE a = 'a' and c = 200; - --- RLS policy expression contains whole row. - -RESET SESSION AUTHORIZATION; -:init_range_parted; -CREATE POLICY policy_range_parted_wholerow on range_parted AS RESTRICTIVE for UPDATE USING (true) - WITH CHECK (range_parted = row('b', 10, 112, 1, NULL)::range_parted); -SET SESSION AUTHORIZATION regress_range_parted_user; --- ok, should pass the RLS check -UPDATE range_parted set a = 'b', c = 112 WHERE a = 'a' and c = 200; -RESET SESSION AUTHORIZATION; -:init_range_parted; -SET SESSION AUTHORIZATION regress_range_parted_user; --- fail, the whole row RLS check should fail -UPDATE range_parted set a = 'b', c = 116 WHERE a = 'a' and c = 200; - --- Cleanup -RESET SESSION AUTHORIZATION; -DROP POLICY policy_range_parted ON range_parted; -DROP POLICY policy_range_parted_subplan ON range_parted; -DROP POLICY policy_range_parted_wholerow ON range_parted; -REVOKE ALL ON range_parted, mintab FROM regress_range_parted_user; -DROP USER regress_range_parted_user; -DROP TABLE mintab; - - --- statement triggers with update row movement ---------------------------------------------------- - -:init_range_parted; - -CREATE FUNCTION trigfunc() returns trigger language plpgsql as -$$ - begin - raise notice 'trigger = % fired on table % during %', - TG_NAME, TG_TABLE_NAME, TG_OP; - return null; - end; -$$; --- Triggers on root partition -CREATE TRIGGER parent_delete_trig - AFTER DELETE ON range_parted for each statement execute procedure trigfunc(); -CREATE TRIGGER parent_update_trig - AFTER UPDATE ON range_parted for each statement execute procedure trigfunc(); -CREATE TRIGGER parent_insert_trig - AFTER INSERT ON range_parted for each statement execute procedure trigfunc(); - --- Triggers on leaf partition part_c_1_100 -CREATE TRIGGER c1_delete_trig - AFTER DELETE ON part_c_1_100 for each statement execute procedure trigfunc(); -CREATE TRIGGER c1_update_trig - AFTER UPDATE ON part_c_1_100 for each statement execute procedure trigfunc(); -CREATE TRIGGER c1_insert_trig - AFTER INSERT ON part_c_1_100 for each statement execute procedure trigfunc(); - --- Triggers on leaf partition part_d_1_15 -CREATE TRIGGER d1_delete_trig - AFTER DELETE ON part_d_1_15 for each statement execute procedure trigfunc(); -CREATE TRIGGER d1_update_trig - AFTER UPDATE ON part_d_1_15 for each statement execute procedure trigfunc(); -CREATE TRIGGER d1_insert_trig - AFTER INSERT ON part_d_1_15 for each statement execute procedure trigfunc(); --- Triggers on leaf partition part_d_15_20 -CREATE TRIGGER d15_delete_trig - AFTER DELETE ON part_d_15_20 for each statement execute procedure trigfunc(); -CREATE TRIGGER d15_update_trig - AFTER UPDATE ON part_d_15_20 for each statement execute procedure trigfunc(); -CREATE TRIGGER d15_insert_trig - AFTER INSERT ON part_d_15_20 for each statement execute procedure trigfunc(); - --- Move all rows from part_c_100_200 to part_c_1_100. None of the delete or --- insert statement triggers should be fired. -UPDATE range_parted set c = c - 50 WHERE c > 97; -:show_data; - -DROP TRIGGER parent_delete_trig ON range_parted; -DROP TRIGGER parent_update_trig ON range_parted; -DROP TRIGGER parent_insert_trig ON range_parted; -DROP TRIGGER c1_delete_trig ON part_c_1_100; -DROP TRIGGER c1_update_trig ON part_c_1_100; -DROP TRIGGER c1_insert_trig ON part_c_1_100; -DROP TRIGGER d1_delete_trig ON part_d_1_15; -DROP TRIGGER d1_update_trig ON part_d_1_15; -DROP TRIGGER d1_insert_trig ON part_d_1_15; -DROP TRIGGER d15_delete_trig ON part_d_15_20; -DROP TRIGGER d15_update_trig ON part_d_15_20; -DROP TRIGGER d15_insert_trig ON part_d_15_20; - - --- Creating default partition for range -:init_range_parted; -create table part_def partition of range_parted default; -\d+ part_def -insert into range_parted values ('c', 9); --- ok -update part_def set a = 'd' where a = 'c'; --- fail -update part_def set a = 'a' where a = 'd'; - -:show_data; - --- Update row movement from non-default to default partition. --- fail, default partition is not under part_a_10_a_20; -UPDATE part_a_10_a_20 set a = 'ad' WHERE a = 'a'; --- ok -UPDATE range_parted set a = 'ad' WHERE a = 'a'; -UPDATE range_parted set a = 'bd' WHERE a = 'b'; -:show_data; --- Update row movement from default to non-default partitions. --- ok -UPDATE range_parted set a = 'a' WHERE a = 'ad'; -UPDATE range_parted set a = 'b' WHERE a = 'bd'; -:show_data; - --- Cleanup: range_parted no longer needed. -DROP TABLE range_parted; - -CREATE TABLE list_parted ( - a text, - b int -) PARTITION BY list (a); -CREATE TABLE list_part1 PARTITION OF list_parted for VALUES in ('a', 'b'); -CREATE TABLE list_default PARTITION OF list_parted default; -INSERT into list_part1 VALUES ('a', 1); -INSERT into list_default VALUES ('d', 10); - --- fail -UPDATE list_default set a = 'a' WHERE a = 'd'; --- ok -UPDATE list_default set a = 'x' WHERE a = 'd'; - -DROP TABLE list_parted; - --- Test retrieval of system columns with non-consistent partition row types. --- This is only partially supported, as seen in the results. - -create table utrtest (a int, b text) partition by list (a); -create table utr1 (a int check (a in (1)), q text, b text); -create table utr2 (a int check (a in (2)), b text); -alter table utr1 drop column q; -alter table utrtest attach partition utr1 for values in (1); -alter table utrtest attach partition utr2 for values in (2); - -insert into utrtest values (1, 'foo') - returning *, tableoid::regclass, xmin = pg_current_xact_id()::xid as xmin_ok; -insert into utrtest values (2, 'bar') - returning *, tableoid::regclass, xmin = pg_current_xact_id()::xid as xmin_ok; -- fails -insert into utrtest values (2, 'bar') - returning *, tableoid::regclass; - -update utrtest set b = b || b from (values (1), (2)) s(x) where a = s.x - returning *, tableoid::regclass, xmin = pg_current_xact_id()::xid as xmin_ok; - -update utrtest set a = 3 - a from (values (1), (2)) s(x) where a = s.x - returning *, tableoid::regclass, xmin = pg_current_xact_id()::xid as xmin_ok; -- fails - -update utrtest set a = 3 - a from (values (1), (2)) s(x) where a = s.x - returning *, tableoid::regclass; - -delete from utrtest - returning *, tableoid::regclass, xmax = pg_current_xact_id()::xid as xmax_ok; - -drop table utrtest; - - --------------- --- Some more update-partition-key test scenarios below. This time use list --- partitions. --------------- - --- Setup for list partitions -CREATE TABLE list_parted (a numeric, b int, c int8) PARTITION BY list (a); -CREATE TABLE sub_parted PARTITION OF list_parted for VALUES in (1) PARTITION BY list (b); - -CREATE TABLE sub_part1(b int, c int8, a numeric); -ALTER TABLE sub_parted ATTACH PARTITION sub_part1 for VALUES in (1); -CREATE TABLE sub_part2(b int, c int8, a numeric); -ALTER TABLE sub_parted ATTACH PARTITION sub_part2 for VALUES in (2); - -CREATE TABLE list_part1(a numeric, b int, c int8); -ALTER TABLE list_parted ATTACH PARTITION list_part1 for VALUES in (2,3); - -INSERT into list_parted VALUES (2,5,50); -INSERT into list_parted VALUES (3,6,60); -INSERT into sub_parted VALUES (1,1,60); -INSERT into sub_parted VALUES (1,2,10); - --- Test partition constraint violation when intermediate ancestor is used and --- constraint is inherited from upper root. -UPDATE sub_parted set a = 2 WHERE c = 10; - --- Test update-partition-key, where the unpruned partitions do not have their --- partition keys updated. -SELECT tableoid::regclass::text, * FROM list_parted WHERE a = 2 ORDER BY 1; -UPDATE list_parted set b = c + a WHERE a = 2; -SELECT tableoid::regclass::text, * FROM list_parted WHERE a = 2 ORDER BY 1; - - --- Test the case where BR UPDATE triggers change the partition key. -CREATE FUNCTION func_parted_mod_b() returns trigger as $$ -BEGIN - NEW.b = 2; -- This is changing partition key column. - return NEW; -END $$ LANGUAGE plpgsql; -CREATE TRIGGER parted_mod_b before update on sub_part1 - for each row execute procedure func_parted_mod_b(); - -SELECT tableoid::regclass::text, * FROM list_parted ORDER BY 1, 2, 3, 4; - --- This should do the tuple routing even though there is no explicit --- partition-key update, because there is a trigger on sub_part1. -UPDATE list_parted set c = 70 WHERE b = 1; -SELECT tableoid::regclass::text, * FROM list_parted ORDER BY 1, 2, 3, 4; - -DROP TRIGGER parted_mod_b ON sub_part1; - --- If BR DELETE trigger prevented DELETE from happening, we should also skip --- the INSERT if that delete is part of UPDATE=>DELETE+INSERT. -CREATE OR REPLACE FUNCTION func_parted_mod_b() returns trigger as $$ -BEGIN - raise notice 'Trigger: Got OLD row %, but returning NULL', OLD; - return NULL; -END $$ LANGUAGE plpgsql; -CREATE TRIGGER trig_skip_delete before delete on sub_part2 - for each row execute procedure func_parted_mod_b(); -UPDATE list_parted set b = 1 WHERE c = 70; -SELECT tableoid::regclass::text, * FROM list_parted ORDER BY 1, 2, 3, 4; --- Drop the trigger. Now the row should be moved. -DROP TRIGGER trig_skip_delete ON sub_part2; -UPDATE list_parted set b = 1 WHERE c = 70; -SELECT tableoid::regclass::text, * FROM list_parted ORDER BY 1, 2, 3, 4; -DROP FUNCTION func_parted_mod_b(); - --- UPDATE partition-key with FROM clause. If join produces multiple output --- rows for the same row to be modified, we should tuple-route the row only --- once. There should not be any rows inserted. -CREATE TABLE non_parted (id int); -INSERT into non_parted VALUES (1), (1), (1), (2), (2), (2), (3), (3), (3); -UPDATE list_parted t1 set a = 2 FROM non_parted t2 WHERE t1.a = t2.id and a = 1; -SELECT tableoid::regclass::text, * FROM list_parted ORDER BY 1, 2, 3, 4; -DROP TABLE non_parted; - --- Cleanup: list_parted no longer needed. -DROP TABLE list_parted; - --- create custom operator class and hash function, for the same reason --- explained in alter_table.sql -create or replace function dummy_hashint4(a int4, seed int8) returns int8 as -$$ begin return (a + seed); end; $$ language 'plpgsql' immutable; -create operator class custom_opclass for type int4 using hash as -operator 1 = , function 2 dummy_hashint4(int4, int8); - -create table hash_parted ( - a int, - b int -) partition by hash (a custom_opclass, b custom_opclass); -create table hpart1 partition of hash_parted for values with (modulus 2, remainder 1); -create table hpart2 partition of hash_parted for values with (modulus 4, remainder 2); -create table hpart3 partition of hash_parted for values with (modulus 8, remainder 0); -create table hpart4 partition of hash_parted for values with (modulus 8, remainder 4); -insert into hpart1 values (1, 1); -insert into hpart2 values (2, 5); -insert into hpart4 values (3, 4); - --- fail -update hpart1 set a = 3, b=4 where a = 1; --- ok, row movement -update hash_parted set b = b - 1 where b = 1; --- ok -update hash_parted set b = b + 8 where b = 1; - --- cleanup -drop table hash_parted; -drop operator class custom_opclass using hash; -drop function dummy_hashint4(a int4, seed int8); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fvacuum.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fvacuum.sql deleted file mode 100644 index 9faa8a34a6..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fvacuum.sql +++ /dev/null @@ -1,320 +0,0 @@ --- --- VACUUM --- - -CREATE TABLE vactst (i INT); -INSERT INTO vactst VALUES (1); -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst VALUES (0); -SELECT count(*) FROM vactst; -DELETE FROM vactst WHERE i != 0; -SELECT * FROM vactst; -VACUUM FULL vactst; -UPDATE vactst SET i = i + 1; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst SELECT * FROM vactst; -INSERT INTO vactst VALUES (0); -SELECT count(*) FROM vactst; -DELETE FROM vactst WHERE i != 0; -VACUUM (FULL) vactst; -DELETE FROM vactst; -SELECT * FROM vactst; - -VACUUM (FULL, FREEZE) vactst; -VACUUM (ANALYZE, FULL) vactst; - -CREATE TABLE vaccluster (i INT PRIMARY KEY); -ALTER TABLE vaccluster CLUSTER ON vaccluster_pkey; -CLUSTER vaccluster; - -CREATE FUNCTION do_analyze() RETURNS VOID VOLATILE LANGUAGE SQL - AS 'ANALYZE pg_am'; -CREATE FUNCTION wrap_do_analyze(c INT) RETURNS INT IMMUTABLE LANGUAGE SQL - AS 'SELECT $1 FROM do_analyze()'; -CREATE INDEX ON vaccluster(wrap_do_analyze(i)); -INSERT INTO vaccluster VALUES (1), (2); -ANALYZE vaccluster; - --- Test ANALYZE in transaction, where the transaction surrounding --- analyze performed modifications. This tests for the bug at --- https://postgr.es/m/c7988239-d42c-ddc4-41db-171b23b35e4f%40ssinger.info --- (which hopefully is unlikely to be reintroduced), but also seems --- independently worthwhile to cover. -INSERT INTO vactst SELECT generate_series(1, 300); -DELETE FROM vactst WHERE i % 7 = 0; -- delete a few rows outside -BEGIN; -INSERT INTO vactst SELECT generate_series(301, 400); -DELETE FROM vactst WHERE i % 5 <> 0; -- delete a few rows inside -ANALYZE vactst; -COMMIT; - -VACUUM FULL pg_am; -VACUUM FULL pg_class; -VACUUM FULL pg_database; -VACUUM FULL vaccluster; -VACUUM FULL vactst; - -VACUUM (DISABLE_PAGE_SKIPPING) vaccluster; - --- PARALLEL option -CREATE TABLE pvactst (i INT, a INT[], p POINT) with (autovacuum_enabled = off); -INSERT INTO pvactst SELECT i, array[1,2,3], point(i, i+1) FROM generate_series(1,1000) i; -CREATE INDEX btree_pvactst ON pvactst USING btree (i); -CREATE INDEX hash_pvactst ON pvactst USING hash (i); -CREATE INDEX brin_pvactst ON pvactst USING brin (i); -CREATE INDEX gin_pvactst ON pvactst USING gin (a); -CREATE INDEX gist_pvactst ON pvactst USING gist (p); -CREATE INDEX spgist_pvactst ON pvactst USING spgist (p); - --- VACUUM invokes parallel index cleanup -SET min_parallel_index_scan_size to 0; -VACUUM (PARALLEL 2) pvactst; - --- VACUUM invokes parallel bulk-deletion -UPDATE pvactst SET i = i WHERE i < 1000; -VACUUM (PARALLEL 2) pvactst; - -UPDATE pvactst SET i = i WHERE i < 1000; -VACUUM (PARALLEL 0) pvactst; -- disable parallel vacuum - -VACUUM (PARALLEL -1) pvactst; -- error -VACUUM (PARALLEL 2, INDEX_CLEANUP FALSE) pvactst; -VACUUM (PARALLEL 2, FULL TRUE) pvactst; -- error, cannot use both PARALLEL and FULL -VACUUM (PARALLEL) pvactst; -- error, cannot use PARALLEL option without parallel degree - --- Test different combinations of parallel and full options for temporary tables -CREATE TEMPORARY TABLE tmp (a int PRIMARY KEY); -CREATE INDEX tmp_idx1 ON tmp (a); -VACUUM (PARALLEL 1, FULL FALSE) tmp; -- parallel vacuum disabled for temp tables -VACUUM (PARALLEL 0, FULL TRUE) tmp; -- can specify parallel disabled (even though that's implied by FULL) -RESET min_parallel_index_scan_size; -DROP TABLE pvactst; - --- INDEX_CLEANUP option -CREATE TABLE no_index_cleanup (i INT PRIMARY KEY, t TEXT); --- Use uncompressed data stored in toast. -CREATE INDEX no_index_cleanup_idx ON no_index_cleanup(t); -ALTER TABLE no_index_cleanup ALTER COLUMN t SET STORAGE EXTERNAL; -INSERT INTO no_index_cleanup(i, t) VALUES (generate_series(1,30), - repeat('1234567890',269)); --- index cleanup option is ignored if VACUUM FULL -VACUUM (INDEX_CLEANUP TRUE, FULL TRUE) no_index_cleanup; -VACUUM (FULL TRUE) no_index_cleanup; --- Toast inherits the value from its parent table. -ALTER TABLE no_index_cleanup SET (vacuum_index_cleanup = false); -DELETE FROM no_index_cleanup WHERE i < 15; --- Nothing is cleaned up. -VACUUM no_index_cleanup; --- Both parent relation and toast are cleaned up. -ALTER TABLE no_index_cleanup SET (vacuum_index_cleanup = true); -VACUUM no_index_cleanup; -ALTER TABLE no_index_cleanup SET (vacuum_index_cleanup = auto); -VACUUM no_index_cleanup; --- Parameter is set for both the parent table and its toast relation. -INSERT INTO no_index_cleanup(i, t) VALUES (generate_series(31,60), - repeat('1234567890',269)); -DELETE FROM no_index_cleanup WHERE i < 45; --- Only toast index is cleaned up. -ALTER TABLE no_index_cleanup SET (vacuum_index_cleanup = off, - toast.vacuum_index_cleanup = yes); -VACUUM no_index_cleanup; --- Only parent is cleaned up. -ALTER TABLE no_index_cleanup SET (vacuum_index_cleanup = true, - toast.vacuum_index_cleanup = false); -VACUUM no_index_cleanup; --- Test some extra relations. -VACUUM (INDEX_CLEANUP FALSE) vaccluster; -VACUUM (INDEX_CLEANUP AUTO) vactst; -- index cleanup option is ignored if no indexes -VACUUM (INDEX_CLEANUP FALSE, FREEZE TRUE) vaccluster; - --- TRUNCATE option -CREATE TEMP TABLE vac_truncate_test(i INT NOT NULL, j text) - WITH (vacuum_truncate=true, autovacuum_enabled=false); -INSERT INTO vac_truncate_test VALUES (1, NULL), (NULL, NULL); -VACUUM (TRUNCATE FALSE, DISABLE_PAGE_SKIPPING) vac_truncate_test; -SELECT pg_relation_size('vac_truncate_test') > 0; -VACUUM (DISABLE_PAGE_SKIPPING) vac_truncate_test; -SELECT pg_relation_size('vac_truncate_test') = 0; -VACUUM (TRUNCATE FALSE, FULL TRUE) vac_truncate_test; -DROP TABLE vac_truncate_test; - --- partitioned table -CREATE TABLE vacparted (a int, b char) PARTITION BY LIST (a); -CREATE TABLE vacparted1 PARTITION OF vacparted FOR VALUES IN (1); -INSERT INTO vacparted VALUES (1, 'a'); -UPDATE vacparted SET b = 'b'; -VACUUM (ANALYZE) vacparted; -VACUUM (FULL) vacparted; -VACUUM (FREEZE) vacparted; - --- check behavior with duplicate column mentions -VACUUM ANALYZE vacparted(a,b,a); -ANALYZE vacparted(a,b,b); - --- partitioned table with index -CREATE TABLE vacparted_i (a int primary key, b varchar(100)) - PARTITION BY HASH (a); -CREATE TABLE vacparted_i1 PARTITION OF vacparted_i - FOR VALUES WITH (MODULUS 2, REMAINDER 0); -CREATE TABLE vacparted_i2 PARTITION OF vacparted_i - FOR VALUES WITH (MODULUS 2, REMAINDER 1); -INSERT INTO vacparted_i SELECT i, 'test_'|| i from generate_series(1,10) i; -VACUUM (ANALYZE) vacparted_i; -VACUUM (FULL) vacparted_i; -VACUUM (FREEZE) vacparted_i; -SELECT relname, relhasindex FROM pg_class - WHERE relname LIKE 'vacparted_i%' AND relkind IN ('p','r') - ORDER BY relname; -DROP TABLE vacparted_i; - --- multiple tables specified -VACUUM vaccluster, vactst; -VACUUM vacparted, does_not_exist; -VACUUM (FREEZE) vacparted, vaccluster, vactst; -VACUUM (FREEZE) does_not_exist, vaccluster; -VACUUM ANALYZE vactst, vacparted (a); -VACUUM ANALYZE vactst (does_not_exist), vacparted (b); -VACUUM FULL vacparted, vactst; -VACUUM FULL vactst, vacparted (a, b), vaccluster (i); -ANALYZE vactst, vacparted; -ANALYZE vacparted (b), vactst; -ANALYZE vactst, does_not_exist, vacparted; -ANALYZE vactst (i), vacparted (does_not_exist); -ANALYZE vactst, vactst; -BEGIN; -- ANALYZE behaves differently inside a transaction block -ANALYZE vactst, vactst; -COMMIT; - --- parenthesized syntax for ANALYZE -ANALYZE (VERBOSE) does_not_exist; -ANALYZE (nonexistent-arg) does_not_exist; -ANALYZE (nonexistentarg) does_not_exit; - --- ensure argument order independence, and that SKIP_LOCKED on non-existing --- relation still errors out. Suppress WARNING messages caused by concurrent --- autovacuums. -SET client_min_messages TO 'ERROR'; -ANALYZE (SKIP_LOCKED, VERBOSE) does_not_exist; -ANALYZE (VERBOSE, SKIP_LOCKED) does_not_exist; - --- SKIP_LOCKED option -VACUUM (SKIP_LOCKED) vactst; -VACUUM (SKIP_LOCKED, FULL) vactst; -ANALYZE (SKIP_LOCKED) vactst; -RESET client_min_messages; - --- ensure VACUUM and ANALYZE don't have a problem with serializable -SET default_transaction_isolation = serializable; -VACUUM vactst; -ANALYZE vactst; -RESET default_transaction_isolation; -BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE; -ANALYZE vactst; -COMMIT; - --- PROCESS_TOAST option -ALTER TABLE vactst ADD COLUMN t TEXT; -ALTER TABLE vactst ALTER COLUMN t SET STORAGE EXTERNAL; -VACUUM (PROCESS_TOAST FALSE) vactst; -VACUUM (PROCESS_TOAST FALSE, FULL) vactst; - -DROP TABLE vaccluster; -DROP TABLE vactst; -DROP TABLE vacparted; -DROP TABLE no_index_cleanup; - --- relation ownership, WARNING logs generated as all are skipped. -CREATE TABLE vacowned (a int); -CREATE TABLE vacowned_parted (a int) PARTITION BY LIST (a); -CREATE TABLE vacowned_part1 PARTITION OF vacowned_parted FOR VALUES IN (1); -CREATE TABLE vacowned_part2 PARTITION OF vacowned_parted FOR VALUES IN (2); -CREATE ROLE regress_vacuum; -SET ROLE regress_vacuum; --- Simple table -VACUUM vacowned; -ANALYZE vacowned; -VACUUM (ANALYZE) vacowned; --- Catalog -VACUUM pg_catalog.pg_class; -ANALYZE pg_catalog.pg_class; -VACUUM (ANALYZE) pg_catalog.pg_class; --- Shared catalog -VACUUM pg_catalog.pg_authid; -ANALYZE pg_catalog.pg_authid; -VACUUM (ANALYZE) pg_catalog.pg_authid; --- Partitioned table and its partitions, nothing owned by other user. --- Relations are not listed in a single command to test ownership --- independently. -VACUUM vacowned_parted; -VACUUM vacowned_part1; -VACUUM vacowned_part2; -ANALYZE vacowned_parted; -ANALYZE vacowned_part1; -ANALYZE vacowned_part2; -VACUUM (ANALYZE) vacowned_parted; -VACUUM (ANALYZE) vacowned_part1; -VACUUM (ANALYZE) vacowned_part2; -RESET ROLE; --- Partitioned table and one partition owned by other user. -ALTER TABLE vacowned_parted OWNER TO regress_vacuum; -ALTER TABLE vacowned_part1 OWNER TO regress_vacuum; -SET ROLE regress_vacuum; -VACUUM vacowned_parted; -VACUUM vacowned_part1; -VACUUM vacowned_part2; -ANALYZE vacowned_parted; -ANALYZE vacowned_part1; -ANALYZE vacowned_part2; -VACUUM (ANALYZE) vacowned_parted; -VACUUM (ANALYZE) vacowned_part1; -VACUUM (ANALYZE) vacowned_part2; -RESET ROLE; --- Only one partition owned by other user. -ALTER TABLE vacowned_parted OWNER TO CURRENT_USER; -SET ROLE regress_vacuum; -VACUUM vacowned_parted; -VACUUM vacowned_part1; -VACUUM vacowned_part2; -ANALYZE vacowned_parted; -ANALYZE vacowned_part1; -ANALYZE vacowned_part2; -VACUUM (ANALYZE) vacowned_parted; -VACUUM (ANALYZE) vacowned_part1; -VACUUM (ANALYZE) vacowned_part2; -RESET ROLE; --- Only partitioned table owned by other user. -ALTER TABLE vacowned_parted OWNER TO regress_vacuum; -ALTER TABLE vacowned_part1 OWNER TO CURRENT_USER; -SET ROLE regress_vacuum; -VACUUM vacowned_parted; -VACUUM vacowned_part1; -VACUUM vacowned_part2; -ANALYZE vacowned_parted; -ANALYZE vacowned_part1; -ANALYZE vacowned_part2; -VACUUM (ANALYZE) vacowned_parted; -VACUUM (ANALYZE) vacowned_part1; -VACUUM (ANALYZE) vacowned_part2; -RESET ROLE; -DROP TABLE vacowned; -DROP TABLE vacowned_parted; -DROP ROLE regress_vacuum; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwindow.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwindow.sql deleted file mode 100644 index a504e46e40..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwindow.sql +++ /dev/null @@ -1,1612 +0,0 @@ --- --- WINDOW FUNCTIONS --- - -CREATE TEMPORARY TABLE empsalary ( - depname varchar, - empno bigint, - salary int, - enroll_date date -); - -INSERT INTO empsalary VALUES -('develop', 10, 5200, '2007-08-01'), -('sales', 1, 5000, '2006-10-01'), -('personnel', 5, 3500, '2007-12-10'), -('sales', 4, 4800, '2007-08-08'), -('personnel', 2, 3900, '2006-12-23'), -('develop', 7, 4200, '2008-01-01'), -('develop', 9, 4500, '2008-01-01'), -('sales', 3, 4800, '2007-08-01'), -('develop', 8, 6000, '2006-10-01'), -('develop', 11, 5200, '2007-08-15'); - -SELECT depname, empno, salary, sum(salary) OVER (PARTITION BY depname) FROM empsalary ORDER BY depname, salary; - -SELECT depname, empno, salary, rank() OVER (PARTITION BY depname ORDER BY salary) FROM empsalary; - --- with GROUP BY -SELECT four, ten, SUM(SUM(four)) OVER (PARTITION BY four), AVG(ten) FROM tenk1 -GROUP BY four, ten ORDER BY four, ten; - -SELECT depname, empno, salary, sum(salary) OVER w FROM empsalary WINDOW w AS (PARTITION BY depname); - -SELECT depname, empno, salary, rank() OVER w FROM empsalary WINDOW w AS (PARTITION BY depname ORDER BY salary) ORDER BY rank() OVER w; - --- empty window specification -SELECT COUNT(*) OVER () FROM tenk1 WHERE unique2 < 10; - -SELECT COUNT(*) OVER w FROM tenk1 WHERE unique2 < 10 WINDOW w AS (); - --- no window operation -SELECT four FROM tenk1 WHERE FALSE WINDOW w AS (PARTITION BY ten); - --- cumulative aggregate -SELECT sum(four) OVER (PARTITION BY ten ORDER BY unique2) AS sum_1, ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT row_number() OVER (ORDER BY unique2) FROM tenk1 WHERE unique2 < 10; - -SELECT rank() OVER (PARTITION BY four ORDER BY ten) AS rank_1, ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT dense_rank() OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT percent_rank() OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT cume_dist() OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT ntile(3) OVER (ORDER BY ten, four), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT ntile(NULL) OVER (ORDER BY ten, four), ten, four FROM tenk1 LIMIT 2; - -SELECT lag(ten) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT lag(ten, four) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT lag(ten, four, 0) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; -SELECT lag(ten, four, 0.7) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10 ORDER BY four, ten; - -SELECT lead(ten) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT lead(ten * 2, 1) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT lead(ten * 2, 1, -1) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; -SELECT lead(ten * 2, 1, -1.4) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10 ORDER BY four, ten; - -SELECT first_value(ten) OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - --- last_value returns the last row of the frame, which is CURRENT ROW in ORDER BY window. -SELECT last_value(four) OVER (ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10; - -SELECT last_value(ten) OVER (PARTITION BY four), ten, four FROM - (SELECT * FROM tenk1 WHERE unique2 < 10 ORDER BY four, ten)s - ORDER BY four, ten; - -SELECT nth_value(ten, four + 1) OVER (PARTITION BY four), ten, four - FROM (SELECT * FROM tenk1 WHERE unique2 < 10 ORDER BY four, ten)s; - -SELECT ten, two, sum(hundred) AS gsum, sum(sum(hundred)) OVER (PARTITION BY two ORDER BY ten) AS wsum -FROM tenk1 GROUP BY ten, two; - -SELECT count(*) OVER (PARTITION BY four), four FROM (SELECT * FROM tenk1 WHERE two = 1)s WHERE unique2 < 10; - -SELECT (count(*) OVER (PARTITION BY four ORDER BY ten) + - sum(hundred) OVER (PARTITION BY four ORDER BY ten))::varchar AS cntsum - FROM tenk1 WHERE unique2 < 10; - --- opexpr with different windows evaluation. -SELECT * FROM( - SELECT count(*) OVER (PARTITION BY four ORDER BY ten) + - sum(hundred) OVER (PARTITION BY two ORDER BY ten) AS total, - count(*) OVER (PARTITION BY four ORDER BY ten) AS fourcount, - sum(hundred) OVER (PARTITION BY two ORDER BY ten) AS twosum - FROM tenk1 -)sub -WHERE total <> fourcount + twosum; - -SELECT avg(four) OVER (PARTITION BY four ORDER BY thousand / 100) FROM tenk1 WHERE unique2 < 10; - -SELECT ten, two, sum(hundred) AS gsum, sum(sum(hundred)) OVER win AS wsum -FROM tenk1 GROUP BY ten, two WINDOW win AS (PARTITION BY two ORDER BY ten); - --- more than one window with GROUP BY -SELECT sum(salary), - row_number() OVER (ORDER BY depname), - sum(sum(salary)) OVER (ORDER BY depname DESC) -FROM empsalary GROUP BY depname; - --- identical windows with different names -SELECT sum(salary) OVER w1, count(*) OVER w2 -FROM empsalary WINDOW w1 AS (ORDER BY salary), w2 AS (ORDER BY salary); - --- subplan -SELECT lead(ten, (SELECT two FROM tenk1 WHERE s.unique2 = unique2)) OVER (PARTITION BY four ORDER BY ten) -FROM tenk1 s WHERE unique2 < 10; - --- empty table -SELECT count(*) OVER (PARTITION BY four) FROM (SELECT * FROM tenk1 WHERE FALSE)s; - --- mixture of agg/wfunc in the same window -SELECT sum(salary) OVER w, rank() OVER w FROM empsalary WINDOW w AS (PARTITION BY depname ORDER BY salary DESC); - --- strict aggs -SELECT empno, depname, salary, bonus, depadj, MIN(bonus) OVER (ORDER BY empno), MAX(depadj) OVER () FROM( - SELECT *, - CASE WHEN enroll_date < '2008-01-01' THEN 2008 - extract(YEAR FROM enroll_date) END * 500 AS bonus, - CASE WHEN - AVG(salary) OVER (PARTITION BY depname) < salary - THEN 200 END AS depadj FROM empsalary -)s; - --- window function over ungrouped agg over empty row set (bug before 9.1) -SELECT SUM(COUNT(f1)) OVER () FROM int4_tbl WHERE f1=42; - --- window function with ORDER BY an expression involving aggregates (9.1 bug) -select ten, - sum(unique1) + sum(unique2) as res, - rank() over (order by sum(unique1) + sum(unique2)) as rank -from tenk1 -group by ten order by ten; - --- window and aggregate with GROUP BY expression (9.2 bug) -explain (costs off) -select first_value(max(x)) over (), y - from (select unique1 as x, ten+four as y from tenk1) ss - group by y; - --- test non-default frame specifications -SELECT four, ten, - sum(ten) over (partition by four order by ten), - last_value(ten) over (partition by four order by ten) -FROM (select distinct ten, four from tenk1) ss; - -SELECT four, ten, - sum(ten) over (partition by four order by ten range between unbounded preceding and current row), - last_value(ten) over (partition by four order by ten range between unbounded preceding and current row) -FROM (select distinct ten, four from tenk1) ss; - -SELECT four, ten, - sum(ten) over (partition by four order by ten range between unbounded preceding and unbounded following), - last_value(ten) over (partition by four order by ten range between unbounded preceding and unbounded following) -FROM (select distinct ten, four from tenk1) ss; - -SELECT four, ten/4 as two, - sum(ten/4) over (partition by four order by ten/4 range between unbounded preceding and current row), - last_value(ten/4) over (partition by four order by ten/4 range between unbounded preceding and current row) -FROM (select distinct ten, four from tenk1) ss; - -SELECT four, ten/4 as two, - sum(ten/4) over (partition by four order by ten/4 rows between unbounded preceding and current row), - last_value(ten/4) over (partition by four order by ten/4 rows between unbounded preceding and current row) -FROM (select distinct ten, four from tenk1) ss; - -SELECT sum(unique1) over (order by four range between current row and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between current row and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 2 preceding and 2 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 2 preceding and 2 following exclude no others), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 2 preceding and 2 following exclude current row), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 2 preceding and 2 following exclude group), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 2 preceding and 2 following exclude ties), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT first_value(unique1) over (ORDER BY four rows between current row and 2 following exclude current row), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT first_value(unique1) over (ORDER BY four rows between current row and 2 following exclude group), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT first_value(unique1) over (ORDER BY four rows between current row and 2 following exclude ties), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT last_value(unique1) over (ORDER BY four rows between current row and 2 following exclude current row), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT last_value(unique1) over (ORDER BY four rows between current row and 2 following exclude group), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT last_value(unique1) over (ORDER BY four rows between current row and 2 following exclude ties), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 2 preceding and 1 preceding), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between 1 following and 3 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between unbounded preceding and 1 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (w range between current row and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four); - -SELECT sum(unique1) over (w range between unbounded preceding and current row exclude current row), - unique1, four -FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four); - -SELECT sum(unique1) over (w range between unbounded preceding and current row exclude group), - unique1, four -FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four); - -SELECT sum(unique1) over (w range between unbounded preceding and current row exclude ties), - unique1, four -FROM tenk1 WHERE unique1 < 10 WINDOW w AS (order by four); - -SELECT first_value(unique1) over w, - nth_value(unique1, 2) over w AS nth_2, - last_value(unique1) over w, unique1, four -FROM tenk1 WHERE unique1 < 10 -WINDOW w AS (order by four range between current row and unbounded following); - -SELECT sum(unique1) over - (order by unique1 - rows (SELECT unique1 FROM tenk1 ORDER BY unique1 LIMIT 1) + 1 PRECEDING), - unique1 -FROM tenk1 WHERE unique1 < 10; - -CREATE TEMP VIEW v_window AS - SELECT i, sum(i) over (order by i rows between 1 preceding and 1 following) as sum_rows - FROM generate_series(1, 10) i; - -SELECT * FROM v_window; - -SELECT pg_get_viewdef('v_window'); - -CREATE OR REPLACE TEMP VIEW v_window AS - SELECT i, sum(i) over (order by i rows between 1 preceding and 1 following - exclude current row) as sum_rows FROM generate_series(1, 10) i; - -SELECT * FROM v_window; - -SELECT pg_get_viewdef('v_window'); - -CREATE OR REPLACE TEMP VIEW v_window AS - SELECT i, sum(i) over (order by i rows between 1 preceding and 1 following - exclude group) as sum_rows FROM generate_series(1, 10) i; - -SELECT * FROM v_window; - -SELECT pg_get_viewdef('v_window'); - -CREATE OR REPLACE TEMP VIEW v_window AS - SELECT i, sum(i) over (order by i rows between 1 preceding and 1 following - exclude ties) as sum_rows FROM generate_series(1, 10) i; - -SELECT * FROM v_window; - -SELECT pg_get_viewdef('v_window'); - -CREATE OR REPLACE TEMP VIEW v_window AS - SELECT i, sum(i) over (order by i rows between 1 preceding and 1 following - exclude no others) as sum_rows FROM generate_series(1, 10) i; - -SELECT * FROM v_window; - -SELECT pg_get_viewdef('v_window'); - -CREATE OR REPLACE TEMP VIEW v_window AS - SELECT i, sum(i) over (order by i groups between 1 preceding and 1 following) as sum_rows FROM generate_series(1, 10) i; - -SELECT * FROM v_window; - -SELECT pg_get_viewdef('v_window'); - -DROP VIEW v_window; - -CREATE TEMP VIEW v_window AS - SELECT i, min(i) over (order by i range between '1 day' preceding and '10 days' following) as min_i - FROM generate_series(now(), now()+'100 days'::interval, '1 hour') i; - -SELECT pg_get_viewdef('v_window'); - --- RANGE offset PRECEDING/FOLLOWING tests - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four desc range between 2::int8 preceding and 1::int2 preceding), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding exclude no others), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding exclude current row), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding exclude group), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 1::int2 preceding exclude ties), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 6::int2 following exclude ties), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four range between 2::int8 preceding and 6::int2 following exclude group), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (partition by four order by unique1 range between 5::int8 preceding and 6::int2 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (partition by four order by unique1 range between 5::int8 preceding and 6::int2 following - exclude current row),unique1, four -FROM tenk1 WHERE unique1 < 10; - -select sum(salary) over (order by enroll_date range between '1 year'::interval preceding and '1 year'::interval following), - salary, enroll_date from empsalary; - -select sum(salary) over (order by enroll_date desc range between '1 year'::interval preceding and '1 year'::interval following), - salary, enroll_date from empsalary; - -select sum(salary) over (order by enroll_date desc range between '1 year'::interval following and '1 year'::interval following), - salary, enroll_date from empsalary; - -select sum(salary) over (order by enroll_date range between '1 year'::interval preceding and '1 year'::interval following - exclude current row), salary, enroll_date from empsalary; - -select sum(salary) over (order by enroll_date range between '1 year'::interval preceding and '1 year'::interval following - exclude group), salary, enroll_date from empsalary; - -select sum(salary) over (order by enroll_date range between '1 year'::interval preceding and '1 year'::interval following - exclude ties), salary, enroll_date from empsalary; - -select first_value(salary) over(order by salary range between 1000 preceding and 1000 following), - lead(salary) over(order by salary range between 1000 preceding and 1000 following), - nth_value(salary, 1) over(order by salary range between 1000 preceding and 1000 following), - salary from empsalary; - -select last_value(salary) over(order by salary range between 1000 preceding and 1000 following), - lag(salary) over(order by salary range between 1000 preceding and 1000 following), - salary from empsalary; - -select first_value(salary) over(order by salary range between 1000 following and 3000 following - exclude current row), - lead(salary) over(order by salary range between 1000 following and 3000 following exclude ties), - nth_value(salary, 1) over(order by salary range between 1000 following and 3000 following - exclude ties), - salary from empsalary; - -select last_value(salary) over(order by salary range between 1000 following and 3000 following - exclude group), - lag(salary) over(order by salary range between 1000 following and 3000 following exclude group), - salary from empsalary; - -select first_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude ties), - last_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following), - salary, enroll_date from empsalary; - -select first_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude ties), - last_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude ties), - salary, enroll_date from empsalary; - -select first_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude group), - last_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude group), - salary, enroll_date from empsalary; - -select first_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude current row), - last_value(salary) over(order by enroll_date range between unbounded preceding and '1 year'::interval following - exclude current row), - salary, enroll_date from empsalary; - --- RANGE offset PRECEDING/FOLLOWING with null values -select x, y, - first_value(y) over w, - last_value(y) over w -from - (select x, x as y from generate_series(1,5) as x - union all select null, 42 - union all select null, 43) ss -window w as - (order by x asc nulls first range between 2 preceding and 2 following); - -select x, y, - first_value(y) over w, - last_value(y) over w -from - (select x, x as y from generate_series(1,5) as x - union all select null, 42 - union all select null, 43) ss -window w as - (order by x asc nulls last range between 2 preceding and 2 following); - -select x, y, - first_value(y) over w, - last_value(y) over w -from - (select x, x as y from generate_series(1,5) as x - union all select null, 42 - union all select null, 43) ss -window w as - (order by x desc nulls first range between 2 preceding and 2 following); - -select x, y, - first_value(y) over w, - last_value(y) over w -from - (select x, x as y from generate_series(1,5) as x - union all select null, 42 - union all select null, 43) ss -window w as - (order by x desc nulls last range between 2 preceding and 2 following); - --- There is a syntactic ambiguity in the SQL standard. Since --- UNBOUNDED is a non-reserved word, it could be the name of a --- function parameter and be used as an expression. There is a --- grammar hack to resolve such cases as the keyword. The following --- tests record this behavior. - -CREATE FUNCTION unbounded_syntax_test1a(x int) RETURNS TABLE (a int, b int, c int) -LANGUAGE SQL -BEGIN ATOMIC - SELECT sum(unique1) over (rows between x preceding and x following), - unique1, four - FROM tenk1 WHERE unique1 < 10; -END; - -CREATE FUNCTION unbounded_syntax_test1b(x int) RETURNS TABLE (a int, b int, c int) -LANGUAGE SQL -AS $$ - SELECT sum(unique1) over (rows between x preceding and x following), - unique1, four - FROM tenk1 WHERE unique1 < 10; -$$; - --- These will apply the argument to the window specification inside the function. -SELECT * FROM unbounded_syntax_test1a(2); -SELECT * FROM unbounded_syntax_test1b(2); - -CREATE FUNCTION unbounded_syntax_test2a(unbounded int) RETURNS TABLE (a int, b int, c int) -LANGUAGE SQL -BEGIN ATOMIC - SELECT sum(unique1) over (rows between unbounded preceding and unbounded following), - unique1, four - FROM tenk1 WHERE unique1 < 10; -END; - -CREATE FUNCTION unbounded_syntax_test2b(unbounded int) RETURNS TABLE (a int, b int, c int) -LANGUAGE SQL -AS $$ - SELECT sum(unique1) over (rows between unbounded preceding and unbounded following), - unique1, four - FROM tenk1 WHERE unique1 < 10; -$$; - --- These will not apply the argument but instead treat UNBOUNDED as a keyword. -SELECT * FROM unbounded_syntax_test2a(2); -SELECT * FROM unbounded_syntax_test2b(2); - -DROP FUNCTION unbounded_syntax_test1a, unbounded_syntax_test1b, - unbounded_syntax_test2a, unbounded_syntax_test2b; - --- Other tests with token UNBOUNDED in potentially problematic position -CREATE FUNCTION unbounded(x int) RETURNS int LANGUAGE SQL IMMUTABLE RETURN x; - -SELECT sum(unique1) over (rows between 1 preceding and 1 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between unbounded(1) preceding and unbounded(1) following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (rows between unbounded.x preceding and unbounded.x following), - unique1, four -FROM tenk1, (values (1)) as unbounded(x) WHERE unique1 < 10; - -DROP FUNCTION unbounded; - --- Check overflow behavior for various integer sizes - -select x, last_value(x) over (order by x::smallint range between current row and 2147450884 following) -from generate_series(32764, 32766) x; - -select x, last_value(x) over (order by x::smallint desc range between current row and 2147450885 following) -from generate_series(-32766, -32764) x; - -select x, last_value(x) over (order by x range between current row and 4 following) -from generate_series(2147483644, 2147483646) x; - -select x, last_value(x) over (order by x desc range between current row and 5 following) -from generate_series(-2147483646, -2147483644) x; - -select x, last_value(x) over (order by x range between current row and 4 following) -from generate_series(9223372036854775804, 9223372036854775806) x; - -select x, last_value(x) over (order by x desc range between current row and 5 following) -from generate_series(-9223372036854775806, -9223372036854775804) x; - --- Test in_range for other numeric datatypes - -create temp table numerics( - id int, - f_float4 float4, - f_float8 float8, - f_numeric numeric -); - -insert into numerics values -(0, '-infinity', '-infinity', '-infinity'), -(1, -3, -3, -3), -(2, -1, -1, -1), -(3, 0, 0, 0), -(4, 1.1, 1.1, 1.1), -(5, 1.12, 1.12, 1.12), -(6, 2, 2, 2), -(7, 100, 100, 100), -(8, 'infinity', 'infinity', 'infinity'), -(9, 'NaN', 'NaN', 'NaN'); - -select id, f_float4, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float4 range between - 1 preceding and 1 following); -select id, f_float4, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float4 range between - 1 preceding and 1.1::float4 following); -select id, f_float4, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float4 range between - 'inf' preceding and 'inf' following); -select id, f_float4, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float4 range between - 'inf' preceding and 'inf' preceding); -select id, f_float4, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float4 range between - 'inf' following and 'inf' following); -select id, f_float4, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float4 range between - 1.1 preceding and 'NaN' following); -- error, NaN disallowed - -select id, f_float8, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float8 range between - 1 preceding and 1 following); -select id, f_float8, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float8 range between - 1 preceding and 1.1::float8 following); -select id, f_float8, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float8 range between - 'inf' preceding and 'inf' following); -select id, f_float8, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float8 range between - 'inf' preceding and 'inf' preceding); -select id, f_float8, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float8 range between - 'inf' following and 'inf' following); -select id, f_float8, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_float8 range between - 1.1 preceding and 'NaN' following); -- error, NaN disallowed - -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 1 preceding and 1 following); -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 1 preceding and 1.1::numeric following); -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 1 preceding and 1.1::float8 following); -- currently unsupported -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 'inf' preceding and 'inf' following); -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 'inf' preceding and 'inf' preceding); -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 'inf' following and 'inf' following); -select id, f_numeric, first_value(id) over w, last_value(id) over w -from numerics -window w as (order by f_numeric range between - 1.1 preceding and 'NaN' following); -- error, NaN disallowed - --- Test in_range for other datetime datatypes - -create temp table datetimes( - id int, - f_time time, - f_timetz timetz, - f_interval interval, - f_timestamptz timestamptz, - f_timestamp timestamp -); - -insert into datetimes values -(1, '11:00', '11:00 BST', '1 year', '2000-10-19 10:23:54+01', '2000-10-19 10:23:54'), -(2, '12:00', '12:00 BST', '2 years', '2001-10-19 10:23:54+01', '2001-10-19 10:23:54'), -(3, '13:00', '13:00 BST', '3 years', '2001-10-19 10:23:54+01', '2001-10-19 10:23:54'), -(4, '14:00', '14:00 BST', '4 years', '2002-10-19 10:23:54+01', '2002-10-19 10:23:54'), -(5, '15:00', '15:00 BST', '5 years', '2003-10-19 10:23:54+01', '2003-10-19 10:23:54'), -(6, '15:00', '15:00 BST', '5 years', '2004-10-19 10:23:54+01', '2004-10-19 10:23:54'), -(7, '17:00', '17:00 BST', '7 years', '2005-10-19 10:23:54+01', '2005-10-19 10:23:54'), -(8, '18:00', '18:00 BST', '8 years', '2006-10-19 10:23:54+01', '2006-10-19 10:23:54'), -(9, '19:00', '19:00 BST', '9 years', '2007-10-19 10:23:54+01', '2007-10-19 10:23:54'), -(10, '20:00', '20:00 BST', '10 years', '2008-10-19 10:23:54+01', '2008-10-19 10:23:54'); - -select id, f_time, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_time range between - '70 min'::interval preceding and '2 hours'::interval following); - -select id, f_time, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_time desc range between - '70 min' preceding and '2 hours' following); - -select id, f_timetz, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_timetz range between - '70 min'::interval preceding and '2 hours'::interval following); - -select id, f_timetz, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_timetz desc range between - '70 min' preceding and '2 hours' following); - -select id, f_interval, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_interval range between - '1 year'::interval preceding and '1 year'::interval following); - -select id, f_interval, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_interval desc range between - '1 year' preceding and '1 year' following); - -select id, f_timestamptz, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_timestamptz range between - '1 year'::interval preceding and '1 year'::interval following); - -select id, f_timestamptz, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_timestamptz desc range between - '1 year' preceding and '1 year' following); - -select id, f_timestamp, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_timestamp range between - '1 year'::interval preceding and '1 year'::interval following); - -select id, f_timestamp, first_value(id) over w, last_value(id) over w -from datetimes -window w as (order by f_timestamp desc range between - '1 year' preceding and '1 year' following); - --- RANGE offset PRECEDING/FOLLOWING error cases -select sum(salary) over (order by enroll_date, salary range between '1 year'::interval preceding and '2 years'::interval following - exclude ties), salary, enroll_date from empsalary; - -select sum(salary) over (range between '1 year'::interval preceding and '2 years'::interval following - exclude ties), salary, enroll_date from empsalary; - -select sum(salary) over (order by depname range between '1 year'::interval preceding and '2 years'::interval following - exclude ties), salary, enroll_date from empsalary; - -select max(enroll_date) over (order by enroll_date range between 1 preceding and 2 following - exclude ties), salary, enroll_date from empsalary; - -select max(enroll_date) over (order by salary range between -1 preceding and 2 following - exclude ties), salary, enroll_date from empsalary; - -select max(enroll_date) over (order by salary range between 1 preceding and -2 following - exclude ties), salary, enroll_date from empsalary; - -select max(enroll_date) over (order by salary range between '1 year'::interval preceding and '2 years'::interval following - exclude ties), salary, enroll_date from empsalary; - -select max(enroll_date) over (order by enroll_date range between '1 year'::interval preceding and '-2 years'::interval following - exclude ties), salary, enroll_date from empsalary; - --- GROUPS tests - -SELECT sum(unique1) over (order by four groups between unbounded preceding and current row), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between unbounded preceding and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between current row and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 1 preceding and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 1 following and unbounded following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between unbounded preceding and 2 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 2 preceding and 1 preceding), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 2 preceding and 1 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 0 preceding and 0 following), - unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 2 preceding and 1 following - exclude current row), unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 2 preceding and 1 following - exclude group), unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (order by four groups between 2 preceding and 1 following - exclude ties), unique1, four -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (partition by ten - order by four groups between 0 preceding and 0 following),unique1, four, ten -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (partition by ten - order by four groups between 0 preceding and 0 following exclude current row), unique1, four, ten -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (partition by ten - order by four groups between 0 preceding and 0 following exclude group), unique1, four, ten -FROM tenk1 WHERE unique1 < 10; - -SELECT sum(unique1) over (partition by ten - order by four groups between 0 preceding and 0 following exclude ties), unique1, four, ten -FROM tenk1 WHERE unique1 < 10; - -select first_value(salary) over(order by enroll_date groups between 1 preceding and 1 following), - lead(salary) over(order by enroll_date groups between 1 preceding and 1 following), - nth_value(salary, 1) over(order by enroll_date groups between 1 preceding and 1 following), - salary, enroll_date from empsalary; - -select last_value(salary) over(order by enroll_date groups between 1 preceding and 1 following), - lag(salary) over(order by enroll_date groups between 1 preceding and 1 following), - salary, enroll_date from empsalary; - -select first_value(salary) over(order by enroll_date groups between 1 following and 3 following - exclude current row), - lead(salary) over(order by enroll_date groups between 1 following and 3 following exclude ties), - nth_value(salary, 1) over(order by enroll_date groups between 1 following and 3 following - exclude ties), - salary, enroll_date from empsalary; - -select last_value(salary) over(order by enroll_date groups between 1 following and 3 following - exclude group), - lag(salary) over(order by enroll_date groups between 1 following and 3 following exclude group), - salary, enroll_date from empsalary; - --- Show differences in offset interpretation between ROWS, RANGE, and GROUPS -WITH cte (x) AS ( - SELECT * FROM generate_series(1, 35, 2) -) -SELECT x, (sum(x) over w) -FROM cte -WINDOW w AS (ORDER BY x rows between 1 preceding and 1 following); - -WITH cte (x) AS ( - SELECT * FROM generate_series(1, 35, 2) -) -SELECT x, (sum(x) over w) -FROM cte -WINDOW w AS (ORDER BY x range between 1 preceding and 1 following); - -WITH cte (x) AS ( - SELECT * FROM generate_series(1, 35, 2) -) -SELECT x, (sum(x) over w) -FROM cte -WINDOW w AS (ORDER BY x groups between 1 preceding and 1 following); - -WITH cte (x) AS ( - select 1 union all select 1 union all select 1 union all - SELECT * FROM generate_series(5, 49, 2) -) -SELECT x, (sum(x) over w) -FROM cte -WINDOW w AS (ORDER BY x rows between 1 preceding and 1 following); - -WITH cte (x) AS ( - select 1 union all select 1 union all select 1 union all - SELECT * FROM generate_series(5, 49, 2) -) -SELECT x, (sum(x) over w) -FROM cte -WINDOW w AS (ORDER BY x range between 1 preceding and 1 following); - -WITH cte (x) AS ( - select 1 union all select 1 union all select 1 union all - SELECT * FROM generate_series(5, 49, 2) -) -SELECT x, (sum(x) over w) -FROM cte -WINDOW w AS (ORDER BY x groups between 1 preceding and 1 following); - --- with UNION -SELECT count(*) OVER (PARTITION BY four) FROM (SELECT * FROM tenk1 UNION ALL SELECT * FROM tenk2)s LIMIT 0; - --- check some degenerate cases -create temp table t1 (f1 int, f2 int8); -insert into t1 values (1,1),(1,2),(2,2); - -select f1, sum(f1) over (partition by f1 - range between 1 preceding and 1 following) -from t1 where f1 = f2; -- error, must have order by -explain (costs off) -select f1, sum(f1) over (partition by f1 order by f2 - range between 1 preceding and 1 following) -from t1 where f1 = f2; -select f1, sum(f1) over (partition by f1 order by f2 - range between 1 preceding and 1 following) -from t1 where f1 = f2; -select f1, sum(f1) over (partition by f1, f1 order by f2 - range between 2 preceding and 1 preceding) -from t1 where f1 = f2; -select f1, sum(f1) over (partition by f1, f2 order by f2 - range between 1 following and 2 following) -from t1 where f1 = f2; - -select f1, sum(f1) over (partition by f1 - groups between 1 preceding and 1 following) -from t1 where f1 = f2; -- error, must have order by -explain (costs off) -select f1, sum(f1) over (partition by f1 order by f2 - groups between 1 preceding and 1 following) -from t1 where f1 = f2; -select f1, sum(f1) over (partition by f1 order by f2 - groups between 1 preceding and 1 following) -from t1 where f1 = f2; -select f1, sum(f1) over (partition by f1, f1 order by f2 - groups between 2 preceding and 1 preceding) -from t1 where f1 = f2; -select f1, sum(f1) over (partition by f1, f2 order by f2 - groups between 1 following and 2 following) -from t1 where f1 = f2; - --- ordering by a non-integer constant is allowed -SELECT rank() OVER (ORDER BY length('abc')); - --- can't order by another window function -SELECT rank() OVER (ORDER BY rank() OVER (ORDER BY random())); - --- some other errors -SELECT * FROM empsalary WHERE row_number() OVER (ORDER BY salary) < 10; - -SELECT * FROM empsalary INNER JOIN tenk1 ON row_number() OVER (ORDER BY salary) < 10; - -SELECT rank() OVER (ORDER BY 1), count(*) FROM empsalary GROUP BY 1; - -SELECT * FROM rank() OVER (ORDER BY random()); - -DELETE FROM empsalary WHERE (rank() OVER (ORDER BY random())) > 10; - -DELETE FROM empsalary RETURNING rank() OVER (ORDER BY random()); - -SELECT count(*) OVER w FROM tenk1 WINDOW w AS (ORDER BY unique1), w AS (ORDER BY unique1); - -SELECT rank() OVER (PARTITION BY four, ORDER BY ten) FROM tenk1; - -SELECT count() OVER () FROM tenk1; - -SELECT generate_series(1, 100) OVER () FROM empsalary; - -SELECT ntile(0) OVER (ORDER BY ten), ten, four FROM tenk1; - -SELECT nth_value(four, 0) OVER (ORDER BY ten), ten, four FROM tenk1; - --- filter - -SELECT sum(salary), row_number() OVER (ORDER BY depname), sum( - sum(salary) FILTER (WHERE enroll_date > '2007-01-01') -) FILTER (WHERE depname <> 'sales') OVER (ORDER BY depname DESC) AS "filtered_sum", - depname -FROM empsalary GROUP BY depname; - --- Test pushdown of quals into a subquery containing window functions - --- pushdown is safe because all PARTITION BY clauses include depname: -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT depname, - sum(salary) OVER (PARTITION BY depname) depsalary, - min(salary) OVER (PARTITION BY depname || 'A', depname) depminsalary - FROM empsalary) emp -WHERE depname = 'sales'; - --- pushdown is unsafe because there's a PARTITION BY clause without depname: -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT depname, - sum(salary) OVER (PARTITION BY enroll_date) enroll_salary, - min(salary) OVER (PARTITION BY depname) depminsalary - FROM empsalary) emp -WHERE depname = 'sales'; - --- Test window function run conditions are properly pushed down into the --- WindowAgg -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - row_number() OVER (ORDER BY empno) rn - FROM empsalary) emp -WHERE rn < 3; - --- The following 3 statements should result the same result. -SELECT * FROM - (SELECT empno, - row_number() OVER (ORDER BY empno) rn - FROM empsalary) emp -WHERE rn < 3; - -SELECT * FROM - (SELECT empno, - row_number() OVER (ORDER BY empno) rn - FROM empsalary) emp -WHERE 3 > rn; - -SELECT * FROM - (SELECT empno, - row_number() OVER (ORDER BY empno) rn - FROM empsalary) emp -WHERE 2 >= rn; - --- Ensure r <= 3 is pushed down into the run condition of the window agg -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - rank() OVER (ORDER BY salary DESC) r - FROM empsalary) emp -WHERE r <= 3; - -SELECT * FROM - (SELECT empno, - salary, - rank() OVER (ORDER BY salary DESC) r - FROM empsalary) emp -WHERE r <= 3; - --- Ensure dr = 1 is converted to dr <= 1 to get all rows leading up to dr = 1 -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - dense_rank() OVER (ORDER BY salary DESC) dr - FROM empsalary) emp -WHERE dr = 1; - -SELECT * FROM - (SELECT empno, - salary, - dense_rank() OVER (ORDER BY salary DESC) dr - FROM empsalary) emp -WHERE dr = 1; - --- Check COUNT() and COUNT(*) -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY salary DESC) c - FROM empsalary) emp -WHERE c <= 3; - -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY salary DESC) c - FROM empsalary) emp -WHERE c <= 3; - -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(empno) OVER (ORDER BY salary DESC) c - FROM empsalary) emp -WHERE c <= 3; - -SELECT * FROM - (SELECT empno, - salary, - count(empno) OVER (ORDER BY salary DESC) c - FROM empsalary) emp -WHERE c <= 3; - -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY salary DESC ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) c - FROM empsalary) emp -WHERE c >= 3; - -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER () c - FROM empsalary) emp -WHERE 11 <= c; - -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY salary DESC) c, - dense_rank() OVER (ORDER BY salary DESC) dr - FROM empsalary) emp -WHERE dr = 1; - --- Ensure we get a run condition when there's a PARTITION BY clause -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - depname, - row_number() OVER (PARTITION BY depname ORDER BY empno) rn - FROM empsalary) emp -WHERE rn < 3; - --- and ensure we get the correct results from the above plan -SELECT * FROM - (SELECT empno, - depname, - row_number() OVER (PARTITION BY depname ORDER BY empno) rn - FROM empsalary) emp -WHERE rn < 3; - --- ensure that "unused" subquery columns are not removed when the column only --- exists in the run condition -EXPLAIN (COSTS OFF) -SELECT empno, depname FROM - (SELECT empno, - depname, - row_number() OVER (PARTITION BY depname ORDER BY empno) rn - FROM empsalary) emp -WHERE rn < 3; - --- likewise with count(empno) instead of row_number() -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - depname, - salary, - count(empno) OVER (PARTITION BY depname ORDER BY salary DESC) c - FROM empsalary) emp -WHERE c <= 3; - --- and again, check the results are what we expect. -SELECT * FROM - (SELECT empno, - depname, - salary, - count(empno) OVER (PARTITION BY depname ORDER BY salary DESC) c - FROM empsalary) emp -WHERE c <= 3; - --- Some more complex cases with multiple window clauses -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT *, - count(salary) OVER (PARTITION BY depname || '') c1, -- w1 - row_number() OVER (PARTITION BY depname) rn, -- w2 - count(*) OVER (PARTITION BY depname) c2, -- w2 - count(*) OVER (PARTITION BY '' || depname) c3 -- w3 - FROM empsalary -) e WHERE rn <= 1 AND c1 <= 3; - --- Ensure we correctly filter out all of the run conditions from each window -SELECT * FROM - (SELECT *, - count(salary) OVER (PARTITION BY depname || '') c1, -- w1 - row_number() OVER (PARTITION BY depname) rn, -- w2 - count(*) OVER (PARTITION BY depname) c2, -- w2 - count(*) OVER (PARTITION BY '' || depname) c3 -- w3 - FROM empsalary -) e WHERE rn <= 1 AND c1 <= 3; - --- Tests to ensure we don't push down the run condition when it's not valid to --- do so. - --- Ensure we don't push down when the frame options show that the window --- function is not monotonically increasing -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY salary DESC ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) c - FROM empsalary) emp -WHERE c <= 3; - --- Ensure we don't push down when the window function's monotonic properties --- don't match that of the clauses. -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY salary) c - FROM empsalary) emp -WHERE 3 <= c; - --- Ensure we don't pushdown when there are multiple window clauses to evaluate -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT empno, - salary, - count(*) OVER (ORDER BY empno DESC) c, - dense_rank() OVER (ORDER BY salary DESC) dr - FROM empsalary) emp -WHERE dr = 1; - --- Test Sort node collapsing -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT depname, - sum(salary) OVER (PARTITION BY depname order by empno) depsalary, - min(salary) OVER (PARTITION BY depname, empno order by enroll_date) depminsalary - FROM empsalary) emp -WHERE depname = 'sales'; - --- Test Sort node reordering -EXPLAIN (COSTS OFF) -SELECT - lead(1) OVER (PARTITION BY depname ORDER BY salary, enroll_date), - lag(1) OVER (PARTITION BY depname ORDER BY salary,enroll_date,empno) -FROM empsalary; - --- Test incremental sorting -EXPLAIN (COSTS OFF) -SELECT * FROM - (SELECT depname, - empno, - salary, - enroll_date, - row_number() OVER (PARTITION BY depname ORDER BY enroll_date) AS first_emp, - row_number() OVER (PARTITION BY depname ORDER BY enroll_date DESC) AS last_emp - FROM empsalary) emp -WHERE first_emp = 1 OR last_emp = 1; - -SELECT * FROM - (SELECT depname, - empno, - salary, - enroll_date, - row_number() OVER (PARTITION BY depname ORDER BY enroll_date) AS first_emp, - row_number() OVER (PARTITION BY depname ORDER BY enroll_date DESC) AS last_emp - FROM empsalary) emp -WHERE first_emp = 1 OR last_emp = 1; - --- cleanup -DROP TABLE empsalary; - --- test user-defined window function with named args and default args -CREATE FUNCTION nth_value_def(val anyelement, n integer = 1) RETURNS anyelement - LANGUAGE internal WINDOW IMMUTABLE STRICT AS 'window_nth_value'; - -SELECT nth_value_def(n := 2, val := ten) OVER (PARTITION BY four), ten, four - FROM (SELECT * FROM tenk1 WHERE unique2 < 10 ORDER BY four, ten) s; - -SELECT nth_value_def(ten) OVER (PARTITION BY four), ten, four - FROM (SELECT * FROM tenk1 WHERE unique2 < 10 ORDER BY four, ten) s; - --- --- Test the basic moving-aggregate machinery --- - --- create aggregates that record the series of transform calls (these are --- intentionally not true inverses) - -CREATE FUNCTION logging_sfunc_nonstrict(text, anyelement) RETURNS text AS -$$ SELECT COALESCE($1, '') || '*' || quote_nullable($2) $$ -LANGUAGE SQL IMMUTABLE; - -CREATE FUNCTION logging_msfunc_nonstrict(text, anyelement) RETURNS text AS -$$ SELECT COALESCE($1, '') || '+' || quote_nullable($2) $$ -LANGUAGE SQL IMMUTABLE; - -CREATE FUNCTION logging_minvfunc_nonstrict(text, anyelement) RETURNS text AS -$$ SELECT $1 || '-' || quote_nullable($2) $$ -LANGUAGE SQL IMMUTABLE; - -CREATE AGGREGATE logging_agg_nonstrict (anyelement) -( - stype = text, - sfunc = logging_sfunc_nonstrict, - mstype = text, - msfunc = logging_msfunc_nonstrict, - minvfunc = logging_minvfunc_nonstrict -); - -CREATE AGGREGATE logging_agg_nonstrict_initcond (anyelement) -( - stype = text, - sfunc = logging_sfunc_nonstrict, - mstype = text, - msfunc = logging_msfunc_nonstrict, - minvfunc = logging_minvfunc_nonstrict, - initcond = 'I', - minitcond = 'MI' -); - -CREATE FUNCTION logging_sfunc_strict(text, anyelement) RETURNS text AS -$$ SELECT $1 || '*' || quote_nullable($2) $$ -LANGUAGE SQL STRICT IMMUTABLE; - -CREATE FUNCTION logging_msfunc_strict(text, anyelement) RETURNS text AS -$$ SELECT $1 || '+' || quote_nullable($2) $$ -LANGUAGE SQL STRICT IMMUTABLE; - -CREATE FUNCTION logging_minvfunc_strict(text, anyelement) RETURNS text AS -$$ SELECT $1 || '-' || quote_nullable($2) $$ -LANGUAGE SQL STRICT IMMUTABLE; - -CREATE AGGREGATE logging_agg_strict (text) -( - stype = text, - sfunc = logging_sfunc_strict, - mstype = text, - msfunc = logging_msfunc_strict, - minvfunc = logging_minvfunc_strict -); - -CREATE AGGREGATE logging_agg_strict_initcond (anyelement) -( - stype = text, - sfunc = logging_sfunc_strict, - mstype = text, - msfunc = logging_msfunc_strict, - minvfunc = logging_minvfunc_strict, - initcond = 'I', - minitcond = 'MI' -); - --- test strict and non-strict cases -SELECT - p::text || ',' || i::text || ':' || COALESCE(v::text, 'NULL') AS row, - logging_agg_nonstrict(v) over wnd as nstrict, - logging_agg_nonstrict_initcond(v) over wnd as nstrict_init, - logging_agg_strict(v::text) over wnd as strict, - logging_agg_strict_initcond(v) over wnd as strict_init -FROM (VALUES - (1, 1, NULL), - (1, 2, 'a'), - (1, 3, 'b'), - (1, 4, NULL), - (1, 5, NULL), - (1, 6, 'c'), - (2, 1, NULL), - (2, 2, 'x'), - (3, 1, 'z') -) AS t(p, i, v) -WINDOW wnd AS (PARTITION BY P ORDER BY i ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) -ORDER BY p, i; - --- and again, but with filter -SELECT - p::text || ',' || i::text || ':' || - CASE WHEN f THEN COALESCE(v::text, 'NULL') ELSE '-' END as row, - logging_agg_nonstrict(v) filter(where f) over wnd as nstrict_filt, - logging_agg_nonstrict_initcond(v) filter(where f) over wnd as nstrict_init_filt, - logging_agg_strict(v::text) filter(where f) over wnd as strict_filt, - logging_agg_strict_initcond(v) filter(where f) over wnd as strict_init_filt -FROM (VALUES - (1, 1, true, NULL), - (1, 2, false, 'a'), - (1, 3, true, 'b'), - (1, 4, false, NULL), - (1, 5, false, NULL), - (1, 6, false, 'c'), - (2, 1, false, NULL), - (2, 2, true, 'x'), - (3, 1, true, 'z') -) AS t(p, i, f, v) -WINDOW wnd AS (PARTITION BY p ORDER BY i ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) -ORDER BY p, i; - --- test that volatile arguments disable moving-aggregate mode -SELECT - i::text || ':' || COALESCE(v::text, 'NULL') as row, - logging_agg_strict(v::text) - over wnd as inverse, - logging_agg_strict(v::text || CASE WHEN random() < 0 then '?' ELSE '' END) - over wnd as noinverse -FROM (VALUES - (1, 'a'), - (2, 'b'), - (3, 'c') -) AS t(i, v) -WINDOW wnd AS (ORDER BY i ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) -ORDER BY i; - -SELECT - i::text || ':' || COALESCE(v::text, 'NULL') as row, - logging_agg_strict(v::text) filter(where true) - over wnd as inverse, - logging_agg_strict(v::text) filter(where random() >= 0) - over wnd as noinverse -FROM (VALUES - (1, 'a'), - (2, 'b'), - (3, 'c') -) AS t(i, v) -WINDOW wnd AS (ORDER BY i ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) -ORDER BY i; - --- test that non-overlapping windows don't use inverse transitions -SELECT - logging_agg_strict(v::text) OVER wnd -FROM (VALUES - (1, 'a'), - (2, 'b'), - (3, 'c') -) AS t(i, v) -WINDOW wnd AS (ORDER BY i ROWS BETWEEN CURRENT ROW AND CURRENT ROW) -ORDER BY i; - --- test that returning NULL from the inverse transition functions --- restarts the aggregation from scratch. The second aggregate is supposed --- to test cases where only some aggregates restart, the third one checks --- that one aggregate restarting doesn't cause others to restart. - -CREATE FUNCTION sum_int_randrestart_minvfunc(int4, int4) RETURNS int4 AS -$$ SELECT CASE WHEN random() < 0.2 THEN NULL ELSE $1 - $2 END $$ -LANGUAGE SQL STRICT; - -CREATE AGGREGATE sum_int_randomrestart (int4) -( - stype = int4, - sfunc = int4pl, - mstype = int4, - msfunc = int4pl, - minvfunc = sum_int_randrestart_minvfunc -); - -WITH -vs AS ( - SELECT i, (random() * 100)::int4 AS v - FROM generate_series(1, 100) AS i -), -sum_following AS ( - SELECT i, SUM(v) OVER - (ORDER BY i DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS s - FROM vs -) -SELECT DISTINCT - sum_following.s = sum_int_randomrestart(v) OVER fwd AS eq1, - -sum_following.s = sum_int_randomrestart(-v) OVER fwd AS eq2, - 100*3+(vs.i-1)*3 = length(logging_agg_nonstrict(''::text) OVER fwd) AS eq3 -FROM vs -JOIN sum_following ON sum_following.i = vs.i -WINDOW fwd AS ( - ORDER BY vs.i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING -); - --- --- Test various built-in aggregates that have moving-aggregate support --- - --- test inverse transition functions handle NULLs properly -SELECT i,AVG(v::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,AVG(v::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,AVG(v::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,AVG(v::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1.5),(2,2.5),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,AVG(v::interval) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,'1 sec'),(2,'2 sec'),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::money) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,'1.10'),(2,'2.20'),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::interval) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,'1 sec'),(2,'2 sec'),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1.1),(2,2.2),(3,NULL),(4,NULL)) t(i,v); - -SELECT SUM(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1.01),(2,2),(3,3)) v(i,n); - -SELECT i,COUNT(v) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,COUNT(*) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT VAR_POP(n::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_POP(n::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_POP(n::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_POP(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_SAMP(n::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_SAMP(n::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_SAMP(n::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VAR_SAMP(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VARIANCE(n::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VARIANCE(n::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VARIANCE(n::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT VARIANCE(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT STDDEV_POP(n::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_POP(n::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_POP(n::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_POP(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_SAMP(n::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_SAMP(n::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_SAMP(n::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV_SAMP(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(1,NULL),(2,600),(3,470),(4,170),(5,430),(6,300)) r(i,n); - -SELECT STDDEV(n::bigint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(0,NULL),(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT STDDEV(n::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(0,NULL),(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT STDDEV(n::smallint) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(0,NULL),(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - -SELECT STDDEV(n::numeric) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) - FROM (VALUES(0,NULL),(1,600),(2,470),(3,170),(4,430),(5,300)) r(i,n); - --- test that inverse transition functions work with various frame options -SELECT i,SUM(v::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND CURRENT ROW) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::int) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,NULL),(4,NULL)) t(i,v); - -SELECT i,SUM(v::int) OVER (ORDER BY i ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) - FROM (VALUES(1,1),(2,2),(3,3),(4,4)) t(i,v); - --- ensure aggregate over numeric properly recovers from NaN values -SELECT a, b, - SUM(b) OVER(ORDER BY A ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) -FROM (VALUES(1,1::numeric),(2,2),(3,'NaN'),(4,3),(5,4)) t(a,b); - --- It might be tempting for someone to add an inverse trans function for --- float and double precision. This should not be done as it can give incorrect --- results. This test should fail if anyone ever does this without thinking too --- hard about it. -SELECT to_char(SUM(n::float8) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING),'999999999999999999999D9') - FROM (VALUES(1,1e20),(2,1)) n(i,n); - -SELECT i, b, bool_and(b) OVER w, bool_or(b) OVER w - FROM (VALUES (1,true), (2,true), (3,false), (4,false), (5,true)) v(i,b) - WINDOW w AS (ORDER BY i ROWS BETWEEN CURRENT ROW AND 1 FOLLOWING); - --- Tests for problems with failure to walk or mutate expressions --- within window frame clauses. - --- test walker (fails with collation error if expressions are not walked) -SELECT array_agg(i) OVER w - FROM generate_series(1,5) i -WINDOW w AS (ORDER BY i ROWS BETWEEN (('foo' < 'foobar')::integer) PRECEDING AND CURRENT ROW); - --- test mutator (fails when inlined if expressions are not mutated) -CREATE FUNCTION pg_temp.f(group_size BIGINT) RETURNS SETOF integer[] -AS $$ - SELECT array_agg(s) OVER w - FROM generate_series(1,5) s - WINDOW w AS (ORDER BY s ROWS BETWEEN CURRENT ROW AND GROUP_SIZE FOLLOWING) -$$ LANGUAGE SQL STABLE; - -EXPLAIN (costs off) SELECT * FROM pg_temp.f(2); -SELECT * FROM pg_temp.f(2); diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwith.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwith.sql deleted file mode 100644 index 5c52561a8a..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwith.sql +++ /dev/null @@ -1,1570 +0,0 @@ --- --- Tests for common table expressions (WITH query, ... SELECT ...) --- - --- Basic WITH -WITH q1(x,y) AS (SELECT 1,2) -SELECT * FROM q1, q1 AS q2; - --- Multiple uses are evaluated only once -SELECT count(*) FROM ( - WITH q1(x) AS (SELECT random() FROM generate_series(1, 5)) - SELECT * FROM q1 - UNION - SELECT * FROM q1 -) ss; - --- WITH RECURSIVE - --- sum of 1..100 -WITH RECURSIVE t(n) AS ( - VALUES (1) -UNION ALL - SELECT n+1 FROM t WHERE n < 100 -) -SELECT sum(n) FROM t; - -WITH RECURSIVE t(n) AS ( - SELECT (VALUES(1)) -UNION ALL - SELECT n+1 FROM t WHERE n < 5 -) -SELECT * FROM t; - --- UNION DISTINCT requires hashable type -WITH RECURSIVE t(n) AS ( - VALUES (1::money) -UNION - SELECT n+1::money FROM t WHERE n < 100::money -) -SELECT sum(n) FROM t; - --- recursive view -CREATE RECURSIVE VIEW nums (n) AS - VALUES (1) -UNION ALL - SELECT n+1 FROM nums WHERE n < 5; - -SELECT * FROM nums; - -CREATE OR REPLACE RECURSIVE VIEW nums (n) AS - VALUES (1) -UNION ALL - SELECT n+1 FROM nums WHERE n < 6; - -SELECT * FROM nums; - --- This is an infinite loop with UNION ALL, but not with UNION -WITH RECURSIVE t(n) AS ( - SELECT 1 -UNION - SELECT 10-n FROM t) -SELECT * FROM t; - --- This'd be an infinite loop, but outside query reads only as much as needed -WITH RECURSIVE t(n) AS ( - VALUES (1) -UNION ALL - SELECT n+1 FROM t) -SELECT * FROM t LIMIT 10; - --- UNION case should have same property -WITH RECURSIVE t(n) AS ( - SELECT 1 -UNION - SELECT n+1 FROM t) -SELECT * FROM t LIMIT 10; - --- Test behavior with an unknown-type literal in the WITH -WITH q AS (SELECT 'foo' AS x) -SELECT x, pg_typeof(x) FROM q; - -WITH RECURSIVE t(n) AS ( - SELECT 'foo' -UNION ALL - SELECT n || ' bar' FROM t WHERE length(n) < 20 -) -SELECT n, pg_typeof(n) FROM t; - --- In a perfect world, this would work and resolve the literal as int ... --- but for now, we have to be content with resolving to text too soon. -WITH RECURSIVE t(n) AS ( - SELECT '7' -UNION ALL - SELECT n+1 FROM t WHERE n < 10 -) -SELECT n, pg_typeof(n) FROM t; - --- Deeply nested WITH caused a list-munging problem in v13 --- Detection of cross-references and self-references -WITH RECURSIVE w1(c1) AS - (WITH w2(c2) AS - (WITH w3(c3) AS - (WITH w4(c4) AS - (WITH w5(c5) AS - (WITH RECURSIVE w6(c6) AS - (WITH w6(c6) AS - (WITH w8(c8) AS - (SELECT 1) - SELECT * FROM w8) - SELECT * FROM w6) - SELECT * FROM w6) - SELECT * FROM w5) - SELECT * FROM w4) - SELECT * FROM w3) - SELECT * FROM w2) -SELECT * FROM w1; --- Detection of invalid self-references -WITH RECURSIVE outermost(x) AS ( - SELECT 1 - UNION (WITH innermost1 AS ( - SELECT 2 - UNION (WITH innermost2 AS ( - SELECT 3 - UNION (WITH innermost3 AS ( - SELECT 4 - UNION (WITH innermost4 AS ( - SELECT 5 - UNION (WITH innermost5 AS ( - SELECT 6 - UNION (WITH innermost6 AS - (SELECT 7) - SELECT * FROM innermost6)) - SELECT * FROM innermost5)) - SELECT * FROM innermost4)) - SELECT * FROM innermost3)) - SELECT * FROM innermost2)) - SELECT * FROM outermost - UNION SELECT * FROM innermost1) - ) - SELECT * FROM outermost ORDER BY 1; - --- --- Some examples with a tree --- --- department structure represented here is as follows: --- --- ROOT-+->A-+->B-+->C --- | | --- | +->D-+->F --- +->E-+->G - -CREATE TEMP TABLE department ( - id INTEGER PRIMARY KEY, -- department ID - parent_department INTEGER REFERENCES department, -- upper department ID - name TEXT -- department name -); - -INSERT INTO department VALUES (0, NULL, 'ROOT'); -INSERT INTO department VALUES (1, 0, 'A'); -INSERT INTO department VALUES (2, 1, 'B'); -INSERT INTO department VALUES (3, 2, 'C'); -INSERT INTO department VALUES (4, 2, 'D'); -INSERT INTO department VALUES (5, 0, 'E'); -INSERT INTO department VALUES (6, 4, 'F'); -INSERT INTO department VALUES (7, 5, 'G'); - - --- extract all departments under 'A'. Result should be A, B, C, D and F -WITH RECURSIVE subdepartment AS -( - -- non recursive term - SELECT name as root_name, * FROM department WHERE name = 'A' - - UNION ALL - - -- recursive term - SELECT sd.root_name, d.* FROM department AS d, subdepartment AS sd - WHERE d.parent_department = sd.id -) -SELECT * FROM subdepartment ORDER BY name; - --- extract all departments under 'A' with "level" number -WITH RECURSIVE subdepartment(level, id, parent_department, name) AS -( - -- non recursive term - SELECT 1, * FROM department WHERE name = 'A' - - UNION ALL - - -- recursive term - SELECT sd.level + 1, d.* FROM department AS d, subdepartment AS sd - WHERE d.parent_department = sd.id -) -SELECT * FROM subdepartment ORDER BY name; - --- extract all departments under 'A' with "level" number. --- Only shows level 2 or more -WITH RECURSIVE subdepartment(level, id, parent_department, name) AS -( - -- non recursive term - SELECT 1, * FROM department WHERE name = 'A' - - UNION ALL - - -- recursive term - SELECT sd.level + 1, d.* FROM department AS d, subdepartment AS sd - WHERE d.parent_department = sd.id -) -SELECT * FROM subdepartment WHERE level >= 2 ORDER BY name; - --- "RECURSIVE" is ignored if the query has no self-reference -WITH RECURSIVE subdepartment AS -( - -- note lack of recursive UNION structure - SELECT * FROM department WHERE name = 'A' -) -SELECT * FROM subdepartment ORDER BY name; - --- inside subqueries -SELECT count(*) FROM ( - WITH RECURSIVE t(n) AS ( - SELECT 1 UNION ALL SELECT n + 1 FROM t WHERE n < 500 - ) - SELECT * FROM t) AS t WHERE n < ( - SELECT count(*) FROM ( - WITH RECURSIVE t(n) AS ( - SELECT 1 UNION ALL SELECT n + 1 FROM t WHERE n < 100 - ) - SELECT * FROM t WHERE n < 50000 - ) AS t WHERE n < 100); - --- use same CTE twice at different subquery levels -WITH q1(x,y) AS ( - SELECT hundred, sum(ten) FROM tenk1 GROUP BY hundred - ) -SELECT count(*) FROM q1 WHERE y > (SELECT sum(y)/100 FROM q1 qsub); - --- via a VIEW -CREATE TEMPORARY VIEW vsubdepartment AS - WITH RECURSIVE subdepartment AS - ( - -- non recursive term - SELECT * FROM department WHERE name = 'A' - UNION ALL - -- recursive term - SELECT d.* FROM department AS d, subdepartment AS sd - WHERE d.parent_department = sd.id - ) - SELECT * FROM subdepartment; - -SELECT * FROM vsubdepartment ORDER BY name; - --- Check reverse listing -SELECT pg_get_viewdef('vsubdepartment'::regclass); -SELECT pg_get_viewdef('vsubdepartment'::regclass, true); - --- Another reverse-listing example -CREATE VIEW sums_1_100 AS -WITH RECURSIVE t(n) AS ( - VALUES (1) -UNION ALL - SELECT n+1 FROM t WHERE n < 100 -) -SELECT sum(n) FROM t; - -\d+ sums_1_100 - --- corner case in which sub-WITH gets initialized first -with recursive q as ( - select * from department - union all - (with x as (select * from q) - select * from x) - ) -select * from q limit 24; - -with recursive q as ( - select * from department - union all - (with recursive x as ( - select * from department - union all - (select * from q union all select * from x) - ) - select * from x) - ) -select * from q limit 32; - --- recursive term has sub-UNION -WITH RECURSIVE t(i,j) AS ( - VALUES (1,2) - UNION ALL - SELECT t2.i, t.j+1 FROM - (SELECT 2 AS i UNION ALL SELECT 3 AS i) AS t2 - JOIN t ON (t2.i = t.i+1)) - - SELECT * FROM t; - --- --- different tree example --- -CREATE TEMPORARY TABLE tree( - id INTEGER PRIMARY KEY, - parent_id INTEGER REFERENCES tree(id) -); - -INSERT INTO tree -VALUES (1, NULL), (2, 1), (3,1), (4,2), (5,2), (6,2), (7,3), (8,3), - (9,4), (10,4), (11,7), (12,7), (13,7), (14, 9), (15,11), (16,11); - --- --- get all paths from "second level" nodes to leaf nodes --- -WITH RECURSIVE t(id, path) AS ( - VALUES(1,ARRAY[]::integer[]) -UNION ALL - SELECT tree.id, t.path || tree.id - FROM tree JOIN t ON (tree.parent_id = t.id) -) -SELECT t1.*, t2.* FROM t AS t1 JOIN t AS t2 ON - (t1.path[1] = t2.path[1] AND - array_upper(t1.path,1) = 1 AND - array_upper(t2.path,1) > 1) - ORDER BY t1.id, t2.id; - --- just count 'em -WITH RECURSIVE t(id, path) AS ( - VALUES(1,ARRAY[]::integer[]) -UNION ALL - SELECT tree.id, t.path || tree.id - FROM tree JOIN t ON (tree.parent_id = t.id) -) -SELECT t1.id, count(t2.*) FROM t AS t1 JOIN t AS t2 ON - (t1.path[1] = t2.path[1] AND - array_upper(t1.path,1) = 1 AND - array_upper(t2.path,1) > 1) - GROUP BY t1.id - ORDER BY t1.id; - --- this variant tickled a whole-row-variable bug in 8.4devel -WITH RECURSIVE t(id, path) AS ( - VALUES(1,ARRAY[]::integer[]) -UNION ALL - SELECT tree.id, t.path || tree.id - FROM tree JOIN t ON (tree.parent_id = t.id) -) -SELECT t1.id, t2.path, t2 FROM t AS t1 JOIN t AS t2 ON -(t1.id=t2.id); - --- SEARCH clause - -create temp table graph0( f int, t int, label text ); - -insert into graph0 values - (1, 2, 'arc 1 -> 2'), - (1, 3, 'arc 1 -> 3'), - (2, 3, 'arc 2 -> 3'), - (1, 4, 'arc 1 -> 4'), - (4, 5, 'arc 4 -> 5'); - -explain (verbose, costs off) -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t set seq -select * from search_graph order by seq; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t set seq -select * from search_graph order by seq; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union distinct - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t set seq -select * from search_graph order by seq; - -explain (verbose, costs off) -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search breadth first by f, t set seq -select * from search_graph order by seq; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search breadth first by f, t set seq -select * from search_graph order by seq; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union distinct - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search breadth first by f, t set seq -select * from search_graph order by seq; - --- various syntax errors -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by foo, tar set seq -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t set label -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t, f set seq -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t set seq -select * from search_graph order by seq; - -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - (select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t) -) search depth first by f, t set seq -select * from search_graph order by seq; - --- check that we distinguish same CTE name used at different levels --- (this case could be supported, perhaps, but it isn't today) -with recursive x(col) as ( - select 1 - union - (with x as (select * from x) - select * from x) -) search depth first by col set seq -select * from x; - --- test ruleutils and view expansion -create temp view v_search as -with recursive search_graph(f, t, label) as ( - select * from graph0 g - union all - select g.* - from graph0 g, search_graph sg - where g.f = sg.t -) search depth first by f, t set seq -select f, t, label from search_graph; - -select pg_get_viewdef('v_search'); - -select * from v_search; - --- --- test cycle detection --- -create temp table graph( f int, t int, label text ); - -insert into graph values - (1, 2, 'arc 1 -> 2'), - (1, 3, 'arc 1 -> 3'), - (2, 3, 'arc 2 -> 3'), - (1, 4, 'arc 1 -> 4'), - (4, 5, 'arc 4 -> 5'), - (5, 1, 'arc 5 -> 1'); - -with recursive search_graph(f, t, label, is_cycle, path) as ( - select *, false, array[row(g.f, g.t)] from graph g - union all - select g.*, row(g.f, g.t) = any(path), path || row(g.f, g.t) - from graph g, search_graph sg - where g.f = sg.t and not is_cycle -) -select * from search_graph; - --- UNION DISTINCT exercises row type hashing support -with recursive search_graph(f, t, label, is_cycle, path) as ( - select *, false, array[row(g.f, g.t)] from graph g - union distinct - select g.*, row(g.f, g.t) = any(path), path || row(g.f, g.t) - from graph g, search_graph sg - where g.f = sg.t and not is_cycle -) -select * from search_graph; - --- ordering by the path column has same effect as SEARCH DEPTH FIRST -with recursive search_graph(f, t, label, is_cycle, path) as ( - select *, false, array[row(g.f, g.t)] from graph g - union all - select g.*, row(g.f, g.t) = any(path), path || row(g.f, g.t) - from graph g, search_graph sg - where g.f = sg.t and not is_cycle -) -select * from search_graph order by path; - --- CYCLE clause - -explain (verbose, costs off) -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union distinct - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle to 'Y' default 'N' using path -select * from search_graph; - --- multiple CTEs -with recursive -graph(f, t, label) as ( - values (1, 2, 'arc 1 -> 2'), - (1, 3, 'arc 1 -> 3'), - (2, 3, 'arc 2 -> 3'), - (1, 4, 'arc 1 -> 4'), - (4, 5, 'arc 4 -> 5'), - (5, 1, 'arc 5 -> 1') -), -search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle to true default false using path -select f, t, label from search_graph; - --- star expansion -with recursive a as ( - select 1 as b - union all - select * from a -) cycle b set c using p -select * from a; - --- search+cycle -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) search depth first by f, t set seq - cycle f, t set is_cycle using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) search breadth first by f, t set seq - cycle f, t set is_cycle using path -select * from search_graph; - --- various syntax errors -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle foo, tar set is_cycle using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle to true default 55 using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle to point '(1,1)' default point '(0,0)' using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set label to true default false using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle to true default false using label -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set foo to true default false using foo -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t, f set is_cycle to true default false using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) search depth first by f, t set foo - cycle f, t set foo to true default false using path -select * from search_graph; - -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) search depth first by f, t set foo - cycle f, t set is_cycle to true default false using foo -select * from search_graph; - --- test ruleutils and view expansion -create temp view v_cycle1 as -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle using path -select f, t, label from search_graph; - -create temp view v_cycle2 as -with recursive search_graph(f, t, label) as ( - select * from graph g - union all - select g.* - from graph g, search_graph sg - where g.f = sg.t -) cycle f, t set is_cycle to 'Y' default 'N' using path -select f, t, label from search_graph; - -select pg_get_viewdef('v_cycle1'); -select pg_get_viewdef('v_cycle2'); - -select * from v_cycle1; -select * from v_cycle2; - --- --- test multiple WITH queries --- -WITH RECURSIVE - y (id) AS (VALUES (1)), - x (id) AS (SELECT * FROM y UNION ALL SELECT id+1 FROM x WHERE id < 5) -SELECT * FROM x; - --- forward reference OK -WITH RECURSIVE - x(id) AS (SELECT * FROM y UNION ALL SELECT id+1 FROM x WHERE id < 5), - y(id) AS (values (1)) - SELECT * FROM x; - -WITH RECURSIVE - x(id) AS - (VALUES (1) UNION ALL SELECT id+1 FROM x WHERE id < 5), - y(id) AS - (VALUES (1) UNION ALL SELECT id+1 FROM y WHERE id < 10) - SELECT y.*, x.* FROM y LEFT JOIN x USING (id); - -WITH RECURSIVE - x(id) AS - (VALUES (1) UNION ALL SELECT id+1 FROM x WHERE id < 5), - y(id) AS - (VALUES (1) UNION ALL SELECT id+1 FROM x WHERE id < 10) - SELECT y.*, x.* FROM y LEFT JOIN x USING (id); - -WITH RECURSIVE - x(id) AS - (SELECT 1 UNION ALL SELECT id+1 FROM x WHERE id < 3 ), - y(id) AS - (SELECT * FROM x UNION ALL SELECT * FROM x), - z(id) AS - (SELECT * FROM x UNION ALL SELECT id+1 FROM z WHERE id < 10) - SELECT * FROM z; - -WITH RECURSIVE - x(id) AS - (SELECT 1 UNION ALL SELECT id+1 FROM x WHERE id < 3 ), - y(id) AS - (SELECT * FROM x UNION ALL SELECT * FROM x), - z(id) AS - (SELECT * FROM y UNION ALL SELECT id+1 FROM z WHERE id < 10) - SELECT * FROM z; - --- --- Test WITH attached to a data-modifying statement --- - -CREATE TEMPORARY TABLE y (a INTEGER); -INSERT INTO y SELECT generate_series(1, 10); - -WITH t AS ( - SELECT a FROM y -) -INSERT INTO y -SELECT a+20 FROM t RETURNING *; - -SELECT * FROM y; - -WITH t AS ( - SELECT a FROM y -) -UPDATE y SET a = y.a-10 FROM t WHERE y.a > 20 AND t.a = y.a RETURNING y.a; - -SELECT * FROM y; - -WITH RECURSIVE t(a) AS ( - SELECT 11 - UNION ALL - SELECT a+1 FROM t WHERE a < 50 -) -DELETE FROM y USING t WHERE t.a = y.a RETURNING y.a; - -SELECT * FROM y; - -DROP TABLE y; - --- --- error cases --- - -WITH x(n, b) AS (SELECT 1) -SELECT * FROM x; - --- INTERSECT -WITH RECURSIVE x(n) AS (SELECT 1 INTERSECT SELECT n+1 FROM x) - SELECT * FROM x; - -WITH RECURSIVE x(n) AS (SELECT 1 INTERSECT ALL SELECT n+1 FROM x) - SELECT * FROM x; - --- EXCEPT -WITH RECURSIVE x(n) AS (SELECT 1 EXCEPT SELECT n+1 FROM x) - SELECT * FROM x; - -WITH RECURSIVE x(n) AS (SELECT 1 EXCEPT ALL SELECT n+1 FROM x) - SELECT * FROM x; - --- no non-recursive term -WITH RECURSIVE x(n) AS (SELECT n FROM x) - SELECT * FROM x; - --- recursive term in the left hand side (strictly speaking, should allow this) -WITH RECURSIVE x(n) AS (SELECT n FROM x UNION ALL SELECT 1) - SELECT * FROM x; - -CREATE TEMPORARY TABLE y (a INTEGER); -INSERT INTO y SELECT generate_series(1, 10); - --- LEFT JOIN - -WITH RECURSIVE x(n) AS (SELECT a FROM y WHERE a = 1 - UNION ALL - SELECT x.n+1 FROM y LEFT JOIN x ON x.n = y.a WHERE n < 10) -SELECT * FROM x; - --- RIGHT JOIN -WITH RECURSIVE x(n) AS (SELECT a FROM y WHERE a = 1 - UNION ALL - SELECT x.n+1 FROM x RIGHT JOIN y ON x.n = y.a WHERE n < 10) -SELECT * FROM x; - --- FULL JOIN -WITH RECURSIVE x(n) AS (SELECT a FROM y WHERE a = 1 - UNION ALL - SELECT x.n+1 FROM x FULL JOIN y ON x.n = y.a WHERE n < 10) -SELECT * FROM x; - --- subquery -WITH RECURSIVE x(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM x - WHERE n IN (SELECT * FROM x)) - SELECT * FROM x; - --- aggregate functions -WITH RECURSIVE x(n) AS (SELECT 1 UNION ALL SELECT count(*) FROM x) - SELECT * FROM x; - -WITH RECURSIVE x(n) AS (SELECT 1 UNION ALL SELECT sum(n) FROM x) - SELECT * FROM x; - --- ORDER BY -WITH RECURSIVE x(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM x ORDER BY 1) - SELECT * FROM x; - --- LIMIT/OFFSET -WITH RECURSIVE x(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM x LIMIT 10 OFFSET 1) - SELECT * FROM x; - --- FOR UPDATE -WITH RECURSIVE x(n) AS (SELECT 1 UNION ALL SELECT n+1 FROM x FOR UPDATE) - SELECT * FROM x; - --- target list has a recursive query name -WITH RECURSIVE x(id) AS (values (1) - UNION ALL - SELECT (SELECT * FROM x) FROM x WHERE id < 5 -) SELECT * FROM x; - --- mutual recursive query (not implemented) -WITH RECURSIVE - x (id) AS (SELECT 1 UNION ALL SELECT id+1 FROM y WHERE id < 5), - y (id) AS (SELECT 1 UNION ALL SELECT id+1 FROM x WHERE id < 5) -SELECT * FROM x; - --- non-linear recursion is not allowed -WITH RECURSIVE foo(i) AS - (values (1) - UNION ALL - (SELECT i+1 FROM foo WHERE i < 10 - UNION ALL - SELECT i+1 FROM foo WHERE i < 5) -) SELECT * FROM foo; - -WITH RECURSIVE foo(i) AS - (values (1) - UNION ALL - SELECT * FROM - (SELECT i+1 FROM foo WHERE i < 10 - UNION ALL - SELECT i+1 FROM foo WHERE i < 5) AS t -) SELECT * FROM foo; - -WITH RECURSIVE foo(i) AS - (values (1) - UNION ALL - (SELECT i+1 FROM foo WHERE i < 10 - EXCEPT - SELECT i+1 FROM foo WHERE i < 5) -) SELECT * FROM foo; - -WITH RECURSIVE foo(i) AS - (values (1) - UNION ALL - (SELECT i+1 FROM foo WHERE i < 10 - INTERSECT - SELECT i+1 FROM foo WHERE i < 5) -) SELECT * FROM foo; - --- Wrong type induced from non-recursive term -WITH RECURSIVE foo(i) AS - (SELECT i FROM (VALUES(1),(2)) t(i) - UNION ALL - SELECT (i+1)::numeric(10,0) FROM foo WHERE i < 10) -SELECT * FROM foo; - --- rejects different typmod, too (should we allow this?) -WITH RECURSIVE foo(i) AS - (SELECT i::numeric(3,0) FROM (VALUES(1),(2)) t(i) - UNION ALL - SELECT (i+1)::numeric(10,0) FROM foo WHERE i < 10) -SELECT * FROM foo; - --- disallow OLD/NEW reference in CTE -CREATE TEMPORARY TABLE x (n integer); -CREATE RULE r2 AS ON UPDATE TO x DO INSTEAD - WITH t AS (SELECT OLD.*) UPDATE y SET a = t.n FROM t; - --- --- test for bug #4902 --- -with cte(foo) as ( values(42) ) values((select foo from cte)); -with cte(foo) as ( select 42 ) select * from ((select foo from cte)) q; - --- test CTE referencing an outer-level variable (to see that changed-parameter --- signaling still works properly after fixing this bug) -select ( with cte(foo) as ( values(f1) ) - select (select foo from cte) ) -from int4_tbl; - -select ( with cte(foo) as ( values(f1) ) - values((select foo from cte)) ) -from int4_tbl; - --- --- test for nested-recursive-WITH bug --- -WITH RECURSIVE t(j) AS ( - WITH RECURSIVE s(i) AS ( - VALUES (1) - UNION ALL - SELECT i+1 FROM s WHERE i < 10 - ) - SELECT i FROM s - UNION ALL - SELECT j+1 FROM t WHERE j < 10 -) -SELECT * FROM t; - --- --- test WITH attached to intermediate-level set operation --- - -WITH outermost(x) AS ( - SELECT 1 - UNION (WITH innermost as (SELECT 2) - SELECT * FROM innermost - UNION SELECT 3) -) -SELECT * FROM outermost ORDER BY 1; - -WITH outermost(x) AS ( - SELECT 1 - UNION (WITH innermost as (SELECT 2) - SELECT * FROM outermost -- fail - UNION SELECT * FROM innermost) -) -SELECT * FROM outermost ORDER BY 1; - -WITH RECURSIVE outermost(x) AS ( - SELECT 1 - UNION (WITH innermost as (SELECT 2) - SELECT * FROM outermost - UNION SELECT * FROM innermost) -) -SELECT * FROM outermost ORDER BY 1; - -WITH RECURSIVE outermost(x) AS ( - WITH innermost as (SELECT 2 FROM outermost) -- fail - SELECT * FROM innermost - UNION SELECT * from outermost -) -SELECT * FROM outermost ORDER BY 1; - --- --- This test will fail with the old implementation of PARAM_EXEC parameter --- assignment, because the "q1" Var passed down to A's targetlist subselect --- looks exactly like the "A.id" Var passed down to C's subselect, causing --- the old code to give them the same runtime PARAM_EXEC slot. But the --- lifespans of the two parameters overlap, thanks to B also reading A. --- - -with -A as ( select q2 as id, (select q1) as x from int8_tbl ), -B as ( select id, row_number() over (partition by id) as r from A ), -C as ( select A.id, array(select B.id from B where B.id = A.id) from A ) -select * from C; - --- --- Test CTEs read in non-initialization orders --- - -WITH RECURSIVE - tab(id_key,link) AS (VALUES (1,17), (2,17), (3,17), (4,17), (6,17), (5,17)), - iter (id_key, row_type, link) AS ( - SELECT 0, 'base', 17 - UNION ALL ( - WITH remaining(id_key, row_type, link, min) AS ( - SELECT tab.id_key, 'true'::text, iter.link, MIN(tab.id_key) OVER () - FROM tab INNER JOIN iter USING (link) - WHERE tab.id_key > iter.id_key - ), - first_remaining AS ( - SELECT id_key, row_type, link - FROM remaining - WHERE id_key=min - ), - effect AS ( - SELECT tab.id_key, 'new'::text, tab.link - FROM first_remaining e INNER JOIN tab ON e.id_key=tab.id_key - WHERE e.row_type = 'false' - ) - SELECT * FROM first_remaining - UNION ALL SELECT * FROM effect - ) - ) -SELECT * FROM iter; - -WITH RECURSIVE - tab(id_key,link) AS (VALUES (1,17), (2,17), (3,17), (4,17), (6,17), (5,17)), - iter (id_key, row_type, link) AS ( - SELECT 0, 'base', 17 - UNION ( - WITH remaining(id_key, row_type, link, min) AS ( - SELECT tab.id_key, 'true'::text, iter.link, MIN(tab.id_key) OVER () - FROM tab INNER JOIN iter USING (link) - WHERE tab.id_key > iter.id_key - ), - first_remaining AS ( - SELECT id_key, row_type, link - FROM remaining - WHERE id_key=min - ), - effect AS ( - SELECT tab.id_key, 'new'::text, tab.link - FROM first_remaining e INNER JOIN tab ON e.id_key=tab.id_key - WHERE e.row_type = 'false' - ) - SELECT * FROM first_remaining - UNION ALL SELECT * FROM effect - ) - ) -SELECT * FROM iter; - --- --- Data-modifying statements in WITH --- - --- INSERT ... RETURNING -WITH t AS ( - INSERT INTO y - VALUES - (11), - (12), - (13), - (14), - (15), - (16), - (17), - (18), - (19), - (20) - RETURNING * -) -SELECT * FROM t; - -SELECT * FROM y; - --- UPDATE ... RETURNING -WITH t AS ( - UPDATE y - SET a=a+1 - RETURNING * -) -SELECT * FROM t; - -SELECT * FROM y; - --- DELETE ... RETURNING -WITH t AS ( - DELETE FROM y - WHERE a <= 10 - RETURNING * -) -SELECT * FROM t; - -SELECT * FROM y; - --- forward reference -WITH RECURSIVE t AS ( - INSERT INTO y - SELECT a+5 FROM t2 WHERE a > 5 - RETURNING * -), t2 AS ( - UPDATE y SET a=a-11 RETURNING * -) -SELECT * FROM t -UNION ALL -SELECT * FROM t2; - -SELECT * FROM y; - --- unconditional DO INSTEAD rule -CREATE RULE y_rule AS ON DELETE TO y DO INSTEAD - INSERT INTO y VALUES(42) RETURNING *; - -WITH t AS ( - DELETE FROM y RETURNING * -) -SELECT * FROM t; - -SELECT * FROM y; - -DROP RULE y_rule ON y; - --- check merging of outer CTE with CTE in a rule action -CREATE TEMP TABLE bug6051 AS - select i from generate_series(1,3) as t(i); - -SELECT * FROM bug6051; - -WITH t1 AS ( DELETE FROM bug6051 RETURNING * ) -INSERT INTO bug6051 SELECT * FROM t1; - -SELECT * FROM bug6051; - -CREATE TEMP TABLE bug6051_2 (i int); - -CREATE RULE bug6051_ins AS ON INSERT TO bug6051 DO INSTEAD - INSERT INTO bug6051_2 - VALUES(NEW.i); - -WITH t1 AS ( DELETE FROM bug6051 RETURNING * ) -INSERT INTO bug6051 SELECT * FROM t1; - -SELECT * FROM bug6051; -SELECT * FROM bug6051_2; - --- check INSERT...SELECT rule actions are disallowed on commands --- that have modifyingCTEs -CREATE OR REPLACE RULE bug6051_ins AS ON INSERT TO bug6051 DO INSTEAD - INSERT INTO bug6051_2 - SELECT NEW.i; - -WITH t1 AS ( DELETE FROM bug6051 RETURNING * ) -INSERT INTO bug6051 SELECT * FROM t1; - --- silly example to verify that hasModifyingCTE flag is propagated -CREATE TEMP TABLE bug6051_3 AS - SELECT a FROM generate_series(11,13) AS a; - -CREATE RULE bug6051_3_ins AS ON INSERT TO bug6051_3 DO INSTEAD - SELECT i FROM bug6051_2; - -BEGIN; SET LOCAL force_parallel_mode = on; - -WITH t1 AS ( DELETE FROM bug6051_3 RETURNING * ) - INSERT INTO bug6051_3 SELECT * FROM t1; - -COMMIT; - -SELECT * FROM bug6051_3; - --- check case where CTE reference is removed due to optimization -EXPLAIN (VERBOSE, COSTS OFF) -SELECT q1 FROM -( - WITH t_cte AS (SELECT * FROM int8_tbl t) - SELECT q1, (SELECT q2 FROM t_cte WHERE t_cte.q1 = i8.q1) AS t_sub - FROM int8_tbl i8 -) ss; - -SELECT q1 FROM -( - WITH t_cte AS (SELECT * FROM int8_tbl t) - SELECT q1, (SELECT q2 FROM t_cte WHERE t_cte.q1 = i8.q1) AS t_sub - FROM int8_tbl i8 -) ss; - -EXPLAIN (VERBOSE, COSTS OFF) -SELECT q1 FROM -( - WITH t_cte AS MATERIALIZED (SELECT * FROM int8_tbl t) - SELECT q1, (SELECT q2 FROM t_cte WHERE t_cte.q1 = i8.q1) AS t_sub - FROM int8_tbl i8 -) ss; - -SELECT q1 FROM -( - WITH t_cte AS MATERIALIZED (SELECT * FROM int8_tbl t) - SELECT q1, (SELECT q2 FROM t_cte WHERE t_cte.q1 = i8.q1) AS t_sub - FROM int8_tbl i8 -) ss; - --- a truly recursive CTE in the same list -WITH RECURSIVE t(a) AS ( - SELECT 0 - UNION ALL - SELECT a+1 FROM t WHERE a+1 < 5 -), t2 as ( - INSERT INTO y - SELECT * FROM t RETURNING * -) -SELECT * FROM t2 JOIN y USING (a) ORDER BY a; - -SELECT * FROM y; - --- data-modifying WITH in a modifying statement -WITH t AS ( - DELETE FROM y - WHERE a <= 10 - RETURNING * -) -INSERT INTO y SELECT -a FROM t RETURNING *; - -SELECT * FROM y; - --- check that WITH query is run to completion even if outer query isn't -WITH t AS ( - UPDATE y SET a = a * 100 RETURNING * -) -SELECT * FROM t LIMIT 10; - -SELECT * FROM y; - --- data-modifying WITH containing INSERT...ON CONFLICT DO UPDATE -CREATE TABLE withz AS SELECT i AS k, (i || ' v')::text v FROM generate_series(1, 16, 3) i; -ALTER TABLE withz ADD UNIQUE (k); - -WITH t AS ( - INSERT INTO withz SELECT i, 'insert' - FROM generate_series(0, 16) i - ON CONFLICT (k) DO UPDATE SET v = withz.v || ', now update' - RETURNING * -) -SELECT * FROM t JOIN y ON t.k = y.a ORDER BY a, k; - --- Test EXCLUDED.* reference within CTE -WITH aa AS ( - INSERT INTO withz VALUES(1, 5) ON CONFLICT (k) DO UPDATE SET v = EXCLUDED.v - WHERE withz.k != EXCLUDED.k - RETURNING * -) -SELECT * FROM aa; - --- New query/snapshot demonstrates side-effects of previous query. -SELECT * FROM withz ORDER BY k; - --- --- Ensure subqueries within the update clause work, even if they --- reference outside values --- -WITH aa AS (SELECT 1 a, 2 b) -INSERT INTO withz VALUES(1, 'insert') -ON CONFLICT (k) DO UPDATE SET v = (SELECT b || ' update' FROM aa WHERE a = 1 LIMIT 1); -WITH aa AS (SELECT 1 a, 2 b) -INSERT INTO withz VALUES(1, 'insert') -ON CONFLICT (k) DO UPDATE SET v = ' update' WHERE withz.k = (SELECT a FROM aa); -WITH aa AS (SELECT 1 a, 2 b) -INSERT INTO withz VALUES(1, 'insert') -ON CONFLICT (k) DO UPDATE SET v = (SELECT b || ' update' FROM aa WHERE a = 1 LIMIT 1); -WITH aa AS (SELECT 'a' a, 'b' b UNION ALL SELECT 'a' a, 'b' b) -INSERT INTO withz VALUES(1, 'insert') -ON CONFLICT (k) DO UPDATE SET v = (SELECT b || ' update' FROM aa WHERE a = 'a' LIMIT 1); -WITH aa AS (SELECT 1 a, 2 b) -INSERT INTO withz VALUES(1, (SELECT b || ' insert' FROM aa WHERE a = 1 )) -ON CONFLICT (k) DO UPDATE SET v = (SELECT b || ' update' FROM aa WHERE a = 1 LIMIT 1); - --- Update a row more than once, in different parts of a wCTE. That is --- an allowed, presumably very rare, edge case, but since it was --- broken in the past, having a test seems worthwhile. -WITH simpletup AS ( - SELECT 2 k, 'Green' v), -upsert_cte AS ( - INSERT INTO withz VALUES(2, 'Blue') ON CONFLICT (k) DO - UPDATE SET (k, v) = (SELECT k, v FROM simpletup WHERE simpletup.k = withz.k) - RETURNING k, v) -INSERT INTO withz VALUES(2, 'Red') ON CONFLICT (k) DO -UPDATE SET (k, v) = (SELECT k, v FROM upsert_cte WHERE upsert_cte.k = withz.k) -RETURNING k, v; - -DROP TABLE withz; - --- WITH referenced by MERGE statement -CREATE TABLE m AS SELECT i AS k, (i || ' v')::text v FROM generate_series(1, 16, 3) i; -ALTER TABLE m ADD UNIQUE (k); - -WITH RECURSIVE cte_basic AS (SELECT 1 a, 'cte_basic val' b) -MERGE INTO m USING (select 0 k, 'merge source SubPlan' v) o ON m.k=o.k -WHEN MATCHED THEN UPDATE SET v = (SELECT b || ' merge update' FROM cte_basic WHERE cte_basic.a = m.k LIMIT 1) -WHEN NOT MATCHED THEN INSERT VALUES(o.k, o.v); - --- Basic: -WITH cte_basic AS MATERIALIZED (SELECT 1 a, 'cte_basic val' b) -MERGE INTO m USING (select 0 k, 'merge source SubPlan' v offset 0) o ON m.k=o.k -WHEN MATCHED THEN UPDATE SET v = (SELECT b || ' merge update' FROM cte_basic WHERE cte_basic.a = m.k LIMIT 1) -WHEN NOT MATCHED THEN INSERT VALUES(o.k, o.v); --- Examine -SELECT * FROM m where k = 0; - --- See EXPLAIN output for same query: -EXPLAIN (VERBOSE, COSTS OFF) -WITH cte_basic AS MATERIALIZED (SELECT 1 a, 'cte_basic val' b) -MERGE INTO m USING (select 0 k, 'merge source SubPlan' v offset 0) o ON m.k=o.k -WHEN MATCHED THEN UPDATE SET v = (SELECT b || ' merge update' FROM cte_basic WHERE cte_basic.a = m.k LIMIT 1) -WHEN NOT MATCHED THEN INSERT VALUES(o.k, o.v); - --- InitPlan -WITH cte_init AS MATERIALIZED (SELECT 1 a, 'cte_init val' b) -MERGE INTO m USING (select 1 k, 'merge source InitPlan' v offset 0) o ON m.k=o.k -WHEN MATCHED THEN UPDATE SET v = (SELECT b || ' merge update' FROM cte_init WHERE a = 1 LIMIT 1) -WHEN NOT MATCHED THEN INSERT VALUES(o.k, o.v); --- Examine -SELECT * FROM m where k = 1; - --- See EXPLAIN output for same query: -EXPLAIN (VERBOSE, COSTS OFF) -WITH cte_init AS MATERIALIZED (SELECT 1 a, 'cte_init val' b) -MERGE INTO m USING (select 1 k, 'merge source InitPlan' v offset 0) o ON m.k=o.k -WHEN MATCHED THEN UPDATE SET v = (SELECT b || ' merge update' FROM cte_init WHERE a = 1 LIMIT 1) -WHEN NOT MATCHED THEN INSERT VALUES(o.k, o.v); - --- MERGE source comes from CTE: -WITH merge_source_cte AS MATERIALIZED (SELECT 15 a, 'merge_source_cte val' b) -MERGE INTO m USING (select * from merge_source_cte) o ON m.k=o.a -WHEN MATCHED THEN UPDATE SET v = (SELECT b || merge_source_cte.*::text || ' merge update' FROM merge_source_cte WHERE a = 15) -WHEN NOT MATCHED THEN INSERT VALUES(o.a, o.b || (SELECT merge_source_cte.*::text || ' merge insert' FROM merge_source_cte)); --- Examine -SELECT * FROM m where k = 15; - --- See EXPLAIN output for same query: -EXPLAIN (VERBOSE, COSTS OFF) -WITH merge_source_cte AS MATERIALIZED (SELECT 15 a, 'merge_source_cte val' b) -MERGE INTO m USING (select * from merge_source_cte) o ON m.k=o.a -WHEN MATCHED THEN UPDATE SET v = (SELECT b || merge_source_cte.*::text || ' merge update' FROM merge_source_cte WHERE a = 15) -WHEN NOT MATCHED THEN INSERT VALUES(o.a, o.b || (SELECT merge_source_cte.*::text || ' merge insert' FROM merge_source_cte)); - -DROP TABLE m; - --- check that run to completion happens in proper ordering - -TRUNCATE TABLE y; -INSERT INTO y SELECT generate_series(1, 3); -CREATE TEMPORARY TABLE yy (a INTEGER); - -WITH RECURSIVE t1 AS ( - INSERT INTO y SELECT * FROM y RETURNING * -), t2 AS ( - INSERT INTO yy SELECT * FROM t1 RETURNING * -) -SELECT 1; - -SELECT * FROM y; -SELECT * FROM yy; - -WITH RECURSIVE t1 AS ( - INSERT INTO yy SELECT * FROM t2 RETURNING * -), t2 AS ( - INSERT INTO y SELECT * FROM y RETURNING * -) -SELECT 1; - -SELECT * FROM y; -SELECT * FROM yy; - --- triggers - -TRUNCATE TABLE y; -INSERT INTO y SELECT generate_series(1, 10); - -CREATE FUNCTION y_trigger() RETURNS trigger AS $$ -begin - raise notice 'y_trigger: a = %', new.a; - return new; -end; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER y_trig BEFORE INSERT ON y FOR EACH ROW - EXECUTE PROCEDURE y_trigger(); - -WITH t AS ( - INSERT INTO y - VALUES - (21), - (22), - (23) - RETURNING * -) -SELECT * FROM t; - -SELECT * FROM y; - -DROP TRIGGER y_trig ON y; - -CREATE TRIGGER y_trig AFTER INSERT ON y FOR EACH ROW - EXECUTE PROCEDURE y_trigger(); - -WITH t AS ( - INSERT INTO y - VALUES - (31), - (32), - (33) - RETURNING * -) -SELECT * FROM t LIMIT 1; - -SELECT * FROM y; - -DROP TRIGGER y_trig ON y; - -CREATE OR REPLACE FUNCTION y_trigger() RETURNS trigger AS $$ -begin - raise notice 'y_trigger'; - return null; -end; -$$ LANGUAGE plpgsql; - -CREATE TRIGGER y_trig AFTER INSERT ON y FOR EACH STATEMENT - EXECUTE PROCEDURE y_trigger(); - -WITH t AS ( - INSERT INTO y - VALUES - (41), - (42), - (43) - RETURNING * -) -SELECT * FROM t; - -SELECT * FROM y; - -DROP TRIGGER y_trig ON y; -DROP FUNCTION y_trigger(); - --- WITH attached to inherited UPDATE or DELETE - -CREATE TEMP TABLE parent ( id int, val text ); -CREATE TEMP TABLE child1 ( ) INHERITS ( parent ); -CREATE TEMP TABLE child2 ( ) INHERITS ( parent ); - -INSERT INTO parent VALUES ( 1, 'p1' ); -INSERT INTO child1 VALUES ( 11, 'c11' ),( 12, 'c12' ); -INSERT INTO child2 VALUES ( 23, 'c21' ),( 24, 'c22' ); - -WITH rcte AS ( SELECT sum(id) AS totalid FROM parent ) -UPDATE parent SET id = id + totalid FROM rcte; - -SELECT * FROM parent; - -WITH wcte AS ( INSERT INTO child1 VALUES ( 42, 'new' ) RETURNING id AS newid ) -UPDATE parent SET id = id + newid FROM wcte; - -SELECT * FROM parent; - -WITH rcte AS ( SELECT max(id) AS maxid FROM parent ) -DELETE FROM parent USING rcte WHERE id = maxid; - -SELECT * FROM parent; - -WITH wcte AS ( INSERT INTO child2 VALUES ( 42, 'new2' ) RETURNING id AS newid ) -DELETE FROM parent USING wcte WHERE id = newid; - -SELECT * FROM parent; - --- check EXPLAIN VERBOSE for a wCTE with RETURNING - -EXPLAIN (VERBOSE, COSTS OFF) -WITH wcte AS ( INSERT INTO int8_tbl VALUES ( 42, 47 ) RETURNING q2 ) -DELETE FROM a_star USING wcte WHERE aa = q2; - --- error cases - --- data-modifying WITH tries to use its own output -WITH RECURSIVE t AS ( - INSERT INTO y - SELECT * FROM t -) -VALUES(FALSE); - --- no RETURNING in a referenced data-modifying WITH -WITH t AS ( - INSERT INTO y VALUES(0) -) -SELECT * FROM t; - --- data-modifying WITH allowed only at the top level -SELECT * FROM ( - WITH t AS (UPDATE y SET a=a+1 RETURNING *) - SELECT * FROM t -) ss; - --- most variants of rules aren't allowed -CREATE RULE y_rule AS ON INSERT TO y WHERE a=0 DO INSTEAD DELETE FROM y; -WITH t AS ( - INSERT INTO y VALUES(0) -) -VALUES(FALSE); -CREATE OR REPLACE RULE y_rule AS ON INSERT TO y DO INSTEAD NOTHING; -WITH t AS ( - INSERT INTO y VALUES(0) -) -VALUES(FALSE); -CREATE OR REPLACE RULE y_rule AS ON INSERT TO y DO INSTEAD NOTIFY foo; -WITH t AS ( - INSERT INTO y VALUES(0) -) -VALUES(FALSE); -CREATE OR REPLACE RULE y_rule AS ON INSERT TO y DO ALSO NOTIFY foo; -WITH t AS ( - INSERT INTO y VALUES(0) -) -VALUES(FALSE); -CREATE OR REPLACE RULE y_rule AS ON INSERT TO y - DO INSTEAD (NOTIFY foo; NOTIFY bar); -WITH t AS ( - INSERT INTO y VALUES(0) -) -VALUES(FALSE); -DROP RULE y_rule ON y; - --- check that parser lookahead for WITH doesn't cause any odd behavior -create table foo (with baz); -- fail, WITH is a reserved word -create table foo (with ordinality); -- fail, WITH is a reserved word -with ordinality as (select 1 as x) select * from ordinality; - --- check sane response to attempt to modify CTE relation -WITH with_test AS (SELECT 42) INSERT INTO with_test VALUES (1); - --- check response to attempt to modify table with same name as a CTE (perhaps --- surprisingly it works, because CTEs don't hide tables from data-modifying --- statements) -create temp table with_test (i int); -with with_test as (select 42) insert into with_test select * from with_test; -select * from with_test; -drop table with_test; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwrite_parallel.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwrite_parallel.sql deleted file mode 100644 index ae660dc226..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fwrite_parallel.sql +++ /dev/null @@ -1,43 +0,0 @@ --- --- PARALLEL --- - -begin; - --- encourage use of parallel plans -set parallel_setup_cost=0; -set parallel_tuple_cost=0; -set min_parallel_table_scan_size=0; -set max_parallel_workers_per_gather=4; - --- --- Test write operations that has an underlying query that is eligible --- for parallel plans --- -explain (costs off) create table parallel_write as - select length(stringu1) from tenk1 group by length(stringu1); -create table parallel_write as - select length(stringu1) from tenk1 group by length(stringu1); -drop table parallel_write; - -explain (costs off) select length(stringu1) into parallel_write - from tenk1 group by length(stringu1); -select length(stringu1) into parallel_write - from tenk1 group by length(stringu1); -drop table parallel_write; - -explain (costs off) create materialized view parallel_mat_view as - select length(stringu1) from tenk1 group by length(stringu1); -create materialized view parallel_mat_view as - select length(stringu1) from tenk1 group by length(stringu1); -create unique index on parallel_mat_view(length); -refresh materialized view parallel_mat_view; -refresh materialized view concurrently parallel_mat_view; -drop materialized view parallel_mat_view; - -prepare prep_stmt as select length(stringu1) from tenk1 group by length(stringu1); -explain (costs off) create table parallel_write as execute prep_stmt; -create table parallel_write as execute prep_stmt; -drop table parallel_write; - -rollback; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fxid.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fxid.sql deleted file mode 100644 index bee17e6364..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Fxid.sql +++ /dev/null @@ -1,156 +0,0 @@ --- xid and xid8 - --- values in range, in octal, decimal, hex -select '010'::xid, - '42'::xid, - '0xffffffff'::xid, - '-1'::xid, - '010'::xid8, - '42'::xid8, - '0xffffffffffffffff'::xid8, - '-1'::xid8; - --- garbage values are not yet rejected (perhaps they should be) -select ''::xid; -select 'asdf'::xid; -select ''::xid8; -select 'asdf'::xid8; - --- equality -select '1'::xid = '1'::xid; -select '1'::xid != '1'::xid; -select '1'::xid8 = '1'::xid8; -select '1'::xid8 != '1'::xid8; - --- conversion -select '1'::xid = '1'::xid8::xid; -select '1'::xid != '1'::xid8::xid; - --- we don't want relational operators for xid, due to use of modular arithmetic -select '1'::xid < '2'::xid; -select '1'::xid <= '2'::xid; -select '1'::xid > '2'::xid; -select '1'::xid >= '2'::xid; - --- we want them for xid8 though -select '1'::xid8 < '2'::xid8, '2'::xid8 < '2'::xid8, '2'::xid8 < '1'::xid8; -select '1'::xid8 <= '2'::xid8, '2'::xid8 <= '2'::xid8, '2'::xid8 <= '1'::xid8; -select '1'::xid8 > '2'::xid8, '2'::xid8 > '2'::xid8, '2'::xid8 > '1'::xid8; -select '1'::xid8 >= '2'::xid8, '2'::xid8 >= '2'::xid8, '2'::xid8 >= '1'::xid8; - --- we also have a 3way compare for btrees -select xid8cmp('1', '2'), xid8cmp('2', '2'), xid8cmp('2', '1'); - --- min() and max() for xid8 -create table xid8_t1 (x xid8); -insert into xid8_t1 values ('0'), ('010'), ('42'), ('0xffffffffffffffff'), ('-1'); -select min(x), max(x) from xid8_t1; - --- xid8 has btree and hash opclasses -create index on xid8_t1 using btree(x); -create index on xid8_t1 using hash(x); -drop table xid8_t1; - - --- pg_snapshot data type and related functions - --- Note: another set of tests similar to this exists in txid.sql, for a limited --- time (the relevant functions share C code) - --- i/o -select '12:13:'::pg_snapshot; -select '12:18:14,16'::pg_snapshot; -select '12:16:14,14'::pg_snapshot; - --- errors -select '31:12:'::pg_snapshot; -select '0:1:'::pg_snapshot; -select '12:13:0'::pg_snapshot; -select '12:16:14,13'::pg_snapshot; - -create temp table snapshot_test ( - nr integer, - snap pg_snapshot -); - -insert into snapshot_test values (1, '12:13:'); -insert into snapshot_test values (2, '12:20:13,15,18'); -insert into snapshot_test values (3, '100001:100009:100005,100007,100008'); -insert into snapshot_test values (4, '100:150:101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131'); -select snap from snapshot_test order by nr; - -select pg_snapshot_xmin(snap), - pg_snapshot_xmax(snap), - pg_snapshot_xip(snap) -from snapshot_test order by nr; - -select id, pg_visible_in_snapshot(id::text::xid8, snap) -from snapshot_test, generate_series(11, 21) id -where nr = 2; - --- test bsearch -select id, pg_visible_in_snapshot(id::text::xid8, snap) -from snapshot_test, generate_series(90, 160) id -where nr = 4; - --- test current values also -select pg_current_xact_id() >= pg_snapshot_xmin(pg_current_snapshot()); - --- we can't assume current is always less than xmax, however - -select pg_visible_in_snapshot(pg_current_xact_id(), pg_current_snapshot()); - --- test 64bitness - -select pg_snapshot '1000100010001000:1000100010001100:1000100010001012,1000100010001013'; -select pg_visible_in_snapshot('1000100010001012', '1000100010001000:1000100010001100:1000100010001012,1000100010001013'); -select pg_visible_in_snapshot('1000100010001015', '1000100010001000:1000100010001100:1000100010001012,1000100010001013'); - --- test 64bit overflow -SELECT pg_snapshot '1:9223372036854775807:3'; -SELECT pg_snapshot '1:9223372036854775808:3'; - --- test pg_current_xact_id_if_assigned -BEGIN; -SELECT pg_current_xact_id_if_assigned() IS NULL; -SELECT pg_current_xact_id() \gset -SELECT pg_current_xact_id_if_assigned() IS NOT DISTINCT FROM xid8 :'pg_current_xact_id'; -COMMIT; - --- test xid status functions -BEGIN; -SELECT pg_current_xact_id() AS committed \gset -COMMIT; - -BEGIN; -SELECT pg_current_xact_id() AS rolledback \gset -ROLLBACK; - -BEGIN; -SELECT pg_current_xact_id() AS inprogress \gset - -SELECT pg_xact_status(:committed::text::xid8) AS committed; -SELECT pg_xact_status(:rolledback::text::xid8) AS rolledback; -SELECT pg_xact_status(:inprogress::text::xid8) AS inprogress; -SELECT pg_xact_status('1'::xid8); -- BootstrapTransactionId is always committed -SELECT pg_xact_status('2'::xid8); -- FrozenTransactionId is always committed -SELECT pg_xact_status('3'::xid8); -- in regress testing FirstNormalTransactionId will always be behind oldestXmin - -COMMIT; - -BEGIN; -CREATE FUNCTION test_future_xid_status(xid8) -RETURNS void -LANGUAGE plpgsql -AS -$$ -BEGIN - PERFORM pg_xact_status($1); - RAISE EXCEPTION 'didn''t ERROR at xid in the future as expected'; -EXCEPTION - WHEN invalid_parameter_value THEN - RAISE NOTICE 'Got expected error for xid in the future'; -END; -$$; -SELECT test_future_xid_status((:inprogress + 10000)::text::xid8); -ROLLBACK; diff --git a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres-old-soon-decommissioned%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftriggers.sql b/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres-old-soon-decommissioned%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftriggers.sql deleted file mode 100644 index 68495ca112..0000000000 --- a/vendor/tree-sitter-sql/examples/real_world_stuff/postgres/postgres%2Fpostgres-old-soon-decommissioned%2Fmaster%2Fsrc%2Ftest%2Fregress%2Fsql%2Ftriggers.sql +++ /dev/null @@ -1,580 +0,0 @@ --- --- TRIGGERS --- - -create table pkeys (pkey1 int4 not null, pkey2 text not null); -create table fkeys (fkey1 int4, fkey2 text, fkey3 int); -create table fkeys2 (fkey21 int4, fkey22 text, pkey23 int not null); - -create index fkeys_i on fkeys (fkey1, fkey2); -create index fkeys2_i on fkeys2 (fkey21, fkey22); -create index fkeys2p_i on fkeys2 (pkey23); - -insert into pkeys values (10, '1'); -insert into pkeys values (20, '2'); -insert into pkeys values (30, '3'); -insert into pkeys values (40, '4'); -insert into pkeys values (50, '5'); -insert into pkeys values (60, '6'); -create unique index pkeys_i on pkeys (pkey1, pkey2); - --- --- For fkeys: --- (fkey1, fkey2) --> pkeys (pkey1, pkey2) --- (fkey3) --> fkeys2 (pkey23) --- -create trigger check_fkeys_pkey_exist - before insert or update on fkeys - for each row - execute procedure - check_primary_key ('fkey1', 'fkey2', 'pkeys', 'pkey1', 'pkey2'); - -create trigger check_fkeys_pkey2_exist - before insert or update on fkeys - for each row - execute procedure check_primary_key ('fkey3', 'fkeys2', 'pkey23'); - --- --- For fkeys2: --- (fkey21, fkey22) --> pkeys (pkey1, pkey2) --- -create trigger check_fkeys2_pkey_exist - before insert or update on fkeys2 - for each row - execute procedure - check_primary_key ('fkey21', 'fkey22', 'pkeys', 'pkey1', 'pkey2'); - --- Test comments -COMMENT ON TRIGGER check_fkeys2_pkey_bad ON fkeys2 IS 'wrong'; -COMMENT ON TRIGGER check_fkeys2_pkey_exist ON fkeys2 IS 'right'; -COMMENT ON TRIGGER check_fkeys2_pkey_exist ON fkeys2 IS NULL; - --- --- For pkeys: --- ON DELETE/UPDATE (pkey1, pkey2) CASCADE: --- fkeys (fkey1, fkey2) and fkeys2 (fkey21, fkey22) --- -create trigger check_pkeys_fkey_cascade - before delete or update on pkeys - for each row - execute procedure - check_foreign_key (2, 'cascade', 'pkey1', 'pkey2', - 'fkeys', 'fkey1', 'fkey2', 'fkeys2', 'fkey21', 'fkey22'); - --- --- For fkeys2: --- ON DELETE/UPDATE (pkey23) RESTRICT: --- fkeys (fkey3) --- -create trigger check_fkeys2_fkey_restrict - before delete or update on fkeys2 - for each row - execute procedure check_foreign_key (1, 'restrict', 'pkey23', 'fkeys', 'fkey3'); - -insert into fkeys2 values (10, '1', 1); -insert into fkeys2 values (30, '3', 2); -insert into fkeys2 values (40, '4', 5); -insert into fkeys2 values (50, '5', 3); --- no key in pkeys -insert into fkeys2 values (70, '5', 3); - -insert into fkeys values (10, '1', 2); -insert into fkeys values (30, '3', 3); -insert into fkeys values (40, '4', 2); -insert into fkeys values (50, '5', 2); --- no key in pkeys -insert into fkeys values (70, '5', 1); --- no key in fkeys2 -insert into fkeys values (60, '6', 4); - -delete from pkeys where pkey1 = 30 and pkey2 = '3'; -delete from pkeys where pkey1 = 40 and pkey2 = '4'; -update pkeys set pkey1 = 7, pkey2 = '70' where pkey1 = 50 and pkey2 = '5'; -update pkeys set pkey1 = 7, pkey2 = '70' where pkey1 = 10 and pkey2 = '1'; - -DROP TABLE pkeys; -DROP TABLE fkeys; -DROP TABLE fkeys2; - --- -- I've disabled the funny_dup17 test because the new semantics --- -- of AFTER ROW triggers, which get now fired at the end of a --- -- query always, cause funny_dup17 to enter an endless loop. --- -- --- -- Jan --- --- create table dup17 (x int4); --- --- create trigger dup17_before --- before insert on dup17 --- for each row --- execute procedure --- funny_dup17 () --- ; --- --- insert into dup17 values (17); --- select count(*) from dup17; --- insert into dup17 values (17); --- select count(*) from dup17; --- --- drop trigger dup17_before on dup17; --- --- create trigger dup17_after --- after insert on dup17 --- for each row --- execute procedure --- funny_dup17 () --- ; --- insert into dup17 values (13); --- select count(*) from dup17 where x = 13; --- insert into dup17 values (13); --- select count(*) from dup17 where x = 13; --- --- DROP TABLE dup17; - -create sequence ttdummy_seq increment 10 start 0 minvalue 0; - -create table tttest ( - price_id int4, - price_val int4, - price_on int4, - price_off int4 default 999999 -); - -create trigger ttdummy - before delete or update on tttest - for each row - execute procedure - ttdummy (price_on, price_off); - -create trigger ttserial - before insert or update on tttest - for each row - execute procedure - autoinc (price_on, ttdummy_seq); - -insert into tttest values (1, 1, null); -insert into tttest values (2, 2, null); -insert into tttest values (3, 3, 0); - -select * from tttest; -delete from tttest where price_id = 2; -select * from tttest; --- what do we see ? - --- get current prices -select * from tttest where price_off = 999999; - --- change price for price_id == 3 -update tttest set price_val = 30 where price_id = 3; -select * from tttest; - --- now we want to change pric_id in ALL tuples --- this gets us not what we need -update tttest set price_id = 5 where price_id = 3; -select * from tttest; - --- restore data as before last update: -select set_ttdummy(0); -delete from tttest where price_id = 5; -update tttest set price_off = 999999 where price_val = 30; -select * from tttest; - --- and try change price_id now! -update tttest set price_id = 5 where price_id = 3; -select * from tttest; --- isn't it what we need ? - -select set_ttdummy(1); - --- we want to correct some "date" -update tttest set price_on = -1 where price_id = 1; --- but this doesn't work - --- try in this way -select set_ttdummy(0); -update tttest set price_on = -1 where price_id = 1; -select * from tttest; --- isn't it what we need ? - --- get price for price_id == 5 as it was @ "date" 35 -select * from tttest where price_on <= 35 and price_off > 35 and price_id = 5; - -drop table tttest; -drop sequence ttdummy_seq; - --- --- tests for per-statement triggers --- - -CREATE TABLE log_table (tstamp timestamp default timeofday()::timestamp); - -CREATE TABLE main_table (a int, b int); - -COPY main_table (a,b) FROM stdin; -5 10 -20 20 -30 10 -50 35 -80 15 -\. - -CREATE FUNCTION trigger_func() RETURNS trigger LANGUAGE plpgsql AS ' -BEGIN - RAISE NOTICE ''trigger_func(%) called: action = %, when = %, level = %'', TG_ARGV[0], TG_OP, TG_WHEN, TG_LEVEL; - RETURN NULL; -END;'; - -CREATE TRIGGER before_ins_stmt_trig BEFORE INSERT ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('before_ins_stmt'); - -CREATE TRIGGER after_ins_stmt_trig AFTER INSERT ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('after_ins_stmt'); - --- --- if neither 'FOR EACH ROW' nor 'FOR EACH STATEMENT' was specified, --- CREATE TRIGGER should default to 'FOR EACH STATEMENT' --- -CREATE TRIGGER after_upd_stmt_trig AFTER UPDATE ON main_table -EXECUTE PROCEDURE trigger_func('after_upd_stmt'); - -CREATE TRIGGER after_upd_row_trig AFTER UPDATE ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('after_upd_row'); - -INSERT INTO main_table DEFAULT VALUES; - -UPDATE main_table SET a = a + 1 WHERE b < 30; --- UPDATE that effects zero rows should still call per-statement trigger -UPDATE main_table SET a = a + 2 WHERE b > 100; - --- COPY should fire per-row and per-statement INSERT triggers -COPY main_table (a, b) FROM stdin; -30 40 -50 60 -\. - -SELECT * FROM main_table ORDER BY a, b; - --- --- test triggers with WHEN clause --- - -CREATE TRIGGER modified_a BEFORE UPDATE OF a ON main_table -FOR EACH ROW WHEN (OLD.a <> NEW.a) EXECUTE PROCEDURE trigger_func('modified_a'); -CREATE TRIGGER modified_any BEFORE UPDATE OF a ON main_table -FOR EACH ROW WHEN (OLD.* IS DISTINCT FROM NEW.*) EXECUTE PROCEDURE trigger_func('modified_any'); -CREATE TRIGGER insert_a AFTER INSERT ON main_table -FOR EACH ROW WHEN (NEW.a = 123) EXECUTE PROCEDURE trigger_func('insert_a'); -CREATE TRIGGER delete_a AFTER DELETE ON main_table -FOR EACH ROW WHEN (OLD.a = 123) EXECUTE PROCEDURE trigger_func('delete_a'); -CREATE TRIGGER insert_when BEFORE INSERT ON main_table -FOR EACH STATEMENT WHEN (true) EXECUTE PROCEDURE trigger_func('insert_when'); -CREATE TRIGGER delete_when AFTER DELETE ON main_table -FOR EACH STATEMENT WHEN (true) EXECUTE PROCEDURE trigger_func('delete_when'); -INSERT INTO main_table (a) VALUES (123), (456); -COPY main_table FROM stdin; -123 999 -456 999 -\. -DELETE FROM main_table WHERE a IN (123, 456); -UPDATE main_table SET a = 50, b = 60; -SELECT * FROM main_table ORDER BY a, b; -SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_a'; -SELECT pg_get_triggerdef(oid, false) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_a'; -SELECT pg_get_triggerdef(oid, true) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'modified_any'; -DROP TRIGGER modified_a ON main_table; -DROP TRIGGER modified_any ON main_table; -DROP TRIGGER insert_a ON main_table; -DROP TRIGGER delete_a ON main_table; -DROP TRIGGER insert_when ON main_table; -DROP TRIGGER delete_when ON main_table; - --- Test column-level triggers -DROP TRIGGER after_upd_row_trig ON main_table; - -CREATE TRIGGER before_upd_a_row_trig BEFORE UPDATE OF a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('before_upd_a_row'); -CREATE TRIGGER after_upd_b_row_trig AFTER UPDATE OF b ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('after_upd_b_row'); -CREATE TRIGGER after_upd_a_b_row_trig AFTER UPDATE OF a, b ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('after_upd_a_b_row'); - -CREATE TRIGGER before_upd_a_stmt_trig BEFORE UPDATE OF a ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('before_upd_a_stmt'); -CREATE TRIGGER after_upd_b_stmt_trig AFTER UPDATE OF b ON main_table -FOR EACH STATEMENT EXECUTE PROCEDURE trigger_func('after_upd_b_stmt'); - -SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgrelid = 'main_table'::regclass AND tgname = 'after_upd_a_b_row_trig'; - -UPDATE main_table SET a = 50; -UPDATE main_table SET b = 10; - --- bogus cases -CREATE TRIGGER error_upd_and_col BEFORE UPDATE OR UPDATE OF a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_upd_and_col'); -CREATE TRIGGER error_upd_a_a BEFORE UPDATE OF a, a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_upd_a_a'); -CREATE TRIGGER error_ins_a BEFORE INSERT OF a ON main_table -FOR EACH ROW EXECUTE PROCEDURE trigger_func('error_ins_a'); -CREATE TRIGGER error_ins_when BEFORE INSERT OR UPDATE ON main_table -FOR EACH ROW WHEN (OLD.a <> NEW.a) -EXECUTE PROCEDURE trigger_func('error_ins_old'); -CREATE TRIGGER error_del_when BEFORE DELETE OR UPDATE ON main_table -FOR EACH ROW WHEN (OLD.a <> NEW.a) -EXECUTE PROCEDURE trigger_func('error_del_new'); -CREATE TRIGGER error_del_when BEFORE INSERT OR UPDATE ON main_table -FOR EACH ROW WHEN (NEW.tableoid <> 0) -EXECUTE PROCEDURE trigger_func('error_when_sys_column'); -CREATE TRIGGER error_stmt_when BEFORE UPDATE OF a ON main_table -FOR EACH STATEMENT WHEN (OLD.* IS DISTINCT FROM NEW.*) -EXECUTE PROCEDURE trigger_func('error_stmt_when'); - --- check dependency restrictions -ALTER TABLE main_table DROP COLUMN b; --- this should succeed, but we'll roll it back to keep the triggers around -begin; -DROP TRIGGER after_upd_a_b_row_trig ON main_table; -DROP TRIGGER after_upd_b_row_trig ON main_table; -DROP TRIGGER after_upd_b_stmt_trig ON main_table; -ALTER TABLE main_table DROP COLUMN b; -rollback; - --- Test enable/disable triggers - -create table trigtest (i serial primary key); --- test that disabling RI triggers works -create table trigtest2 (i int references trigtest(i) on delete cascade); - -create function trigtest() returns trigger as $$ -begin - raise notice '% % % %', TG_RELNAME, TG_OP, TG_WHEN, TG_LEVEL; - return new; -end;$$ language plpgsql; - -create trigger trigtest_b_row_tg before insert or update or delete on trigtest -for each row execute procedure trigtest(); -create trigger trigtest_a_row_tg after insert or update or delete on trigtest -for each row execute procedure trigtest(); -create trigger trigtest_b_stmt_tg before insert or update or delete on trigtest -for each statement execute procedure trigtest(); -create trigger trigtest_a_stmt_tg after insert or update or delete on trigtest -for each statement execute procedure trigtest(); - -insert into trigtest default values; -alter table trigtest disable trigger trigtest_b_row_tg; -insert into trigtest default values; -alter table trigtest disable trigger user; -insert into trigtest default values; -alter table trigtest enable trigger trigtest_a_stmt_tg; -insert into trigtest default values; -insert into trigtest2 values(1); -insert into trigtest2 values(2); -delete from trigtest where i=2; -select * from trigtest2; -alter table trigtest disable trigger all; -delete from trigtest where i=1; -select * from trigtest2; --- ensure we still insert, even when all triggers are disabled -insert into trigtest default values; -select * from trigtest; -drop table trigtest2; -drop table trigtest; - - --- dump trigger data -CREATE TABLE trigger_test ( - i int, - v varchar -); - -CREATE OR REPLACE FUNCTION trigger_data() RETURNS trigger -LANGUAGE plpgsql AS $$ - -declare - - argstr text; - relid text; - -begin - - relid := TG_relid::regclass; - - -- plpgsql can't discover its trigger data in a hash like perl and python - -- can, or by a sort of reflection like tcl can, - -- so we have to hard code the names. - raise NOTICE 'TG_NAME: %', TG_name; - raise NOTICE 'TG_WHEN: %', TG_when; - raise NOTICE 'TG_LEVEL: %', TG_level; - raise NOTICE 'TG_OP: %', TG_op; - raise NOTICE 'TG_RELID::regclass: %', relid; - raise NOTICE 'TG_RELNAME: %', TG_relname; - raise NOTICE 'TG_TABLE_NAME: %', TG_table_name; - raise NOTICE 'TG_TABLE_SCHEMA: %', TG_table_schema; - raise NOTICE 'TG_NARGS: %', TG_nargs; - - argstr := '['; - for i in 0 .. TG_nargs - 1 loop - if i > 0 then - argstr := argstr || ', '; - end if; - argstr := argstr || TG_argv[i]; - end loop; - argstr := argstr || ']'; - raise NOTICE 'TG_ARGV: %', argstr; - - if TG_OP != 'INSERT' then - raise NOTICE 'OLD: %', OLD; - end if; - - if TG_OP != 'DELETE' then - raise NOTICE 'NEW: %', NEW; - end if; - - if TG_OP = 'DELETE' then - return OLD; - else - return NEW; - end if; - -end; -$$; - -CREATE TRIGGER show_trigger_data_trig -BEFORE INSERT OR UPDATE OR DELETE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo'); - -insert into trigger_test values(1,'insert'); -update trigger_test set v = 'update' where i = 1; -delete from trigger_test; - -DROP TRIGGER show_trigger_data_trig on trigger_test; - -DROP FUNCTION trigger_data(); - -DROP TABLE trigger_test; - --- --- Test use of row comparisons on OLD/NEW --- - -CREATE TABLE trigger_test (f1 int, f2 text, f3 text); - --- this is the obvious (and wrong...) way to compare rows -CREATE FUNCTION mytrigger() RETURNS trigger LANGUAGE plpgsql as $$ -begin - if row(old.*) = row(new.*) then - raise notice 'row % not changed', new.f1; - else - raise notice 'row % changed', new.f1; - end if; - return new; -end$$; - -CREATE TRIGGER t -BEFORE UPDATE ON trigger_test -FOR EACH ROW EXECUTE PROCEDURE mytrigger(); - -INSERT INTO trigger_test VALUES(1, 'foo', 'bar'); -INSERT INTO trigger_test VALUES(2, 'baz', 'quux'); - -UPDATE trigger_test SET f3 = 'bar'; -UPDATE trigger_test SET f3 = NULL; --- this demonstrates that the above isn't really working as desired: -UPDATE trigger_test SET f3 = NULL; - --- the right way when considering nulls is -CREATE OR REPLACE FUNCTION mytrigger() RETURNS trigger LANGUAGE plpgsql as $$ -begin - if row(old.*) is distinct from row(new.*) then - raise notice 'row % changed', new.f1; - else - raise notice 'row % not changed', new.f1; - end if; - return new; -end$$; - -UPDATE trigger_test SET f3 = 'bar'; -UPDATE trigger_test SET f3 = NULL; -UPDATE trigger_test SET f3 = NULL; - -DROP TABLE trigger_test; - -DROP FUNCTION mytrigger(); - --- Test snapshot management in serializable transactions involving triggers --- per bug report in 6bc73d4c0910042358k3d1adff3qa36f8df75198ecea@mail.gmail.com -CREATE FUNCTION serializable_update_trig() RETURNS trigger LANGUAGE plpgsql AS -$$ -declare - rec record; -begin - new.description = 'updated in trigger'; - return new; -end; -$$; - -CREATE TABLE serializable_update_tab ( - id int, - filler text, - description text -); - -CREATE TRIGGER serializable_update_trig BEFORE UPDATE ON serializable_update_tab - FOR EACH ROW EXECUTE PROCEDURE serializable_update_trig(); - -INSERT INTO serializable_update_tab SELECT a, repeat('xyzxz', 100), 'new' - FROM generate_series(1, 50) a; - -BEGIN; -SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -UPDATE serializable_update_tab SET description = 'no no', id = 1 WHERE id = 1; -COMMIT; -SELECT description FROM serializable_update_tab WHERE id = 1; -DROP TABLE serializable_update_tab; - --- minimal update trigger - -CREATE TABLE min_updates_test ( - f1 text, - f2 int, - f3 int); - -CREATE TABLE min_updates_test_oids ( - f1 text, - f2 int, - f3 int) WITH OIDS; - -INSERT INTO min_updates_test VALUES ('a',1,2),('b','2',null); - -INSERT INTO min_updates_test_oids VALUES ('a',1,2),('b','2',null); - -CREATE TRIGGER z_min_update -BEFORE UPDATE ON min_updates_test -FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger(); - -CREATE TRIGGER z_min_update -BEFORE UPDATE ON min_updates_test_oids -FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger(); - -\set QUIET false - -UPDATE min_updates_test SET f1 = f1; - -UPDATE min_updates_test SET f2 = f2 + 1; - -UPDATE min_updates_test SET f3 = 2 WHERE f3 is null; - -UPDATE min_updates_test_oids SET f1 = f1; - -UPDATE min_updates_test_oids SET f2 = f2 + 1; - -UPDATE min_updates_test_oids SET f3 = 2 WHERE f3 is null; - -\set QUIET true - -SELECT * FROM min_updates_test; - -SELECT * FROM min_updates_test_oids; - -DROP TABLE min_updates_test; - -DROP TABLE min_updates_test_oids;