Question: Show a SQL definition from the pg_partman project (pg_partman--2.2.0--2.2.1, item 1).

/*
 * Function to manage pre-creation of the next partitions in a set.
 * Also manages dropping old partitions if the retention option is set.
 * If p_parent_table is passed, will only run run_maintenance() on that one table (no matter what the configuration table may have set for it)
 * Otherwise, will run on all tables in the config table with p_run_maintenance() set to true.
 * For large partition sets, running analyze can cause maintenance to take longer than expected. Can set p_analyze to false to avoid a forced analyze run.
 * Be aware that constraint exclusion may not work properly until an analyze on the partition set is run.
 */
CREATE OR REPLACE FUNCTION run_maintenance(p_parent_table text DEFAULT NULL, p_analyze boolean DEFAULT true, p_jobmon boolean DEFAULT true, p_debug boolean DEFAULT false) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_adv_lock                      boolean;
v_check_subpart                 int;
v_create_count                  int := 0;
v_current_partition             text;
v_current_partition_id          bigint;
v_current_partition_timestamp   timestamp;
v_datetime_string               text;
v_drop_count                    int := 0;
v_id_position                   int;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_created        boolean;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamp;
v_max_id_parent                 bigint;
v_max_time_parent               timestamp;
v_next_partition_id             bigint;
v_next_partition_timestamp      timestamp;
v_parent_schema                 text;
v_parent_tablename              text;
v_premade_count                 int;
v_premake_id_max                bigint;
v_premake_id_min                bigint;
v_premake_timestamp_min         timestamp;
v_premake_timestamp_max         timestamp;
v_quarter                       text;
v_row                           record;
v_row_max_id                    record;
v_row_max_time                  record;
v_row_sub                       record;
v_skip_maint                    boolean;
v_step_id                       bigint;
v_step_overflow_id              bigint;
v_step_serial_id                bigint;
v_sub_id_max                    bigint;
v_sub_id_max_suffix             bigint;
v_sub_id_min                    bigint;
v_sub_parent                    text;
v_sub_timestamp_max             timestamp;
v_sub_timestamp_max_suffix      timestamp;
v_sub_timestamp_min             timestamp;
v_tablename                     text;
v_tables_list_sql               text;
v_time_position                 int;
v_year                          text;

BEGIN

v_adv_lock := pg_try_advisory_xact_lock(hashtext('pg_partman run_maintenance'));
IF v_adv_lock = 'false' THEN
    RAISE NOTICE 'Partman maintenance already running.';
    RETURN;
END IF;

IF p_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    EXECUTE format('SELECT %I.add_job(%L)', v_jobmon_schema, 'PARTMAN RUN MAINTENANCE') INTO v_job_id;
    EXECUTE format('SELECT %I.add_step(%L, %L)', v_jobmon_schema, v_job_id, 'Running maintenance loop') INTO v_step_id;
END IF;

-- Check for consistent data in part_config_sub table. Was unable to get this working properly as either a constraint or trigger.
-- Would either delay raising an error until the next write (which I cannot predict) or disallow future edits to update a sub-partition set's configuration.
-- This way at least provides a consistent way to check that I know will run. If anyone can get a working constraint/trigger, please help!
-- Don't have to worry about this in the serial trigger maintenance since subpartitioning requires run_maintenance().
FOR v_row IN
    SELECT sub_parent FROM @extschema@.part_config_sub
LOOP
    SELECT count(*) INTO v_check_subpart FROM @extschema@.check_subpart_sameconfig(v_row.sub_parent);
    IF v_check_subpart > 1 THEN
        RAISE EXCEPTION 'Inconsistent data in part_config_sub table. Sub-partition tables that are themselves sub-partitions cannot have differing configuration values among their siblings.
        Run this query: "SELECT * FROM @extschema@.check_subpart_sameconfig(''%'');" This should only return a single row or nothing.
        If multiple rows are returned, results are all children of the given parent. Update the differing values to be consistent for your desired values.', v_row.sub_parent;
    END IF;
END LOOP;

v_row := NULL; -- Ensure it's reset

v_tables_list_sql := 'SELECT parent_table
                , partition_type
                , partition_interval
                , control
                , premake
                , datetime_string
                , undo_in_progress
                , sub_partition_set_full
                , epoch
            FROM @extschema@.part_config
            WHERE sub_partition_set_full = false';

IF p_parent_table IS NULL THEN
    v_tables_list_sql := v_tables_list_sql || ' AND use_run_maintenance = true';
ELSE
    v_tables_list_sql := v_tables_list_sql || format(' AND parent_table = %L', p_parent_table);
END IF;

FOR v_row IN EXECUTE v_tables_list_sql
LOOP

    CONTINUE WHEN v_row.undo_in_progress;
    v_skip_maint := true; -- reset every loop

    SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_row.parent_table;

    SELECT partition_tablename INTO v_last_partition FROM @extschema@.show_partitions(v_row.parent_table, 'DESC') LIMIT 1;
    IF p_debug THEN
        RAISE NOTICE 'run_maint: parent_table: %, v_last_partition: %', v_row.parent_table, v_last_partition;
    END IF;

    IF v_row.partition_type = 'time' OR v_row.partition_type = 'time-custom' THEN

        v_time_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;
        IF v_row.partition_interval::interval <> '3 months' OR (v_row.partition_interval::interval = '3 months' AND v_row.partition_type = 'time-custom') THEN
           v_last_partition_timestamp := to_timestamp(substring(v_last_partition from v_time_position), v_row.datetime_string);
        ELSE
            -- to_timestamp doesn't recognize 'Q' date string formater. Handle it
            v_year := split_part(substring(v_last_partition FROM v_time_position), 'q', 1);
            v_quarter := split_part(substring(v_last_partition FROM v_time_position), 'q', 2);
            CASE
                WHEN v_quarter = '1' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-01-01', 'YYYY-MM-DD');
                WHEN v_quarter = '2' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-04-01', 'YYYY-MM-DD');
                WHEN v_quarter = '3' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-07-01', 'YYYY-MM-DD');
                WHEN v_quarter = '4' THEN
                    v_last_partition_timestamp := to_timestamp(v_year || '-10-01', 'YYYY-MM-DD');
            END CASE;
        END IF;

        -- Loop through child tables starting from highest to get current max value in partition set
        -- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
        FOR v_row_max_time IN
            SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(v_row.parent_table, 'DESC')
        LOOP
            IF v_row.epoch = false THEN
                EXECUTE format('SELECT max(%I)::text FROM %I.%I'
                                    , v_row.control
                                    , v_row_max_time.partition_schemaname
                                    , v_row_max_time.partition_tablename
                                ) INTO v_current_partition_timestamp;
            ELSE
                EXECUTE format('SELECT to_timestamp(max(%I))::text FROM %I.%I'
                                    , v_row.control
                                    , v_row_max_time.partition_schemaname
                                    , v_row_max_time.partition_tablename
                                ) INTO v_current_partition_timestamp;
            END IF;
            IF v_current_partition_timestamp IS NOT NULL THEN
                SELECT suffix_timestamp INTO v_current_partition_timestamp FROM @extschema@.show_partition_name(v_row.parent_table, v_current_partition_timestamp::text);
                EXIT;
            END IF;
        END LOOP;
        -- Check for values in the parent table. If they are there and greater than all child values, use that instead
        -- This allows maintenance to continue working properly if there is a large gap in data insertion. Data will remain in parent, but new tables will be created
        IF v_row.epoch = false THEN
            EXECUTE format('SELECT max(%I) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_time_parent;
        ELSE
            EXECUTE format('SELECT to_timestamp(max(%I)) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_time_parent;
        END IF;
        IF p_debug THEN
            RAISE NOTICE 'run_maint: v_current_partition_timestamp: %, v_max_time_parent: %', v_current_partition_timestamp, v_max_time_parent;
        END IF;
        IF v_max_time_parent > v_current_partition_timestamp THEN
            SELECT suffix_timestamp INTO v_current_partition_timestamp FROM @extschema@.show_partition_name(v_row.parent_table, v_max_time_parent::text);
        END IF;
        IF v_current_partition_timestamp IS NULL THEN
            -- Partition set is completely empty. Nothing to do
            CONTINUE;
        END IF;

        -- If this is a subpartition, determine if the last child table has been made. If so, mark it as full so future maintenance runs can skip it
        SELECT sub_min::timestamp, sub_max::timestamp INTO v_sub_timestamp_min, v_sub_timestamp_max FROM @extschema@.check_subpartition_limits(v_row.parent_table, 'time');
        IF v_sub_timestamp_max IS NOT NULL THEN
            SELECT suffix_timestamp INTO v_sub_timestamp_max_suffix FROM @extschema@.show_partition_name(v_row.parent_table, v_sub_timestamp_max::text);
            IF v_sub_timestamp_max_suffix = v_last_partition_timestamp THEN
                -- Final partition for this set is created. Set full and skip it
                UPDATE @extschema@.part_config SET sub_partition_set_full = true WHERE parent_table = v_row.parent_table;
                CONTINUE;
            END IF;
        END IF;

        -- Check and see how many premade partitions there are.
        v_premade_count = round(EXTRACT('epoch' FROM age(v_last_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.partition_interval::interval));
        v_next_partition_timestamp := v_last_partition_timestamp;
        IF p_debug THEN
            RAISE NOTICE 'run_maint before loop: current_partition_timestamp: %, v_premade_count: %, v_sub_timestamp_min: %, v_sub_timestamp_max: %'
                , v_current_partition_timestamp
                , v_premade_count
                , v_sub_timestamp_min
                , v_sub_timestamp_max;
        END IF;
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed
        WHILE (v_premade_count < v_row.premake) LOOP
            IF p_debug THEN
                RAISE NOTICE 'run_maint: parent_table: %, v_premade_count: %, v_next_partition_timestamp: %', v_row.parent_table, v_premade_count, v_next_partition_timestamp;
            END IF;
            IF v_next_partition_timestamp < v_sub_timestamp_min OR v_next_partition_timestamp > v_sub_timestamp_max THEN
                -- With subpartitioning, no need to run if the timestamp is not in the parent table's range
                EXIT;
            END IF;
            BEGIN
                v_next_partition_timestamp := v_next_partition_timestamp + v_row.partition_interval::interval;
            EXCEPTION WHEN datetime_field_overflow THEN
                v_premade_count := v_row.premake; -- do this so it can exit the premake check loop and continue in the outer for loop
                IF v_jobmon_schema IS NOT NULL THEN
                    EXECUTE format('SELECT %I.add_step(%L, %L)', v_jobmon_schema, v_job_id, 'Attempted partition time interval is outside PostgreSQL''s supported time range.') INTO v_step_overflow_id;
                    EXECUTE format('SELECT %I.update_step(%L, %L, %L)', v_jobmon_schema, v_step_overflow_id, 'CRITICAL', 'Child partition creation skippd for parent table '||v_partition_time);
                END IF;
                RAISE WARNING 'Attempted partition time interval is outside PostgreSQL''s supported time range. Child partition creation skipped for parent table %', v_row.parent_table;
                CONTINUE;
            END;
            v_last_partition_created := @extschema@.create_partition_time(v_row.parent_table, ARRAY[v_next_partition_timestamp], p_analyze);
            IF v_last_partition_created THEN
                v_create_count := v_create_count + 1;
                PERFORM @extschema@.create_function_time(v_row.parent_table, v_job_id);
            END IF;

            v_premade_count = round(EXTRACT('epoch' FROM age(v_next_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.partition_interval::interval));
        END LOOP;
    ELSIF v_row.partition_type = 'id' THEN
        -- Loop through child tables starting from highest to get current max value in partition set
        -- Avoids doing a scan on entire partition set and/or getting any values accidentally in parent.
        FOR v_row_max_id IN
            SELECT partition_schemaname, partition_tablename FROM @extschema@.show_partitions(v_row.parent_table, 'DESC')
        LOOP
            EXECUTE format('SELECT max(%I)::text FROM %I.%I'
                            , v_row.control
                            , v_row_max_id.partition_schemaname
                            , v_row_max_id.partition_tablename) INTO v_current_partition_id;
            IF v_current_partition_id IS NOT NULL THEN
                SELECT suffix_id INTO v_current_partition_id FROM @extschema@.show_partition_name(v_row.parent_table, v_current_partition_id::text);
                EXIT;
            END IF;
        END LOOP;
        -- Check for values in the parent table. If they are there and greater than all child values, use that instead
        -- This allows maintenance to continue working properly if there is a large gap in data insertion. Data will remain in parent, but new tables will be created
        EXECUTE format('SELECT max(%I) FROM ONLY %I.%I', v_row.control, v_parent_schema, v_parent_tablename) INTO v_max_id_parent;
        IF v_max_id_parent > v_current_partition_id THEN
            SELECT suffix_id INTO v_current_partition_id FROM @extschema@.show_partition_name(v_row.parent_table, v_max_id_parent::text);
        END IF;
        IF v_current_partition_id IS NULL THEN
            -- Partition set is completely empty. Nothing to do
            CONTINUE;
        END IF;

        v_id_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;
        v_last_partition_id = substring(v_last_partition from v_id_position)::bigint;
        -- Determine if this table is a child of a subpartition parent. If so, get limits to see if run_maintenance even needs to run for it.
        SELECT sub_min::bigint, sub_max::bigint INTO v_sub_id_min, v_sub_id_max FROM @extschema@.check_subpartition_limits(v_row.parent_table, 'id');
        IF v_sub_id_max IS NOT NULL THEN
            SELECT suffix_id INTO v_sub_id_max_suffix FROM @extschema@.show_partition_name(v_row.parent_table, v_sub_id_max::text);
            IF v_sub_id_max_suffix = v_last_partition_id THEN
                -- Final partition for this set is created. Set full and skip it
                UPDATE @extschema@.part_config SET sub_partition_set_full = true WHERE parent_table = v_row.parent_table;
                CONTINUE;
            END IF;
        END IF;

        v_next_partition_id := v_last_partition_id;
        v_premade_count := ((v_last_partition_id - v_current_partition_id) / v_row.partition_interval::bigint);
        -- Loop premaking until config setting is met. Allows it to catch up if it fell behind or if premake changed.
        WHILE (v_premade_count < v_row.premake) LOOP
            IF p_debug THEN
                RAISE NOTICE 'run_maint: parent_table: %, v_premade_count: %, v_next_partition_id: %', v_row.parent_table, v_premade_count, v_next_partition_id;
            END IF;
            IF v_next_partition_id < v_sub_id_min OR v_next_partition_id > v_sub_id_max THEN
                -- With subpartitioning, no need to run if the id is not in the parent table's range
                EXIT;
            END IF;
            v_next_partition_id := v_next_partition_id + v_row.partition_interval::bigint;
            v_last_partition_created := @extschema@.create_partition_id(v_row.parent_table, ARRAY[v_next_partition_id], p_analyze);
            IF v_last_partition_created THEN
                v_create_count := v_create_count + 1;
                PERFORM @extschema@.create_function_id(v_row.parent_table, v_job_id);
            END IF;
            v_premade_count := ((v_next_partition_id - v_current_partition_id) / v_row.partition_interval::bigint);
        END LOOP;

    END IF; -- end main IF check for time or id

    -- Manage additonal constraints if set
    PERFORM @extschema@.apply_constraints(p_parent_table := v_row.parent_table, p_job_id := v_job_id, p_debug := p_debug);

END LOOP; -- end of creation loop

-- Manage dropping old partitions if retention option is set
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND
        (partition_type = 'time' OR partition_type = 'time-custom')
LOOP
    IF p_parent_table IS NULL THEN
        v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
    ELSE -- Only run retention on table given in parameter
        IF p_parent_table <> v_row.parent_table THEN
            CONTINUE;
        ELSE
            v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
        END IF;
    END IF;
    IF v_drop_count > 0 THEN
        PERFORM @extschema@.create_function_time(v_row.parent_table, v_job_id);
    END IF;
END LOOP;
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND partition_type = 'id'
LOOP
    IF p_parent_table IS NULL THEN
        v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
    ELSE -- Only run retention on table given in parameter
        IF p_parent_table <> v_row.parent_table THEN
            CONTINUE;
        ELSE
            v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
        END IF;
    END IF;
    IF v_drop_count > 0 THEN
        PERFORM @extschema@.create_function_id(v_row.parent_table, v_job_id);
    END IF;
END LOOP;

IF v_jobmon_schema IS NOT NULL THEN
    EXECUTE format('SELECT %I.update_step(%L, %L, ''Partition maintenance finished. %s partitions made. %s partitions dropped.'')'
        , v_jobmon_schema
        , v_step_id
        , 'OK'
        , v_create_count
        , v_drop_count);
    IF v_step_overflow_id IS NOT NULL OR v_step_serial_id IS NOT NULL THEN
        EXECUTE format('SELECT %I.fail_job(%L)', v_jobmon_schema, v_job_id);
    ELSE
        EXECUTE format('SELECT %I.close_job(%L)', v_jobmon_schema, v_job_id);
    END IF;
END IF;

EXCEPTION
    WHEN OTHERS THEN
        GET STACKED DIAGNOSTICS ex_message = MESSAGE_TEXT,
                                ex_context = PG_EXCEPTION_CONTEXT,
                                ex_detail = PG_EXCEPTION_DETAIL,
                                ex_hint = PG_EXCEPTION_HINT;
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE format('SELECT %I.add_job(''PARTMAN RUN MAINTENANCE'')', v_jobmon_schema) INTO v_job_id;
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before job logging started'')', v_jobmon_schema, v_job_id, p_parent_table) INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE format('SELECT %I.add_step(%s, ''EXCEPTION before first step logged'')', v_jobmon_schema, v_job_id) INTO v_step_id;
            END IF;
            EXECUTE format('SELECT %I.update_step(%s, ''CRITICAL'', %L)', v_jobmon_schema, v_step_id, 'ERROR: '||coalesce(SQLERRM,'unknown'));
            EXECUTE format('SELECT %I.fail_job(%s)', v_jobmon_schema, v_job_id);
        END IF;
        RAISE EXCEPTION '%
CONTEXT: %
DETAIL: %
HINT: %', ex_message, ex_context, ex_detail, ex_hint;
END
$$;

Explanation: SQL definition from the open-source pg_partman PostgreSQL project.


Question: PostgreSQL regression test 'json': Write the SELECT query (example 8).

SELECT row_to_json(row((select array_agg(x) as d from generate_series(5,10) x)),false);

Explanation: Regression test for Json in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT row_to_json(row((select array_agg(x) as d from generate_series(5,10) x)),false)) AS _sub;


Question: PostgreSQL regression test 'pg_dependencies': Write the SELECT query (example 62).

SELECT '[{"attributes" : [1,2], "dependency" : {}, "degree": 1.0}]'::pg_dependencies;

Explanation: Regression test for Pg Dependencies in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '[{"attributes" : [1,2], "dependency" : {}, "degree": 1.0}]'::pg_dependencies) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 388).

create table rule_and_refint_t2 (
	id2a integer,
	id2c integer,

	primary key (id2a, id2c)
);

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: PostgreSQL regression test 'aggregates': Write the SELECT query (example 86).

SELECT corr(g, 0.09), regr_r2(g, 0.09), regr_slope(g, 0.09), regr_intercept(g, 0.09)
  FROM generate_series(1, 30) g;

Explanation: Regression test for Aggregates in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT corr(g, 0.09), regr_r2(g, 0.09), regr_slope(g, 0.09), regr_intercept(g, 0.09)
  FROM generate_series(1, 30) g) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'hash_index' (example 48).

UPDATE hash_f8_heap
   SET seqno = 20000
   WHERE hash_f8_heap.random = '488912369'::float8;

Explanation: DML from PostgreSQL core regression test for Hash Index.


Question: PostgreSQL regression test 'rangetypes': Write the SELECT query (example 262).

select count(*) from test_range_spgist where ir @> 10;

Explanation: Regression test for Rangetypes in PostgreSQL core test suite.

SELECT count(*) FROM (select count(*) from test_range_spgist where ir @> 10) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'citext' (example 287).

INSERT INTO caster (bitv)          VALUES ('101'::citext);

Explanation: Example query from the 'citext' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'pg_buffercache' (example 37).

SELECT * FROM pg_buffercache_mark_dirty(:max_buffers);

Explanation: Example query from the 'pg_buffercache' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 216).

insert into rtest_nothn4 values (30, 'don''t want this');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: PostgreSQL regression test 'stats_import': Write the SELECT query (example 224).

SELECT pg_catalog.pg_restore_extended_stats(
  'schemaname', 'stats_import',
  'relname', 'test',
  'statistics_schemaname', 'stats_import',
  'statistics_name', 'test_stat_mcv',
  'inherited', false,
  'most_common_vals', '{{four,NULL},
                        {one,"(1,1.1,ONE,01-01-2001,\"{\"\"xkey\"\": \"\"xval\"\"}\")"},
                        {tre,"(3,3.3,TRE,03-03-2003,)"},
                        {two,"(2,2.2,TWO,02-02-2002,\"[true, 4, \"\"six\"\"]\")"}}'::text[],
  'most_common_freqs', '{0.25,0.25,0.25,0.25}'::double precision[]);

Explanation: Regression test for Stats Import in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_catalog.pg_restore_extended_stats(
  'schemaname', 'stats_import',
  'relname', 'test',
  'statistics_schemaname', 'stats_import',
  'statistics_name', 'test_stat_mcv',
  'inherited', false,
  'most_common_vals', '{{four,NULL},
                        {one,"(1,1.1,ONE,01-01-2001,\"{\"\"xkey\"\": \"\"xval\"\"}\")"},
                        {tre,"(3,3.3,TRE,03-03-2003,)"},
                        {two,"(2,2.2,TWO,02-02-2002,\"[true, 4, \"\"six\"\"]\")"}}'::text[],
  'most_common_freqs', '{0.25,0.25,0.25,0.25}'::double precision[])) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'constraints' (example 185).

UPDATE unique_tbl SET i = 2 WHERE i = 4 AND t = 'four';

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 796).

Explanation: Regression test for Jsonb Jsonpath in PostgreSQL core test suite.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 492).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: PostgreSQL regression test 'groupingsets': Write the SELECT query (example 66).

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);

Explanation: Regression test for Groupingsets in PostgreSQL core test suite.

SELECT count(*) FROM (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)) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pg_trgm' (example 12).

Explanation: Example query from the 'pg_trgm' extension test/demo.


Question: PostgreSQL regression test 'timestamp': Write the SELECT query (example 129).

select date_bin('365000 days'::interval, '4400-01-01 BC'::timestamp, '4000-01-01 BC'::timestamp);

Explanation: Regression test for Timestamp in PostgreSQL core test suite.

SELECT count(*) FROM (select date_bin('365000 days'::interval, '4400-01-01 BC'::timestamp, '4000-01-01 BC'::timestamp)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 360).

INSERT INTO num_exp_add VALUES (8,7,'-82953604');


Question: Show a query using PostgreSQL contrib extension 'cube' (example 82).

Explanation: Example query from the 'cube' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'timestamptz' (example 58).

INSERT INTO TIMESTAMPTZ_TBL VALUES ('97FEB10 5:32:01PM UTC');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 159).

Explanation: Regression test for Arrays in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT ARRAY[1,2] || ARRAY[3,4] AS "{1,2,3,4}") AS _sub;


Question: pgTAP test for Valueset (assertion 302).

-- Fail with an extra record.
SELECT * FROM check_test(
    set_eq(
        'justnames',
        ARRAY['Andrew', 'Anna', 'Antonio', 'Angelina', 'Andrea', 'Angel' ]
    ),
    false,
    'set_eq(prepared, array) extra record',
    '',
    '    Extra records:
        (Anthony)'
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


Question: PL/pgSQL test: Plpgsql Cache (example 7).

$$;

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');

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Cache.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 78).

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '[1,1,2]'::jsonb @> '[1,2,2]'::jsonb) AS _sub;


Question: Show a SQL definition from the timescaledb project (size_utils, item 3).

CREATE OR REPLACE FUNCTION _timescaledb_functions.relation_approximate_size(relation REGCLASS)
RETURNS TABLE (total_size BIGINT, heap_size BIGINT, index_size BIGINT, toast_size BIGINT)
AS '@MODULE_PATHNAME@', 'ts_relation_approximate_size' LANGUAGE C STRICT VOLATILE;

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 603).

ALTER EXTENSION pgtap ADD FUNCTION _do_ne( TEXT, TEXT, TEXT, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: PostgreSQL regression test 'pg_ndistinct': Write the SELECT query (example 12).

SELECT '[{"attributes" : [2,3], "invalid" : 3, "ndistinct" : 4}]'::pg_ndistinct;

Explanation: Regression test for Pg Ndistinct in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '[{"attributes" : [2,3], "invalid" : 3, "ndistinct" : 4}]'::pg_ndistinct) AS _sub;


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 215).

SELECT count(*) FROM (select null::int = all ('{1,2,3}')) AS _sub;


Question: PL/pgSQL test: Plpgsql Domain (example 4).

SELECT * FROM test_argresult_booltrue(false, true);

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Domain.


Question: pgTAP test for Ownership (assertion 102).

/****************************************************************************/
-- Test index_owner_is().
SELECT * FROM check_test(
    index_owner_is('someschema', 'anothertab', 'idx_name', current_user, 'mumble'),
	true,
    'index_owner_is(schema, table, index, user, desc)',
    'mumble',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


Question: PostgreSQL regression test 'object_address': Write the SELECT query (example 48).

SELECT pg_get_object_address('schema', '{one}', '{}');

Explanation: Regression test for Object Address in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_get_object_address('schema', '{one}', '{}')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'numeric_big' (example 263).

Explanation: DML from PostgreSQL core regression test for Numeric Big.


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 969).

CREATE TABLE ref1_2 PARTITION OF ref FOR VALUES IN (1, 2) PARTITION BY list (f2);

Explanation: DDL from PostgreSQL core regression test for Foreign Key.


Question: pgTAP test for Policy (assertion 20).

SELECT * FROM check_test(
    policies_are( 'public', 'passwd', ARRAY['root_all', 'all_view', 'user_mod', 'daemon_insert', 'daemon_delete'] ),
    true,
    'policies_are(schema, table, policies)',
    'Table public.passwd should have the correct policies',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 5).

CREATE TABLE prt1_p2 PARTITION OF prt1 FOR VALUES FROM (250) TO (500);

Explanation: DDL from PostgreSQL core regression test for Partition Join.


Question: Write the DDL statement from PostgreSQL regression test 'rules' (example 36).

create rule rtest_t6_ins as on insert to rtest_t6
		where new.a > 25 do instead
	insert into rtest_t8 values (new.a, new.b);

Explanation: DDL from PostgreSQL core regression test for Rules.


Question: Write the DDL statement from PostgreSQL regression test 'partition_split' (example 1).

Explanation: DDL from PostgreSQL core regression test for Partition Split.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 286).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Write the DDL statement from PostgreSQL regression test 'partition_split' (example 109).

CREATE TABLE sales (salesperson_id INT REFERENCES salespeople(salesperson_id), sales_amount INT, sales_date DATE);


Question: PostgreSQL regression test 'create_operator': Write the SELECT query (example 21).

Explanation: Regression test for Create Operator in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT false<=-1 BETWEEN 1 AND 1) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'replica_identity' (example 8).

CREATE UNIQUE INDEX test_replica_identity_expr ON test_replica_identity (keya, keyb, (3));

Explanation: DDL from PostgreSQL core regression test for Replica Identity.


Question: Show a query using PostgreSQL contrib extension 'pgstattuple' (example 27).

Explanation: Example query from the 'pgstattuple' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'arrays' (example 300).

INSERT INTO arraggtest (f1, f2, f3) VALUES
('{}','{{pink,white,blue,red,grey,orange}}','{2.1,1.87,1.4,2.2}');

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: Write the DDL statement from PostgreSQL regression test 'create_view' (example 177).

create view vv1 as select * from (tt5 cross join tt6) j(aa,bb,cc,dd);

Explanation: DDL from PostgreSQL core regression test for Create View.


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 219).

SELECT to_tsquery('english', '1 <-> (2 <-> a)');

Explanation: Regression test for Tsearch in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT to_tsquery('english', '1 <-> (2 <-> a)')) AS _sub;


Question: PostgreSQL regression test 'sqljson_queryfuncs': Write the SELECT query (example 69).

SELECT JSON_VALUE(jsonb '1', 'strict $.a' DEFAULT 'error' ON ERROR);

Explanation: Regression test for Sqljson Queryfuncs in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '1', 'strict $.a' DEFAULT 'error' ON ERROR)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 524).

CREATE TABLE plt2_adv_p2 PARTITION OF plt2_adv FOR VALUES IN (NULL);


Question: pgTAP test for Functap (assertion 325).

-- Test diagnostics
SELECT * FROM check_test(
    is_window( 'nooo' ),
    false,
    'is_window(nowin)',
    'Function nooo() should be a window function',
    '    Function nooo() does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 140).

Explanation: Example query from the 'ltree' extension test/demo.


Question: PostgreSQL regression test 'sqljson_queryfuncs': Write the SELECT query (example 85).

SELECT JSON_VALUE(jsonb 'null', '$a' PASSING point ' (1, 2 )' AS a RETURNING point);

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb 'null', '$a' PASSING point ' (1, 2 )' AS a RETURNING point)) AS _sub;


Question: PostgreSQL regression test 'polymorphism': Write the SELECT query (example 161).

select f3, myaggn08a(f1) from t group by f3 order by f3;

Explanation: Regression test for Polymorphism in PostgreSQL core test suite.

SELECT count(*) FROM (select f3, myaggn08a(f1) from t group by f3 order by f3) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'rowsecurity' (example 1175).

CREATE POLICY p4 ON rls_tbl FOR DELETE USING (c1 <= 3);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PL/pgSQL test: Plpython Trigger (example 127).

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
$$;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Trigger.


Question: PostgreSQL regression test 'pg_ndistinct': Write the SELECT query (example 37).

SELECT '[{"attributes" : [2,3], "ndistinct" : null}]'::pg_ndistinct;

Explanation: Regression test for Pg Ndistinct in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '[{"attributes" : [2,3], "ndistinct" : null}]'::pg_ndistinct) AS _sub;


Question: pgTAP test for Functap (assertion 353).

SELECT * FROM check_test(
    is_strict( 'yay', 'whatever' ),
    true,
    'is_strict(func, desc)',
    'whatever',
    ''
);


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 32).

--
-- PGP key ID
--
CREATE FUNCTION pgp_key_id(bytea)
RETURNS text
AS 'MODULE_PATHNAME', 'pgp_key_id_w'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'encoding' (example 58).

Explanation: PL/pgSQL object from PostgreSQL core test for Encoding.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'update' (example 104).

-- 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();

Explanation: PL/pgSQL object from PostgreSQL core test for Update.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 170).

CREATE FUNCTION gbt_macad_union(internal, internal)
RETURNS gbtreekey16
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


Question: Write the DDL statement from PostgreSQL regression test 'partition_split' (example 190).

CREATE TABLE sales_all PARTITION OF sales_list FOR VALUES IN ('Warsaw', 'Lisbon', 'New York', 'Madrid', 'Beijing', 'Berlin', 'Delhi', 'Kyiv', 'Vladivostok', NULL);

Explanation: DDL from PostgreSQL core regression test for Partition Split.


Question: PL/pgSQL test: Pltcl Subxact (example 5).

INSERT INTO subtransaction_tbl VALUES(0);

Explanation: PL/pgSQL example from PostgreSQL source test for Pltcl Subxact.


Question: Show a query using PostgreSQL contrib extension 'hstore' (example 137).

select pg_column_size(slice(hstore 'aa=>1, b=>2, c=>3', ARRAY['c','b','aa']))
         = pg_column_size('aa=>1, b=>2, c=>3'::hstore);

Explanation: Example query from the 'hstore' extension test/demo.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 7).

CREATE FUNCTION gbt_ts_fetch(internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT;


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 284).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: PostgreSQL regression test 'tsearch': Write the SELECT query (example 2).

SELECT oid, dictname
FROM pg_ts_dict
WHERE dictnamespace = 0 OR dictowner = 0 OR dicttemplate = 0;

SELECT count(*) FROM (SELECT oid, dictname
FROM pg_ts_dict
WHERE dictnamespace = 0 OR dictowner = 0 OR dicttemplate = 0) AS _sub;


Question: PostgreSQL regression test 'window': Write the SELECT query (example 159).

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);

Explanation: Regression test for Window in PostgreSQL core test suite.

SELECT count(*) FROM (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)) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'citext' (example 271).

INSERT INTO caster (path)          VALUES ('((0,0),(1,1),(2,0))'::citext);

Explanation: Example query from the 'citext' extension test/demo.


Question: Show a SQL definition from the citus project (multi_partitioning, item 9).

CREATE TABLE partitioning_hash_test_0 PARTITION OF partitioning_hash_test FOR VALUES WITH (MODULUS 3, REMAINDER 0);

Explanation: SQL definition from the open-source citus PostgreSQL project.


Question: pgTAP test for Inheritance (assertion 144).

SELECT * FROM check_test(
    isnt_descendent_of( 'nope', 'parent' ),
    true,
    'isnt_descendent_of(nope, ptab)',
    'Table nope should not be a descendent of parent',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 120).

--GiST support for ltree[]
CREATE FUNCTION _ltree_consistent(internal,_ltree,int2,oid,internal)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


Question: PostgreSQL regression test 'timestamptz': Write the SELECT query (example 303).

SELECT '2011-03-27 03:00:01'::timestamp AT TIME ZONE 'MSK';

Explanation: Regression test for Timestamptz in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT '2011-03-27 03:00:01'::timestamp AT TIME ZONE 'MSK') AS _sub;


Question: PL/pgSQL test: Plpython Trigger (example 55).

-- Unicode variant

CREATE FUNCTION stupid3u() RETURNS trigger
AS $$
    return "foo"
$$ LANGUAGE plpython3u;


Question: PostgreSQL regression test 'merge': Write the SELECT query (example 507).

SELECT tableoid::regclass, * FROM measurement ORDER BY city_id, logdate;

Explanation: Regression test for Merge in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT tableoid::regclass, * FROM measurement ORDER BY city_id, logdate) AS _sub;


Question: pgTAP test for Functap (assertion 42).

SELECT * FROM check_test(
    hasnt_function( 'decode', '{text,text}'::name[] ),
    false,
    'simple function with 2 args',
    'Function decode(text, text) should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 813).

INSERT INTO num_input_test(n1) VALUES ('0x__1234');


Question: PostgreSQL regression test 'arrays': Write the SELECT query (example 306).

Explanation: Regression test for Arrays in PostgreSQL core test suite.

SELECT count(*) FROM (select * from comptable) AS _sub;


Question: Show a SQL definition from the timescaledb project (compat, item 14).

CREATE OR REPLACE FUNCTION _timescaledb_internal.drop_chunk(chunk regclass) RETURNS boolean LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.drop_chunk(regclass) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN _timescaledb_functions.drop_chunk($1);
END$$
SET search_path TO pg_catalog,pg_temp;

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 13).

SELECT count(*) FROM timestamptmp WHERE a  = '2004-10-26 08:55:08'::timestamp;

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 683).

ALTER EXTENSION pgtap ADD FUNCTION domain_type_is( NAME, TEXT, NAME, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: Write the DML statement from PostgreSQL regression test 'insert' (example 117).

insert into part_default values ('aa', 2);

Explanation: DML from PostgreSQL core regression test for Insert.


Question: Write the DML statement from PostgreSQL regression test 'constraints' (example 54).

INSERT INTO INSERT_TBL VALUES (7, '!check failed', -7);

Explanation: DML from PostgreSQL core regression test for Constraints.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 648).

ALTER EXTENSION pgtap ADD FUNCTION isa_ok( anyelement, regtype );


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 647).

ALTER EXTENSION pgtap ADD FUNCTION isa_ok( anyelement, regtype, TEXT );


Question: Write the DML statement from PostgreSQL regression test 'brin_multi' (example 59).

UPDATE brintest_multi SET int8col = int8col * int4col;

Explanation: DML from PostgreSQL core regression test for Brin Multi.


Question: pgTAP test for Pgtap--1.0.0--1.1.0 (assertion 12).

-- _keys( table, constraint_type )
CREATE OR REPLACE FUNCTION _keys ( NAME, CHAR )
RETURNS SETOF NAME[] AS $$
    SELECT _pg_sv_column_array(x.conrelid,x.conkey) -- name[] doesn't support collation
      FROM pg_catalog.pg_class c
      JOIN pg_catalog.pg_constraint x  ON c.oid = x.conrelid
       AND c.relname = $1
       AND x.contype = $2
     WHERE pg_catalog.pg_table_is_visible(c.oid)
  ORDER BY 1
$$ LANGUAGE sql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.0.0--1.1.0.


Question: Write the DML statement from PostgreSQL regression test 'box' (example 4).

Explanation: DML from PostgreSQL core regression test for Box.


Question: Write the DML statement from PostgreSQL regression test 'arrays' (example 43).

UPDATE arrtest
  SET c[NULL:1] = '{"can''t assign"}'
  WHERE array_dims(c) is not null;

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: Write the DML statement from PostgreSQL regression test 'join' (example 224).

insert into tt3 select x, repeat('xyzzy', 100) from generate_series(1,10000) x;

Explanation: DML from PostgreSQL core regression test for Join.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 240).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: pgTAP test for Resultset (assertion 263).

-- Handle fail with a dupe.
SELECT * FROM check_test(
    set_ne(
        'SELECT 1 AS a, ''Anna''::text UNION ALL SELECT 86, ''Angelina'' UNION ALL SELECT 1, ''Anna''',
        'SELECT 1 AS a, ''Anna''::text UNION ALL SELECT 86, ''Angelina'''
    ),
    false,
    'set_ne fail with dupe',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Write the DML statement from PostgreSQL regression test 'timestamp' (example 57).

INSERT INTO TIMESTAMP_TBL VALUES ('97/02/10 17:32:01 UTC');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 177).

CREATE FUNCTION gbt_bpchar_compress(internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: PostgreSQL regression test 'stats_ext': Write the SELECT query (example 606).

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND b AND NOT c');

Explanation: Regression test for Stats Ext in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists_bool WHERE NOT a AND b AND NOT c')) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'numeric_big' (example 91).

Explanation: DML from PostgreSQL core regression test for Numeric Big.


Question: PostgreSQL regression test 'join': Write the SELECT query (example 706).

select *, (select r from (select q1 as q2) x, lateral (select q2 as r) y) from int8_tbl;

Explanation: Regression test for Join in PostgreSQL core test suite.

SELECT count(*) FROM (select *, (select r from (select q1 as q2) x, lateral (select q2 as r) y) from int8_tbl) AS _sub;


Question: PostgreSQL Xfunc: show example 53.

SELECT mleast(ARRAY[10, -1, 5, 4.4]); -- doesn't work;

Explanation: Example from PostgreSQL documentation on Xfunc.


Question: pgTAP test for Functap (assertion 34).

SELECT * FROM check_test(
    hasnt_function( 'pg_catalog', 'now'::name ),
    false,
    'simple schema.function',
    'Function pg_catalog.now() should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: Write the DML statement from PostgreSQL regression test 'line' (example 21).

INSERT INTO LINE_TBL VALUES (line(point '(1,0)', point '(1,0)'));

Explanation: DML from PostgreSQL core regression test for Line.


Question: PostgreSQL regression test 'uuid': Write the SELECT query (example 17).

SELECT guid_field FROM guid1 ORDER BY guid_field DESC;

Explanation: Regression test for Uuid in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT guid_field FROM guid1 ORDER BY guid_field DESC) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 13).

SELECT count(*) FROM moneytmp WHERE a  = '22649.64'::money;

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 669).

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (select '{"aa":1 , "b":2, "cq":3}'::jsonb || '{"cq":"l", "b":"g", "fg":false}') AS _sub;


Question: Show a SQL definition from the citus project (chbenchmark_all_queries, item 14).

CREATE TABLE item (
    i_id int NOT NULL,
    i_name varchar(24) NOT NULL,
    i_price decimal(5,2) NOT NULL,
    i_data varchar(50) NOT NULL,
    i_im_id int NOT NULL,
    PRIMARY KEY (i_id)
);

Explanation: SQL definition from the open-source citus PostgreSQL project.


Question: pgTAP test for Functap (assertion 176).

SELECT * FROM check_test(
    isnt_normal_function( 'public', 'tap_accum'::name ),
    true,
    'isnt_normal_function(schema, agg)',
    'Function public.tap_accum() should not be a normal function',
    ''
);


Question: Show a SQL definition from the citus project (multi_behavioral_analytics_create_table, item 46).

CREATE INDEX is_index6 ON events_table(value_2);


Question: Show a query using PostgreSQL contrib extension 'btree_gin' (example 17).

SELECT * FROM test_int8 WHERE i<1::int4 ORDER BY i;

Explanation: Example query from the 'btree_gin' extension test/demo.


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 105).

Explanation: Regression test for Jsonb Jsonpath in PostgreSQL core test suite.

SELECT count(*) FROM (select * from jsonb_path_query('[1,"1",2,"2",null]', '$[*] ? (@ == $value)', '{"value" : "1"}')) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'rangefuncs' (example 363).

-- 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;

Explanation: PL/pgSQL object from PostgreSQL core test for Rangefuncs.


Question: Show a query using PostgreSQL contrib extension 'seg' (example 63).

Explanation: Example query from the 'seg' extension test/demo.


Question: pgTAP test for Pgtap--0.94.0--0.95.0 (assertion 25).

-- foreign_tables_are( tables )
CREATE OR REPLACE FUNCTION foreign_tables_are ( NAME[] )
RETURNS TEXT AS $$
    SELECT _are(
        'foreign tables', _extras('f', $1), _missing('f', $1),
        'Search path ' || pg_catalog.current_setting('search_path') || ' should have the correct foreign tables'
    );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.94.0--0.95.0.


Question: PostgreSQL regression test 'regproc': Write the SELECT query (example 126).

SELECT * FROM pg_input_error_info('-', 'regoperator');

Explanation: Regression test for Regproc in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('-', 'regoperator')) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'ltree' (example 320).

SELECT count(*) FROM ltreetest WHERE t ~ '23.*.2';

Explanation: Example query from the 'ltree' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 242).

insert into rtest_view1 values (2, 'item 2', 't');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'create_function_sql' (example 58).

-- check display of function arguments in sub-SELECT
CREATE TABLE functest1 (i int);

Explanation: PL/pgSQL object from PostgreSQL core test for Create Function Sql.


Question: Write the DML statement from PostgreSQL regression test 'generated_stored' (example 91).

INSERT INTO gtest3a (a) VALUES ('a'), ('b'), ('c'), (NULL);

Explanation: DML from PostgreSQL core regression test for Generated Stored.


Question: PostgreSQL regression test 'boolean': Write the SELECT query (example 20).

Explanation: Regression test for Boolean in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT bool 'on_' AS error) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'constraints' (example 376).

CREATE TABLE notnull_tbl4_lk2 (LIKE notnull_tbl4 INCLUDING INDEXES);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: Write the DDL statement from PostgreSQL regression test 'partition_join' (example 229).

CREATE TABLE prt3_n_p2 PARTITION OF prt3_n FOR VALUES IN ('0001', '0002', '0008', '0010');

Explanation: DDL from PostgreSQL core regression test for Partition Join.


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 25).

SELECT timestamp with time zone 'J2452271 04:05:06-08';

Explanation: Regression test for Horology in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT timestamp with time zone 'J2452271 04:05:06-08') AS _sub;


Question: PostgreSQL regression test 'copy': Write the SELECT query (example 9).

select * from copytest except select * from copytest2;

Explanation: Regression test for Copy in PostgreSQL core test suite.

SELECT count(*) FROM (select * from copytest except select * from copytest2) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'test_decoding' (example 31).

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');

Explanation: Example query from the 'test_decoding' extension test/demo.


Question: Show an example of PostgreSQL CREATE ROLE (example 2).

CREATE USER davide WITH PASSWORD 'jw8s0F4';

Explanation: PostgreSQL CREATE ROLE command.


Question: PL/pgSQL test: Plpython Spi (example 31).

-- 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;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Spi.


Question: pgTAP test for Pgtap--0.94.0--0.95.0 (assertion 7).

-- is_member_of( role, members[] )
CREATE OR REPLACE FUNCTION is_member_of( NAME, NAME[] )
RETURNS TEXT AS $$
    SELECT is_member_of( $1, $2, 'Should have members of role ' || quote_ident($1) );
$$ LANGUAGE SQL;


Question: PostgreSQL regression test 'select_distinct': Write the SELECT query (example 75).

SELECT 2 IS NOT DISTINCT FROM null as "no";

Explanation: Regression test for Select Distinct in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 2 IS NOT DISTINCT FROM null as "no") AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'triggers' (example 249).

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();

Explanation: DDL from PostgreSQL core regression test for Triggers.


Question: PL/pgSQL test: Pltcl Subxact (example 2).

--
-- 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;

Explanation: PL/pgSQL example from PostgreSQL source test for Pltcl Subxact.


Question: PostgreSQL regression test 'float8': Write the SELECT query (example 89).

SELECT power(float8 '-inf', float8 '-3');

Explanation: Regression test for Float8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT power(float8 '-inf', float8 '-3')) AS _sub;


Question: PostgreSQL regression test 'jsonpath': Write the SELECT query (example 51).

Explanation: Regression test for Jsonpath in PostgreSQL core test suite.

SELECT count(*) FROM (select '$.a[$a + 1, ($b[*]) to -($[0] * 2)]'::jsonpath) AS _sub;


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 19).

CREATE FUNCTION dblink_close (text, text)
RETURNS text
AS 'MODULE_PATHNAME','dblink_close'
LANGUAGE C STRICT PARALLEL RESTRICTED;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: Write the DDL statement from PostgreSQL regression test 'tablesample' (example 52).

create table parted_sample_1 partition of parted_sample for values in (1);

Explanation: DDL from PostgreSQL core regression test for Tablesample.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 122).

SELECT jsonb '{"a":null, "b":"qq"}' ? 'c';

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT jsonb '{"a":null, "b":"qq"}' ? 'c') AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'arrays' (example 107).

insert into arrtest_f values(2,'cat1',1.24);

Explanation: DML from PostgreSQL core regression test for Arrays.


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 14).

SELECT count(*) FROM int8tmp WHERE a >= 464571291354841::int8;

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 371).

ALTER EXTENSION pgtap ADD FUNCTION has_cast ( NAME, NAME, NAME, NAME, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: PostgreSQL regression test 'create_misc': Write the SELECT query (example 67).

SELECT class, c FROM e_star* x WHERE x.c NOTNULL;

Explanation: Regression test for Create Misc in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT class, c FROM e_star* x WHERE x.c NOTNULL) AS _sub;


Question: PostgreSQL regression test 'expressions': Write the SELECT query (example 66).

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);

Explanation: Regression test for Expressions in PostgreSQL core test suite.

SELECT count(*) FROM (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)) AS _sub;


Question: Show a SQL definition from the citus project (multi_agg_approximate_distinct, item 22).

CREATE TABLE test_count_distinct_schema.nation_hash(
    n_nationkey integer not null,
    n_name char(25) not null,
    n_regionkey integer not null,
    n_comment varchar(152)
);

Explanation: SQL definition from the open-source citus PostgreSQL project.


Question: PostgreSQL regression test 'window': Write the SELECT query (example 7).

SELECT depname, empno, salary, rank() OVER w FROM empsalary WINDOW w AS (PARTITION BY depname ORDER BY salary) ORDER BY rank() OVER w;

Explanation: Regression test for Window in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT depname, empno, salary, rank() OVER w FROM empsalary WINDOW w AS (PARTITION BY depname ORDER BY salary) ORDER BY rank() OVER w) AS _sub;


Question: pgTAP test for Index (assertion 70).

SELECT * FROM check_test(
    index_is_primary( 'sometab', 'sometab_pkey' ),
    true,
    'index_is_primary() no schema',
    'Index sometab_pkey should be on a primary key',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: Write the DML statement from PostgreSQL regression test 'int4' (example 6).

INSERT INTO INT4_TBL(f1) VALUES ('- 1234');

Explanation: DML from PostgreSQL core regression test for Int4.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 220).

-- Create the operator class (intentionally not DEFAULT)
CREATE OPERATOR CLASS gist_cidr_ops
FOR TYPE cidr USING gist
AS
	OPERATOR	1	<  (inet, inet) ,
	OPERATOR	2	<= (inet, inet) ,
	OPERATOR	3	=  (inet, inet) ,
	OPERATOR	4	>= (inet, inet) ,
	OPERATOR	5	>  (inet, inet) ,
	OPERATOR	6	<> (inet, inet) ,
	FUNCTION	1	gbt_inet_consistent (internal, inet, int2, oid, internal),
	FUNCTION	2	gbt_inet_union (internal, internal),
	FUNCTION	3	gbt_inet_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_inet_penalty (internal, internal, internal),
	FUNCTION	6	gbt_inet_picksplit (internal, internal),
	FUNCTION	7	gbt_inet_same (gbtreekey16, gbtreekey16, internal),
	-- no fetch support, the compress function is lossy
	FUNCTION	11	gbt_inet_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey16;


Question: Write the DDL statement from PostgreSQL regression test 'create_view' (example 47).

CREATE VIEW v6_temp AS SELECT * FROM base_table WHERE id IN (SELECT id FROM temp_table);

Explanation: DDL from PostgreSQL core regression test for Create View.


Question: PL/pgSQL test: Plpgsql Domain (example 75).

SELECT * FROM test_assign_ordered_named_pairs(1,2,0);  -- should fail someday

CREATE FUNCTION test_null_ordered_named_pair()
  RETURNS ordered_named_pair AS $$
declare v ordered_named_pair;
begin
return v;
end
$$ LANGUAGE plpgsql;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpgsql Domain.


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 292).

create table ab_a2_b2 partition of ab_a2 for values in (2);

Explanation: DDL from PostgreSQL core regression test for Partition Prune.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 352).

ALTER EXTENSION pgtap ADD FUNCTION _is_super( NAME );


Question: Write the DDL statement from PostgreSQL regression test 'rowtypes' (example 149).

CREATE FUNCTION price_key_from_table(price) RETURNS price_key AS $$
    SELECT $1.id
$$ LANGUAGE SQL;

Explanation: DDL from PostgreSQL core regression test for Rowtypes.


Question: Write the DML statement from PostgreSQL regression test 'rangetypes' (example 45).

INSERT INTO numrange_test VALUES('[3,]');

Explanation: DML from PostgreSQL core regression test for Rangetypes.


Question: PostgreSQL regression test 'sqljson_jsontable': Write the SELECT query (example 80).

SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text FORMAT JSON PATH '$' WITH WRAPPER KEEP QUOTES));

Explanation: Regression test for Sqljson Jsontable in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text FORMAT JSON PATH '$' WITH WRAPPER KEEP QUOTES))) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'fast_default' (example 3).

Explanation: DDL from PostgreSQL core regression test for Fast Default.


Question: Show a SQL definition from the pg_partman project (pg_partman--2.3.2--2.3.3, item 14).

/*
 * Function to create partitioning trigger on parent table
 */
CREATE OR REPLACE FUNCTION create_trigger(p_parent_table text) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_function_name         text;
v_new_length            int;
v_parent_schema         text;
v_parent_tablename      text;
v_trig_name             text;
v_trig_sql              text;

BEGIN

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_parent_table, '.', 1)::name
AND tablename = split_part(p_parent_table, '.', 2)::name;
v_trig_name := @extschema@.check_name_length(p_object_name := v_parent_tablename, p_suffix := '_part_trig');
-- Ensure function name matches the naming pattern
v_function_name := @extschema@.check_name_length(v_parent_tablename, '_part_trig_func', FALSE);
v_trig_sql := format('CREATE TRIGGER %I BEFORE INSERT ON %I.%I FOR EACH ROW EXECUTE PROCEDURE %I.%I()'
    , v_trig_name
    , v_parent_schema
    , v_parent_tablename
    , v_parent_schema
    , v_function_name);

EXECUTE v_trig_sql;

END
$$;

Explanation: SQL definition from the open-source pg_partman PostgreSQL project.


Question: PostgreSQL regression test 'partition_aggregate': Write the SELECT query (example 102).

SELECT a, sum(b), count(*) FROM pagg_tab_ml GROUP BY a HAVING avg(b) < 3 ORDER BY 1, 2, 3;

Explanation: Regression test for Partition Aggregate in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT a, sum(b), count(*) FROM pagg_tab_ml GROUP BY a HAVING avg(b) < 3 ORDER BY 1, 2, 3) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 707).

CREATE TABLE fk_partitioned_fk_2 (b int, a int,
	CONSTRAINT fk_part_con FOREIGN KEY (a, b) REFERENCES fk_notpartitioned_pk ON UPDATE CASCADE ON DELETE CASCADE NOT ENFORCED);

Explanation: DDL from PostgreSQL core regression test for Foreign Key.


Question: pgTAP test for Todotap (assertion 7).

SELECT is(
    fail('This is a todo test' ) || '
'
      || pass('This is a todo test that unexpectedly passes' ),
    'not ok 6 - This is a todo test # TODO
# Failed (TODO) test 6: "This is a todo test"
ok 7 - This is a todo test that unexpectedly passes # TODO ',
   'TODO tests should display properly'
);

Explanation: SQL assertion from pgTAP test suite for Todotap.


Question: PostgreSQL regression test 'polymorphism': Write the SELECT query (example 182).

select first_el_agg_f8(x::float8) from generate_series(1,10) x;

Explanation: Regression test for Polymorphism in PostgreSQL core test suite.

SELECT count(*) FROM (select first_el_agg_f8(x::float8) from generate_series(1,10) x) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pg_visibility' (example 22).

Explanation: Example query from the 'pg_visibility' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'partition_aggregate' (example 40).

CREATE TABLE pagg_tab1_p2 PARTITION OF pagg_tab1 FOR VALUES FROM (10) TO (20);

Explanation: DDL from PostgreSQL core regression test for Partition Aggregate.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 221).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: Write the DDL statement from PostgreSQL regression test 'lock' (example 10).

CREATE VIEW lock_view6 AS SELECT * from (select * from lock_tbl1) sub;

Explanation: DDL from PostgreSQL core regression test for Lock.


Question: Show a query using PostgreSQL contrib extension 'cube' (example 131).

Explanation: Example query from the 'cube' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'aggregates' (example 299).

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);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


Question: Show a SQL definition from the timescaledb project (truncate, item 13).

CREATE VIEW dependent_view AS SELECT * FROM _timescaledb_internal._hyper_1_5_chunk;

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: PostgreSQL regression test 'tidscan': Write the SELECT query (example 33).

Explanation: Regression test for Tidscan in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM tidscan) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'strings' (example 335).

INSERT INTO toasttest values (repeat('1234567890',300));

Explanation: DML from PostgreSQL core regression test for Strings.


Question: Write the DDL statement from PostgreSQL regression test 'publication' (example 655).

CREATE TABLE sch1.tbl1_part1 PARTITION OF sch1.tbl1 FOR VALUES FROM (1) to (10);

Explanation: DDL from PostgreSQL core regression test for Publication.


Question: Show a query using PostgreSQL contrib extension 'citext' (example 214).

INSERT INTO caster (text)          VALUES ('12'::int2);

Explanation: Example query from the 'citext' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'test_decoding' (example 18).

SELECT * FROM pg_stat_get_replication_slot('do-not-exist');

Explanation: Example query from the 'test_decoding' extension test/demo.


Question: PostgreSQL regression test 'name': Write the SELECT query (example 33).

Explanation: Regression test for Name in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT parse_ident(E'"c".X XXXX\002XXXXXX')) AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'create_operator' (example 45).

-- Should fail. Procedure should be mandatorily specified
CREATE OPERATOR #@%# (
   rightarg = int8
);

Explanation: PL/pgSQL object from PostgreSQL core test for Create Operator.


Question: PostgreSQL regression test 'interval': Write the SELECT query (example 178).

Explanation: Regression test for Interval in PostgreSQL core test suite.

SELECT count(*) FROM (select interval 'PT2562047788:00:54.775807') AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'create_role' (example 46).

Explanation: DDL from PostgreSQL core regression test for Create Role.


Question: PostgreSQL regression test 'jsonb_jsonpath': Write the SELECT query (example 176).

Explanation: Regression test for Jsonb Jsonpath in PostgreSQL core test suite.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 183).

CREATE FUNCTION isnne(issn, issn13)
	RETURNS boolean
	AS 'int8ne'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.


Question: Show a SQL definition from the zombodb project (issue-864, item 8).

CREATE OR REPLACE VIEW cake.cake_summary AS
SELECT brand.pk_brand_id,
       brand.brand_name,
       (SELECT json_agg(row_to_json(cj.*)) AS json_agg
        FROM (SELECT flavor.pk_flavor,
                     flavor.flv_name,
                     flavor.flv_color
              FROM cake.flavor
              WHERE (brand.pk_brand_id = flavor.fk_flv_to_bd)) cj)::json AS flavor_data,
       cake.zdb_cake_bd_to_flavor(brand.*)                               AS zdb
FROM cake.brand;

Explanation: SQL definition from the open-source zombodb PostgreSQL project.


Question: PostgreSQL regression test 'window': Write the SELECT query (example 69).

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);

Explanation: Regression test for Window in PostgreSQL core test suite.

SELECT count(*) FROM (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)) AS _sub;


Question: Show a SQL definition from the citus project (multi_alter_table_add_foreign_key_without_name, item 10).

CREATE TABLE self_referencing_table(id int, ref_id int, PRIMARY KEY (id, ref_id));

Explanation: SQL definition from the open-source citus PostgreSQL project.


Question: Write the DDL statement from PostgreSQL regression test 'equivclass' (example 7).

create function int8alias2out(int8alias2) returns cstring
  strict immutable language internal as 'int8out';

Explanation: DDL from PostgreSQL core regression test for Equivclass.


Question: Show a SQL definition from the pg_partman project (pg_partman--1.8.0--1.8.1, item 1).

/*
 * Apply constraints managed by partman extension
 */
CREATE OR REPLACE FUNCTION apply_constraints(p_parent_table text, p_child_table text DEFAULT NULL, p_analyze boolean DEFAULT FALSE, p_debug boolean DEFAULT FALSE) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

v_child_table                   text;
v_child_tablename               text;
v_col                           text;
v_constraint_cols               text[];
v_constraint_col_type           text;
v_constraint_name               text;
v_datetime_string               text;
v_existing_constraint_name      text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_id             int;
v_last_partition_timestamp      timestamp;
v_constraint_values             record;
v_old_search_path               text;
v_parent_schema                 text;
v_parent_tablename              text;
v_part_interval                 text;
v_partition_suffix              text;
v_premake                       int;
v_sql                           text;
v_step_id                       bigint;
v_suffix_position               int;
v_type                          text;

BEGIN

SELECT type
    , part_interval
    , premake
    , datetime_string
    , constraint_cols
    , jobmon
INTO v_type
    , v_part_interval
    , v_premake
    , v_datetime_string
    , v_constraint_cols
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

IF v_constraint_cols IS NULL THEN
    IF p_debug THEN
        RAISE NOTICE 'Given parent table (%) not set up for constraint management (constraint_cols is NULL)', p_parent_table;
    END IF;
    -- Returns silently to allow this function to be simply called by maintenance processes without having to check if config options are set.
    RETURN;
END IF;

SELECT show_partitions INTO v_last_partition FROM @extschema@.show_partitions(p_parent_table, 'DESC') LIMIT 1;

IF v_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        SELECT current_setting('search_path') INTO v_old_search_path;
        EXECUTE 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
    END IF;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN CREATE CONSTRAINT: '||p_parent_table);
END IF;

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;

-- If p_child_table is null, figure out the partition that is the one right before the premake value backwards.
IF p_child_table IS NULL THEN

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Automatically determining most recent child on which to apply constraints');
    END IF;

    v_suffix_position := (length(v_last_partition) - position('p_' in reverse(v_last_partition))) + 2;

    IF v_type IN ('time-static', 'time-dynamic') THEN
        v_last_partition_timestamp := to_timestamp(substring(v_last_partition from v_suffix_position), v_datetime_string);
        v_partition_suffix := to_char(v_last_partition_timestamp - (v_part_interval::interval * ((v_premake * 2)+1) ), v_datetime_string);
    ELSIF v_type IN ('id-static', 'id-dynamic') THEN
        v_last_partition_id := substring(v_last_partition from v_suffix_position)::int;
        v_partition_suffix := (v_last_partition_id - (v_part_interval::int * ((v_premake * 2)+1) ))::text;
    END IF;

    v_child_table := @extschema@.check_name_length(v_parent_tablename, v_parent_schema, v_partition_suffix, TRUE);

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Target child table: '||v_child_table);
    END IF;
ELSE
    v_child_table := p_child_table;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_step_id := add_step(v_job_id, 'Checking if target child table exists');
END IF;

SELECT tablename INTO v_child_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = v_child_table;
IF v_child_tablename IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'NOTICE', 'Target child table ('||v_child_table||') does not exist. Skipping constraint creation.');
        PERFORM close_job(v_job_id);
        EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Target child table (%) does not exist. Skipping constraint creation.', v_child_table;
    END IF;
    RETURN;
ELSE
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;
END IF;

FOREACH v_col IN ARRAY v_constraint_cols
LOOP
    SELECT c.conname
    INTO v_existing_constraint_name
    FROM pg_catalog.pg_constraint c
        JOIN pg_catalog.pg_attribute a ON c.conrelid = a.attrelid
    WHERE conrelid = v_child_table::regclass
        AND c.conname LIKE 'partmanconstr_%'
        AND c.contype = 'c'
        AND a.attname = v_col
        AND ARRAY[a.attnum] <@ c.conkey
        AND a.attisdropped = false;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Applying new constraint on column: '||v_col);
    END IF;

    IF v_existing_constraint_name IS NOT NULL THEN
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', 'Partman managed constraint already exists on this table ('||v_child_table||') and column ('||v_col||'). Skipping creation.');
        END IF;
        RAISE WARNING 'Partman managed constraint already exists on this table (%) and column (%). Skipping creation.', v_child_table, v_col ;
        CONTINUE;
    END IF;

    -- Ensure column name gets put on end of constraint name to help avoid naming conflicts
    v_constraint_name := @extschema@.check_name_length('partmanconstr_'||v_child_tablename, p_suffix := '_'||v_col);

    EXECUTE 'SELECT min('||v_col||')::text AS min, max('||v_col||')::text AS max FROM '||v_child_table INTO v_constraint_values;

    IF v_constraint_values IS NOT NULL THEN
        v_sql := concat('ALTER TABLE ', v_child_table, ' ADD CONSTRAINT ', v_constraint_name
            , ' CHECK (', v_col, ' >= ', quote_literal(v_constraint_values.min), ' AND '
            , v_col, ' <= ', quote_literal(v_constraint_values.max), ')' );
        IF p_debug THEN
            RAISE NOTICE 'Constraint creation query: %', v_sql;
        END IF;
        EXECUTE v_sql;

        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'OK', 'New constraint created: '||v_sql);
        END IF;
    ELSE
        IF p_debug THEN
            RAISE NOTICE 'Given column (%) contains all NULLs. No constraint created', v_col;
        END IF;
        IF v_jobmon_schema IS NOT NULL THEN
            PERFORM update_step(v_step_id, 'NOTICE', 'Given column ('||v_col||') contains all NULLs. No constraint created');
        END IF;
    END IF;

END LOOP;

IF p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Running analyze on partition set: '||p_parent_table);
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Running analyze on partition set: %', p_parent_table;
    END IF;

    EXECUTE 'ANALYZE '||p_parent_table;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM close_job(v_job_id);
    EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;

EXCEPTION
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            IF v_job_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_job(''PARTMAN CREATE CONSTRAINT: '||p_parent_table||''')' INTO v_job_id;
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before job logging started'')' INTO v_step_id;
            ELSIF v_step_id IS NULL THEN
                EXECUTE 'SELECT '||v_jobmon_schema||'.add_step('||v_job_id||', ''EXCEPTION before first step logged'')' INTO v_step_id;
            END IF;
            EXECUTE 'SELECT '||v_jobmon_schema||'.update_step('||v_step_id||', ''CRITICAL'', ''ERROR: '||coalesce(SQLERRM,'unknown')||''')';
            EXECUTE 'SELECT '||v_jobmon_schema||'.fail_job('||v_job_id||')';
        END IF;
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

Explanation: SQL definition from the open-source pg_partman PostgreSQL project.


Question: Write the DML statement from PostgreSQL regression test 'truncate' (example 3).

Explanation: DML from PostgreSQL core regression test for Truncate.


Question: Write the DDL statement from PostgreSQL regression test 'window' (example 89).

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;

Explanation: DDL from PostgreSQL core regression test for Window.


Question: PostgreSQL regression test 'unicode': Write the SELECT query (example 7).

SELECT normalize(U&'\0061\0308\24D1c', NFC) = U&'\00E4\24D1c' COLLATE "C" AS test_nfc;

Explanation: Regression test for Unicode in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT normalize(U&'\0061\0308\24D1c', NFC) = U&'\00E4\24D1c' COLLATE "C" AS test_nfc) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 14).

SELECT count(*) FROM int4tmp WHERE a >= 237::int4;

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'equivclass' (example 44).

create unique index ec1_expr1 on ec1((ff + 1));


Question: Write the DDL statement from PostgreSQL regression test 'domain' (example 155).

create domain dcomptype as comptype check ((value).cf1 > 0);

Explanation: DDL from PostgreSQL core regression test for Domain.


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 147).

CREATE TABLE FKTABLE ( ftest1 int, ftest2 int, ftest3 int, ftest4 int,  CONSTRAINT constrname3
			FOREIGN KEY(ftest1, ftest2, ftest3) REFERENCES PKTABLE (ptest1, ptest2, ptest3));

Explanation: DDL from PostgreSQL core regression test for Foreign Key.


Question: Write the DDL statement from PostgreSQL regression test 'create_schema' (example 15).

CREATE SCHEMA regress_schema_1 AUTHORIZATION CURRENT_ROLE
  CREATE VIEW schema_not_existing.view AS SELECT 1;

Explanation: DDL from PostgreSQL core regression test for Create Schema.


Question: PostgreSQL regression test 'tablespace': Write the SELECT query (example 68).

SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'foo_idx';

Explanation: Regression test for Tablespace in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT relname, spcname FROM pg_catalog.pg_tablespace t, pg_catalog.pg_class c
    where c.reltablespace = t.oid AND c.relname = 'foo_idx') AS _sub;


Question: PostgreSQL regression test 'temp': Write the SELECT query (example 101).

select relname from pg_class where relname ~ '^temp_parted_oncommit_test';

Explanation: Regression test for Temp in PostgreSQL core test suite.

SELECT count(*) FROM (select relname from pg_class where relname ~ '^temp_parted_oncommit_test') AS _sub;


Question: Show a SQL definition from the timescaledb project (partitioning, item 1).

-- Should expect an error when creating a hypertable from a partition
\set ON_ERROR_STOP 0
CREATE TABLE partitioned_ht_create(time timestamptz, temp float, device int) PARTITION BY RANGE (time);

Explanation: SQL definition from the open-source timescaledb PostgreSQL project.


Question: PostgreSQL Ddl: show example 81.

REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Explanation: Example from PostgreSQL documentation on Ddl.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'window' (example 123).

-- 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;

Explanation: PL/pgSQL object from PostgreSQL core test for Window.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 392).

Explanation: DML from PostgreSQL core regression test for Numeric.


Question: PostgreSQL regression test 'vacuum': Write the SELECT query (example 58).

SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_inh_parent'::regclass;

Explanation: Regression test for Vacuum in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT reltuples, relhassubclass
  FROM pg_class WHERE oid = 'past_inh_parent'::regclass) AS _sub;


Question: PL/pgSQL test: Plpython Populate (example 19).

INSERT INTO sequences (sequence, eid, product) VALUES ('ABCDEF', 5, 'env') ;

Explanation: PL/pgSQL example from PostgreSQL source test for Plpython Populate.


Question: Show a SQL definition from the timescaledb project (compat, item 2).

CREATE OR REPLACE FUNCTION _timescaledb_internal.attach_osm_table_chunk(hypertable regclass, chunk regclass) RETURNS boolean LANGUAGE PLPGSQL AS $$
BEGIN
  IF current_setting('timescaledb.enable_deprecation_warnings', true)::bool THEN
    RAISE WARNING 'function _timescaledb_internal.attach_osm_table_chunk(regclass,regclass) is deprecated and has been moved to _timescaledb_functions schema. this compatibility function will be removed in a future version.';
  END IF;
  RETURN _timescaledb_functions.attach_osm_table_chunk($1,$2);
END$$
SET search_path TO pg_catalog,pg_temp;


Question: pgTAP test for Functap (assertion 284).

SELECT * FROM check_test(
    is_window( 'someschema', 'huh'::name, 'whatever' ),
    false,
    'is_window(schema, func, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


Question: PL/pgSQL test: Plpython Populate (example 13).

INSERT INTO entry (accession, txid) VALUES ('A00006', '3') ;


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 925).

select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"boolean"');

Explanation: Regression test for Jsonb in PostgreSQL core test suite.

SELECT count(*) FROM (select jsonb_to_tsvector('english', '{"a": "aaa in bbb", "b": 123, "c": 456, "d": true, "f": false, "g": null}'::jsonb, '"boolean"')) AS _sub;


Question: PostgreSQL regression test 'constraints': Write the SELECT query (example 47).

Explanation: Regression test for Constraints in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM INSERT_TBL) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'partition_prune' (example 260).

create table hp1 partition of hp for values with (modulus 4, remainder 1);

Explanation: DDL from PostgreSQL core regression test for Partition Prune.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 619).

ALTER EXTENSION pgtap ADD FUNCTION set_hasnt( TEXT, TEXT, TEXT );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: PostgreSQL regression test 'jsonb': Write the SELECT query (example 465).

SELECT count(*) FROM testjsonb WHERE j @? '$.public';

SELECT count(*) FROM (SELECT count(*) FROM testjsonb WHERE j @? '$.public') AS _sub;


Question: PostgreSQL regression test 'horology': Write the SELECT query (example 55).

SELECT time without time zone 'T040506.07';

Explanation: Regression test for Horology in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT time without time zone 'T040506.07') AS _sub;


Question: Write the PL/pgSQL object from PostgreSQL regression test 'triggers' (example 581).

$$;
alter function whoami() owner to regress_fn_owner;

create table defer_trig (id integer);
grant insert on defer_trig to public;
create constraint trigger whoami after insert on defer_trig
  deferrable initially deferred
  for each row
  execute function whoami();

-- deferred triggers must run as the user that queued the trigger
begin;
set role regress_caller;
insert into defer_trig values (1);
reset role;
set role regress_fn_owner;
insert into defer_trig values (2);
reset role;
commit;

-- security definer functions override the user who queued the trigger
alter function whoami() security definer;
begin;
set role regress_caller;
insert into defer_trig values (3);
reset role;
commit;
alter function whoami() security invoker;

-- make sure the current user is restored after error
create or replace function whoami() returns trigger language plpgsql
as $$
begin
  raise notice 'I am %', current_user;

Explanation: PL/pgSQL object from PostgreSQL core test for Triggers.


Question: Write the DML statement from PostgreSQL regression test 'subselect' (example 144).

Explanation: DML from PostgreSQL core regression test for Subselect.


Question: Write the DML statement from PostgreSQL regression test 'jsonb' (example 431).

Explanation: DML from PostgreSQL core regression test for Jsonb.


Question: Write the DML statement from PostgreSQL regression test 'numeric' (example 279).


Question: PostgreSQL Queries: show example 30.

SELECT a + b AS sum, c FROM table1 ORDER BY sum; SELECT a, max(b) FROM table1 GROUP BY a ORDER BY 1;

Explanation: Example from PostgreSQL documentation on Queries.


Question: Show a SQL definition from the postgrest project (schema, item 7).

CREATE TABLE items AS SELECT x AS id FROM generate_series(1,5) x;

Explanation: SQL definition from the open-source postgrest PostgreSQL project.


Question: PostgreSQL regression test 'join': Write the SELECT query (example 727).

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);

Explanation: Regression test for Join in PostgreSQL core test suite.

SELECT count(*) FROM (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)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'rowsecurity' (example 352).

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;

Explanation: DML from PostgreSQL core regression test for Rowsecurity.


Question: Show a query using PostgreSQL contrib extension 'postgres_fdw' (example 1006).

SELECT count(*)
FROM pg_foreign_server
WHERE srvname = 'fetch101'
AND srvoptions @> array['fetch_size=202'];

Explanation: Example query from the 'postgres_fdw' extension test/demo.


Question: Show a query using PostgreSQL contrib extension 'cube' (example 13).

Explanation: Example query from the 'cube' extension test/demo.


Question: Write the DML statement from PostgreSQL regression test 'insert_conflict' (example 130).

insert into insertconflictv values (1,'foo')
  on conflict (f1) do update set f2 = excluded.f2;

Explanation: DML from PostgreSQL core regression test for Insert Conflict.


Question: Show a query using PostgreSQL contrib extension 'btree_gist' (example 11).

SELECT count(*) FROM inettmp WHERE a <= '89.225.196.191'::inet;

Explanation: Example query from the 'btree_gist' extension test/demo.


Question: Write the DDL statement from PostgreSQL regression test 'foreign_key' (example 1044).

CREATE TABLE fk (id int, a int DEFAULT 50) PARTITION BY RANGE (a);

Explanation: DDL from PostgreSQL core regression test for Foreign Key.


Question: Write the DML statement from PostgreSQL regression test 'foreign_key' (example 943).

INSERT INTO fk VALUES (1);		-- should fail
BEGIN;

Explanation: DML from PostgreSQL core regression test for Foreign Key.


Question: PostgreSQL regression test 'stats': Write the SELECT query (example 297).

SELECT pg_stat_have_stats('database', :dboid, 0);

Explanation: Regression test for Stats in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT pg_stat_have_stats('database', :dboid, 0)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'rules' (example 166).

insert into rtest_t9 values (28, 'Record should go to rtest_t4 and t8');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: pgTAP test for Pgtap--Unpackaged--0.91.0 (assertion 267).

ALTER EXTENSION pgtap ADD FUNCTION has_index ( NAME, NAME, text );

Explanation: SQL assertion from pgTAP test suite for Pgtap--Unpackaged--0.91.0.


Question: Write the DDL statement from PostgreSQL regression test 'sqljson_queryfuncs' (example 240).

CREATE INDEX ON test_jsonb_mutability (JSON_QUERY(js, '$.datetime("YY-MM-DD") ? (@ == $x)' PASSING '2020-07-14'::date AS x));

Explanation: DDL from PostgreSQL core regression test for Sqljson Queryfuncs.


Question: Write the PL/pgSQL object from PostgreSQL regression test 'plpgsql' (example 498).

$$ language plpgsql;

select raise_test();

create or replace function raise_test() returns void as $$
begin
  raise division_by_zero;

Explanation: PL/pgSQL object from PostgreSQL core test for Plpgsql.


Question: Show a SQL definition from the pg_partman project (pg_partman--2.3.1--2.3.2, item 14).

/*
 * Check if parent table is a subpartition of an already existing partition set managed by pg_partman
 *  If so, return the limits of what child tables can be created under the given parent table based on its own suffix
 */
CREATE OR REPLACE FUNCTION check_subpartition_limits(p_parent_table text, p_type text, OUT sub_min text, OUT sub_max text) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE

v_datetime_string       text;
v_id_position           int;
v_parent_schema         text;
v_parent_tablename      text;
v_partition_interval    interval;
v_quarter               text;
v_sub_id_max            bigint;
v_sub_id_min            bigint;
v_sub_timestamp_max     timestamp;
v_sub_timestamp_min     timestamp;
v_time_position         int;
v_top_datetime_string   text;
v_top_interval          text;
v_top_parent            text;
v_top_type              text;
v_year                  text;

BEGIN

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_tables
WHERE schemaname = split_part(p_parent_table, '.', 1)
AND tablename = split_part(p_parent_table, '.', 2);

-- CTE query is done individually for each type (time, id) because it should return NULL if the top parent is not the same type in a subpartition set (id->time or time->id)

IF p_type = 'id' THEN

    WITH top_oid AS (
        SELECT i.inhparent AS top_parent_oid
        FROM pg_catalog.pg_class c
        JOIN pg_catalog.pg_inherits i ON c.oid = i.inhrelid
        JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE n.nspname = v_parent_schema
        AND c.relname = v_parent_tablename
    ) SELECT n.nspname||'.'||c.relname, p.datetime_string, p.partition_interval, p.partition_type
      INTO v_top_parent, v_top_datetime_string, v_top_interval, v_top_type
      FROM pg_catalog.pg_class c
      JOIN top_oid t ON c.oid = t.top_parent_oid
      JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
      JOIN @extschema@.part_config p ON p.parent_table = n.nspname||'.'||c.relname
      WHERE c.oid = t.top_parent_oid
      AND p.partition_type = 'id';

    IF v_top_parent IS NOT NULL THEN
        SELECT child_start_id::text, child_end_id::text
        INTO sub_min, sub_max
        FROM @extschema@.show_partition_info(p_parent_table, v_top_interval, v_top_parent);
    END IF;

ELSIF p_type = 'time' THEN

    WITH top_oid AS (
        SELECT i.inhparent AS top_parent_oid
        FROM pg_catalog.pg_class c
        JOIN pg_catalog.pg_inherits i ON c.oid = i.inhrelid
        JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
        WHERE n.nspname = v_parent_schema
        AND c.relname = v_parent_tablename
    ) SELECT n.nspname||'.'||c.relname, p.datetime_string, p.partition_interval, p.partition_type
      INTO v_top_parent, v_top_datetime_string, v_top_interval, v_top_type
      FROM pg_catalog.pg_class c
      JOIN top_oid t ON c.oid = t.top_parent_oid
      JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
      JOIN @extschema@.part_config p ON p.parent_table = n.nspname||'.'||c.relname
      WHERE c.oid = t.top_parent_oid
      AND p.partition_type = 'time' OR p.partition_type = 'time-custom';

    IF v_top_parent IS NOT NULL THEN
        SELECT child_start_time::text, child_end_time::text
        INTO sub_min, sub_max
        FROM @extschema@.show_partition_info(p_parent_table, v_top_interval, v_top_parent);
    END IF;

ELSE
    RAISE EXCEPTION 'Invalid type given as parameter to check_subpartition_limits()';
END IF;

RETURN;

END
$$;

Explanation: SQL definition from the open-source pg_partman PostgreSQL project.


Question: pgTAP test for Hastap (assertion 121).

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: Write the SQL definition from PostgreSQL contrib extension 'contrib' (item 28).

CREATE FUNCTION gin_extract_query_oid(oid, internal, int2, internal, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;

Explanation: SQL definition from the 'contrib' PostgreSQL contrib extension.