Question: pgTAP test for Ruletap (assertion 19).

SELECT * FROM check_test(
    hasnt_rule( 'public', 'sometab', 'ins_me', 'whatever' ),
    false,
    'hasnt_rule(schema, table, rule, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Ruletap.


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

CREATE TABLE ATACC1 (TEST INT, TEST2 INT
	CHECK (TEST > 0), CHECK (TEST2 > 10) NO INHERIT);

Explanation: DDL from PostgreSQL core regression test for Constraints.


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

-- implicit cast during assignment is a separate code path, test that too

create or replace function dom_check(int) returns di as $$
declare d di;
begin
  d := $1;
  return d;
end
$$ language plpgsql immutable;

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


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

SELECT sum(unique1) over (order by four groups between 2 preceding and 1 preceding),
	unique1, four
FROM tenk1 WHERE unique1 < 10;

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

SELECT count(*) FROM (SELECT sum(unique1) over (order by four groups between 2 preceding and 1 preceding),
	unique1, four
FROM tenk1 WHERE unique1 < 10) AS _sub;


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

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL regression test 'rules': Write the SELECT query (example 152).

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

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


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

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


Question: pgTAP test for Hastap (assertion 160).

SELECT * FROM check_test(
    hasnt_cast( 'INT4', 'INT8', 'foo', 'desc' ),
    true,
    'hasnt_cast( src, targ, func, desc ) fail',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

Explanation: DDL from PostgreSQL core regression test for Portals.


Question: PostgreSQL regression test 'int2': Write the SELECT query (example 65).

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

SELECT count(*) FROM (SELECT int2 '-0o100000') AS _sub;


Question: pgTAP test for Inheritance (assertion 46).

SELECT * FROM check_test(
    is_ancestor_of( 'hide', 'h_parent', 'hide', 'h_child1'::name ),
    true,
    'is_ancestor_of(psch, ptab, csch, ctab)',
    'Table hide.h_parent should be an ancestor of hide.h_child1',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

/*
 * 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_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_new_search_path               text := '@extschema@,pg_temp';
v_next_partition_id             bigint;
v_next_partition_timestamp      timestamp;
v_old_search_path               text;
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_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_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;

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;

SELECT current_setting('search_path') INTO v_old_search_path;
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'::name AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        v_new_search_path := '@extschema@,'||v_jobmon_schema||',pg_temp';
    END IF;
END IF;
EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job('PARTMAN RUN MAINTENANCE');
    v_step_id := add_step(v_job_id, 'Running maintenance loop');
END IF;

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
                , infinite_time_partitions
            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

    -- 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().
    SELECT sub_parent INTO v_sub_parent FROM @extschema@.part_config_sub WHERE sub_parent = v_row.parent_table;
    IF v_sub_parent IS NOT NULL THEN
        SELECT count(*) INTO v_check_subpart FROM @extschema@.check_subpart_sameconfig(v_row.parent_table);
        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 IF;

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

    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

        SELECT child_start_time INTO v_last_partition_timestamp
            FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_row.partition_interval, v_row.parent_table);

        -- 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
            IF v_row.infinite_time_partitions IS TRUE THEN
                -- Set it to now so new partitions continue to be created
                v_current_partition_timestamp = CURRENT_TIMESTAMP;
            ELSE
                -- Nothing to do
                CONTINUE;
            END IF;
        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
                    v_step_overflow_id := add_step(v_job_id, 'Attempted partition time interval is outside PostgreSQL''s supported time range.');
                    PERFORM update_step(v_step_overflow_id, 'CRITICAL', format('Child partition creation skipped for parent table: %s', 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;

        SELECT child_start_id INTO v_last_partition_id
            FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_row.partition_interval, v_row.parent_table);
        -- 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

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
    PERFORM update_step(v_step_id, 'OK', format('Partition maintenance finished. %s partitions made. %s partitions dropped.', v_create_count, v_drop_count));
    IF v_step_overflow_id IS NOT NULL THEN
        PERFORM fail_job(v_job_id);
    ELSE
        PERFORM close_job(v_job_id);
    END IF;
END IF;

EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');

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 'partition_prune': Write the SELECT query (example 138).

select * from boolpart where a is not true and a is not false;

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

SELECT count(*) FROM (select * from boolpart where a is not true and a is not false) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'guc' (example 148).

Explanation: DDL from PostgreSQL core regression test for Guc.


Question: Show a SQL definition from the timescaledb project (drop_hypertable, item 30).

CREATE TABLE t2 (time timestamptz) WITH (tsdb.hypertable);

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


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

create trigger parted_trigger after update of b on parted_trigger
  for each row execute procedure trigger_notice_ab();

Explanation: DDL from PostgreSQL core regression test for Triggers.


Question: Write the DDL statement from PostgreSQL regression test 'truncate' (example 161).

CREATE TABLE trunc_a2 PARTITION OF trunc_a FOR VALUES FROM (10) TO (20)
  PARTITION BY RANGE (a);

Explanation: DDL from PostgreSQL core regression test for Truncate.


Question: Write the DML statement from PostgreSQL regression test 'without_overlaps' (example 600).

DELETE FROM temporal_partitioned_rng WHERE id = '[5,6)' AND valid_at = daterange('2018-02-01', '2018-03-01');

Explanation: DML from PostgreSQL core regression test for Without Overlaps.


Question: PostgreSQL Query: show example 28.

SELECT city, count(*) FILTER (WHERE temp_lo < 45), max(temp_lo) FROM weather GROUP BY city;

Explanation: Example from PostgreSQL documentation on Query.


Question: Write the DDL statement from PostgreSQL regression test 'update' (example 60).

CREATE TABLE part_a_10_a_20 PARTITION OF range_parted FOR VALUES FROM ('a', 10) TO ('a', 20);

Explanation: DDL from PostgreSQL core regression test for Update.


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

SELECT to_timestamp('2024 613566758 1', 'YYYY WW D');

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

SELECT count(*) FROM (SELECT to_timestamp('2024 613566758 1', 'YYYY WW D')) AS _sub;


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

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

SELECT count(*) FROM (SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33, '-2')) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pg_stat_statements' (example 141).

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


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

CREATE UNLOGGED TABLE public.unlogged2 (a int primary key);		-- also OK
CREATE UNLOGGED TABLE pg_temp.unlogged3 (a int primary key);	-- not OK
CREATE TABLE pg_temp.implicitly_temp (a int primary key);		-- OK
CREATE TEMP TABLE explicitly_temp (a int primary key);			-- also OK
CREATE TEMP TABLE pg_temp.doubly_temp (a int primary key);		-- also OK
CREATE TEMP TABLE public.temp_to_perm (a int primary key);		-- not OK
DROP TABLE unlogged1, public.unlogged2;

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


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

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


Question: Show a SQL definition from the timescaledb project (create_table_with, item 49).

CREATE TABLE IF NOT EXISTS t9(time date NOT NULL, device text, value float) WITH (tsdb.columnstore=false,tsdb.hypertable,tsdb.partition_column='time',tsdb.chunk_interval='3 months');


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

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


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

CREATE FUNCTION alt_func1(int) RETURNS int LANGUAGE sql
  AS 'SELECT $1 + 1';

Explanation: DDL from PostgreSQL core regression test for Alter Generic.


Question: pgTAP test for Proctap (assertion 11).

-- is_procedure ( NAME, NAME, NAME[], TEXT )
-- isnt_procedure ( NAME, NAME, NAME[], TEXT )
SELECT * FROM check_test(
    is_procedure( 'procschema', 'aproc', '{}'::name[], 'whatever' ),
    true,
    'is_procedure(schema, proc, noargs, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Proctap.


Question: PostgreSQL regression test 'text': Write the SELECT query (example 6).

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

SELECT count(*) FROM (select 'four: ' || 2+2) AS _sub;


Question: PostgreSQL regression test 'rangefuncs': Write the SELECT query (example 238).

SELECT * FROM rngfuncb(42, 99) AS p(a,b);

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

SELECT count(*) FROM (SELECT * FROM rngfuncb(42, 99) AS p(a,b)) AS _sub;


Question: pgTAP test for Pgtap--0.92.0--0.93.0 (assertion 50).

-- type_owner_is ( schema, type, user, description )
CREATE OR REPLACE FUNCTION type_owner_is ( NAME, NAME, NAME, TEXT )
RETURNS TEXT AS $$
DECLARE
    owner NAME := _get_type_owner($1, $2);
BEGIN
    -- Make sure the type exists.
    IF owner IS NULL THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            E'    Type ' || quote_ident($1) || '.' || quote_ident($2) || ' not found'
        );
    END IF;

    RETURN is(owner, $3, $4);
END;
$$ LANGUAGE plpgsql;

Explanation: SQL assertion from pgTAP test suite for Pgtap--0.92.0--0.93.0.


Question: Show a SQL definition from the pg_partman project (pg_partman--2.0.0--2.1.0, item 35).

/*
 * Given a parent table and partition value, return the name of the child partition it would go in.
 * Also returns just the suffix value and true if the child table exists or false if it does not
 */
CREATE FUNCTION show_partition_name(p_parent_table text, p_value text, OUT partition_table text, OUT suffix_timestamp timestamp, OUT suffix_id bigint, OUT table_exists boolean) RETURNS record
    LANGUAGE plpgsql STABLE
    AS $$
DECLARE

v_child_exists          text;
v_datetime_string       text;
v_max_range             timestamptz;
v_min_range             timestamptz;
v_parent_schema         text;
v_parent_tablename      text;
v_partition_interval    text;
v_time_position         int;
v_type                  text;

BEGIN

SELECT partition_type
    , partition_interval
    , datetime_string
INTO v_type
    , v_partition_interval
    , v_datetime_string
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

IF v_type IS NULL THEN
    RAISE EXCEPTION 'Parent table given is not managed by pg_partman (%)', p_parent_table;
END IF;

SELECT schemaname, tablename INTO v_parent_schema, v_parent_tablename FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = p_parent_table;
IF v_parent_tablename IS NULL THEN
    RAISE EXCEPTION 'Parent table given does not exist (%)', p_parent_table;
END IF;

IF v_type = 'time' THEN
    CASE
        WHEN v_partition_interval::interval = '15 mins' THEN
            suffix_timestamp := date_trunc('hour', p_value::timestamp) +
                '15min'::interval * floor(date_part('minute', p_value::timestamp) / 15.0);
        WHEN v_partition_interval::interval = '30 mins' THEN
            suffix_timestamp := date_trunc('hour', p_value::timestamp) +
                '30min'::interval * floor(date_part('minute', p_value::timestamp) / 30.0);
        WHEN v_partition_interval::interval = '1 hour' THEN
            suffix_timestamp := date_trunc('hour', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 day' THEN
            suffix_timestamp := date_trunc('day', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 week' THEN
            suffix_timestamp := date_trunc('week', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 month' THEN
            suffix_timestamp := date_trunc('month', p_value::timestamp);
        WHEN v_partition_interval::interval = '3 months' THEN
            suffix_timestamp := date_trunc('quarter', p_value::timestamp);
        WHEN v_partition_interval::interval = '1 year' THEN
            suffix_timestamp := date_trunc('year', p_value::timestamp);
    END CASE;
    partition_table := v_parent_schema||'.'||@extschema@.check_name_length(v_parent_tablename, to_char(suffix_timestamp, v_datetime_string), TRUE);
ELSIF v_type = 'id' THEN
    suffix_id := (p_value::bigint - (p_value::bigint % v_partition_interval::bigint));
    partition_table := v_parent_schema||'.'||@extschema@.check_name_length(v_parent_tablename, suffix_id::text, TRUE);
ELSIF v_type = 'time-custom' THEN

    SELECT child_table, lower(partition_range) INTO partition_table, suffix_timestamp FROM @extschema@.custom_time_partitions
        WHERE parent_table = p_parent_table AND partition_range @> p_value::timestamptz;

    IF partition_table IS NULL THEN
        SELECT max(upper(partition_range)) INTO v_max_range FROM @extschema@.custom_time_partitions WHERE parent_table = p_parent_table;
        SELECT min(lower(partition_range)) INTO v_min_range FROM @extschema@.custom_time_partitions WHERE parent_table = p_parent_table;
        IF p_value::timestamp >= v_max_range THEN
            suffix_timestamp := v_max_range;
            LOOP
                -- Keep incrementing higher until given value is below the upper range
                suffix_timestamp := suffix_timestamp + v_partition_interval::interval;
                IF p_value::timestamp < suffix_timestamp THEN
                    -- Have to subtract one interval because the value would actually be in the partition previous
                    --      to this partition timestamp since the partition names contain the lower boundary
                    suffix_timestamp := suffix_timestamp - v_partition_interval::interval;
                    EXIT;
                END IF;
            END LOOP;
        ELSIF p_value::timestamp < v_min_range THEN
            suffix_timestamp := v_min_range;
            LOOP
                -- Keep decrementing lower until given value is below or equal to the lower range
                suffix_timestamp := suffix_timestamp - v_partition_interval::interval;
                IF p_value::timestamp >= suffix_timestamp THEN
                    EXIT;
                END IF;
            END LOOP;
        ELSE
            RAISE EXCEPTION 'Unable to determine a valid child table for the given parent table and value';
        END IF;

        partition_table := v_parent_schema||'.'||@extschema@.check_name_length(v_parent_tablename, to_char(suffix_timestamp, v_datetime_string), TRUE);
    END IF;
END IF;

SELECT schemaname, tablename INTO v_child_exists FROM pg_catalog.pg_tables WHERE schemaname ||'.'|| tablename = partition_table;

IF v_child_exists IS NOT NULL THEN
    table_exists := true;
ELSE
    table_exists := false;
END IF;

RETURN;

END
$$;

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


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

INSERT INTO users (fname, lname, username) VALUES ('charles', 'darwin', 'beagle');

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


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

SELECT cube_ll_coord(ll_to_earth(0,180),1)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,180),2)::numeric(20,5),
 cube_ll_coord(ll_to_earth(0,180),3)::numeric(20,5);

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


Question: pgTAP test for Hastap (assertion 4).

-- Create a partition.
CREATE FUNCTION mkpart() RETURNS SETOF TEXT AS $$
BEGIN
    IF pg_version_num() >= 100000 THEN
        EXECUTE $E$
            CREATE TABLE public.apart (dt DATE NOT NULL) PARTITION BY RANGE (dt);
        $E$;
    ELSE
    EXECUTE $E$
        CREATE TABLE public.apart (dt DATE NOT NULL);
    $E$;
    END IF;
    RETURN;
END;
$$ LANGUAGE plpgsql;

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: PostgreSQL regression test 'create_aggregate': Write the SELECT query (example 44).

SELECT aggfnoid, aggtransfn, aggcombinefn, aggtranstype::regtype,
       aggserialfn, aggdeserialfn, aggfinalmodify
FROM pg_aggregate
WHERE aggfnoid = 'myavg'::REGPROC;

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

SELECT count(*) FROM (SELECT aggfnoid, aggtransfn, aggcombinefn, aggtranstype::regtype,
       aggserialfn, aggdeserialfn, aggfinalmodify
FROM pg_aggregate
WHERE aggfnoid = 'myavg'::REGPROC) AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION has_opclass( NAME, NAME );

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


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

CREATE ACCESS METHOD bogus TYPE INDEX HANDLER heap_tableam_handler;

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


Question: Write the DDL statement from PostgreSQL regression test 'partition_info' (example 13).

CREATE TABLE ptif_test3 PARTITION OF ptif_test
  FOR VALUES FROM (200) TO (maxvalue) PARTITION BY list (b);

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


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

end$$ language plpgsql;

select stricttest();

-- test warnings and errors
set plpgsql.extra_warnings to 'all';
set plpgsql.extra_warnings to 'none';
set plpgsql.extra_errors to 'all';
set plpgsql.extra_errors to 'none';

-- test warnings when shadowing a variable

set plpgsql.extra_warnings to 'shadowed_variables';

-- simple shadowing of input and output parameters
create or replace function shadowtest(in1 int)
	returns table (out1 int) as $$
declare
in1 int;

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


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

select (select max(unique1) filter (where bool_or(ten > 0)) from int8_tbl) from tenk1;

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

SELECT count(*) FROM (select (select max(unique1) filter (where bool_or(ten > 0)) from int8_tbl) from tenk1) AS _sub;


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

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


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

-- alter view rename column works fine
CREATE VIEW v AS SELECT * FROM dist_table;

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


Question: PostgreSQL regression test 'rules': Write the SELECT query (example 337).

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

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


Question: Write the DDL statement from PostgreSQL regression test 'create_index' (example 196).

CREATE UNIQUE INDEX unique_idx4 ON unique_tbl (i) NULLS NOT DISTINCT;  -- ok now

\d unique_tbl
\d unique_idx3
\d unique_idx4
SELECT pg_get_indexdef('unique_idx3'::regclass);

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


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

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


Question: Write the DML statement from PostgreSQL regression test 'domain' (example 138).

insert into vc4table values(array['too long']);  -- fail
insert into vc4table values(array['too long']::vc4[]);  -- cast truncates
select * from vc4table;

Explanation: DML from PostgreSQL core regression test for Domain.


Question: PostgreSQL regression test 'subselect': Write the SELECT query (example 221).

select sum(ss.tst::int) from
  onek o cross join lateral (
  select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst,
         random() as r
  from onek i where i.unique1 = o.unique1 ) ss
where o.ten = 0;

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

SELECT count(*) FROM (select sum(ss.tst::int) from
  onek o cross join lateral (
  select i.ten in (select f1 from int4_tbl where f1 <= o.hundred) as tst,
         random() as r
  from onek i where i.unique1 = o.unique1 ) ss
where o.ten = 0) AS _sub;


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

CREATE OR REPLACE RULE y_rule AS ON INSERT TO y DO INSTEAD NOTIFY foo;

Explanation: DDL from PostgreSQL core regression test for With.


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

CREATE OPERATOR = (
	PROCEDURE = isneq,
	LEFTARG = isbn13,
	RIGHTARG = isbn,
	COMMUTATOR = =,
	NEGATOR = <>,
	RESTRICT = eqsel,
	JOIN = eqjoinsel,
	MERGES,
	HASHES);

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


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

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

SELECT count(*) FROM (select '(a,a)'::textrange) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pageinspect' (example 7).

SELECT octet_length(get_raw_page('test1', 'main', 0)) AS main_0;

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


Question: pgTAP test for Resultset (assertion 257).

-- Handle failure due to missing dupe.
SELECT * FROM check_test(
    bag_eq(
        'SELECT 1 AS a, ''Anna''::text AS b UNION ALL SELECT 86, ''Angelina'' UNION ALL SELECT 1, ''Anna''',
        'SELECT 1 AS a, ''Anna''::TEXT AS b UNION ALL SELECT 86, ''Angelina'''
    ),
    false,
    'bag_eq(values, values) fail missing dupe',
    '',
    '    Extra records:
        (1,Anna)'
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: Write the DML statement from PostgreSQL regression test 'update' (example 81).

UPDATE part_b_10_b_20 set c = c + 20 returning c, b, a;

Explanation: DML from PostgreSQL core regression test for Update.


Question: PostgreSQL regression test 'create_table_like': Write the SELECT query (example 27).

Explanation: Regression test for Create Table Like in PostgreSQL core test suite.

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


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

SELECT rpad('hi'::text,   5, 'xy'::citext) = 'hixyx' AS t;

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


Question: Show a query using PostgreSQL contrib extension 'pg_stat_statements' (example 42).

SELECT * FROM test_squash WHERE id = ANY (ARRAY[1, 2, 3, 4, 5, 6, 7, 8, 9])
    AND data = ANY (ARRAY[1, 2, 3, 4, 5, 6, 7, 8, 9]);

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


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

SELECT * FROM JSON_TABLE(jsonb '{"rec": "(1,2)"}', '$' COLUMNS (id FOR ORDINALITY, comp comp path '$.rec' omit quotes)) jt;

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '{"rec": "(1,2)"}', '$' COLUMNS (id FOR ORDINALITY, comp comp path '$.rec' omit quotes)) jt) AS _sub;


Question: pgTAP test for Valueset (assertion 333).

-- Compare with missing dupe.
SELECT * FROM check_test(
    results_ne(
        'VALUES (1, ''Anna''), (86, ''Angelina''), (1, ''Anna'')',
        'VALUES (1, ''Anna''), (86, ''Angelina'')'
    ),
    true,
    'results_ne(values dupe, values)',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Valueset.


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

ALTER EXTENSION pgtap ADD FUNCTION _definer ( NAME, NAME, NAME[] );

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


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

$$;

SELECT create_and_insert();

TABLE ddl_test;

CREATE FUNCTION alter_and_insert() RETURNS VOID LANGUAGE sql AS $$
  alter table ddl_test alter column f1 type numeric;

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


Question: PL/pgSQL test: Plpython Transaction (example 29).

DO LANGUAGE plpython3u $$
for row in plpy.cursor("SELECT * FROM test2 ORDER BY x"):
    plpy.execute("INSERT INTO test1 (a) VALUES (%s)" % row['x'])
    plpy.rollback()
$$;

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


Question: Show a query using PostgreSQL contrib extension 'bloom' (example 48).

SELECT count(*) FROM tstu WHERE i = 7 AND t = '5';

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


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

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

SELECT count(*) FROM (select '1'::xid != '1'::xid8::xid) AS _sub;


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

select interval '2147483647 months 0.1 yrs';

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

SELECT count(*) FROM (select interval '2147483647 months 0.1 yrs') AS _sub;


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

INSERT INTO num_typemod_test (thousands) VALUES (999500);

Explanation: DML from PostgreSQL core regression test for Numeric.


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

insert into rtest_view3 select * from rtest_vview3;

Explanation: DML from PostgreSQL core regression test for Rules.


Question: pgTAP test for Unique (assertion 12).

SELECT * FROM check_test(
    col_is_unique( 'public', 'sometab', ARRAY['numb', 'myint'], 'public.sometab.numb+myint should be unique' ),
    true,
    'col_is_unique( schema, table, columns, description )',
    'public.sometab.numb+myint should be unique',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Unique.


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

CREATE TABLE salespeople2_5(salesperson_id INT NOT NULL, salesperson_name VARCHAR(30));

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


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

CREATE POLICY p1 ON b1 USING (a % 2 = 0);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

SELECT count(*) FROM int2tmp WHERE a >  237::int2;

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


Question: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 548).

select multirange_of_text(textrange2('a','Z'));  -- should fail
select multirange_of_text(textrange1('a','Z')) @> 'b'::text;

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

SELECT count(*) FROM (select multirange_of_text(textrange2('a','Z'));  -- should fail
select multirange_of_text(textrange1('a','Z')) @> 'b'::text) AS _sub;


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

--
--
--
-- int4 ops
--
--
--
-- define the GiST support methods
CREATE FUNCTION gbt_int4_consistent(internal,int4,int2,oid,internal)
RETURNS bool
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


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

select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")');

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

SELECT count(*) FROM (select jsonb_path_query('[[null, 1, "abc", "abcabc"]]', 'lax $ ? (@[*] starts with "abc")')) AS _sub;


Question: PostgreSQL regression test 'create_view': Write the SELECT query (example 242).

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

SELECT count(*) FROM (select f1, f3 from tt14v) AS _sub;


Question: PostgreSQL regression test 'box': Write the SELECT query (example 81).

SELECT count(*) FROM quad_box_tbl WHERE b &<| box '((100,200),(300,500))';

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

SELECT count(*) FROM (SELECT count(*) FROM quad_box_tbl WHERE b &<| box '((100,200),(300,500))') AS _sub;


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

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

SELECT count(*) FROM (SELECT timestamptz(date '1994-01-01', time '11:00') AS "Jan_01_1994_10am") AS _sub;


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

select ts_headline('[]'::jsonb, tsquery('aaa & bbb'));

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

SELECT count(*) FROM (select ts_headline('[]'::jsonb, tsquery('aaa & bbb'))) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pageinspect' (example 10).

SELECT * FROM brin_revmap_data(get_raw_page('test1_a_idx', 1)) LIMIT 5;

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


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

CREATE FUNCTION _int_inter(_int4, _int4)
RETURNS _int4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;


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

CREATE INDEX ON test_jsonb_mutability (JSON_QUERY(js, '$.time_tz()'));

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


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

SELECT * FROM f_star* x WHERE x.c ISNULL;

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

SELECT count(*) FROM (SELECT * FROM f_star* x WHERE x.c ISNULL) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'inherit' (example 13).

Explanation: DML from PostgreSQL core regression test for Inherit.


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

CREATE FUNCTION distance_taxicab(cube, cube)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;


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

CREATE FUNCTION isnlt(issn, ean13)
	RETURNS boolean
	AS 'int8lt'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


Question: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 335).

SELECT nummultirange(numrange(1,2), numrange(3,4)) - nummultirange();

SELECT count(*) FROM (SELECT nummultirange(numrange(1,2), numrange(3,4)) - nummultirange()) AS _sub;


Question: pgTAP test for Cmpok (assertion 3).

SELECT * FROM check_test(
    cmp_ok( 1, '<>', 2, '1 should <> 2' ),
    true,
    'cmp_ok( int, <>, int )',
    '1 should <> 2',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Cmpok.


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

-- Can reference function with or without OUT params for DROP, etc
DROP FUNCTION rngfunc(int);

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


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

SELECT count(*) FROM (select jsonb_pretty('[{"f1":1,"f2":null},2,null,[[{"x":true},6,7],8],3]')) AS _sub;


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

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

SELECT count(*) FROM (SELECT CAST('922337203685477580700.0'::float8 AS int8)) AS _sub;


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


Question: PostgreSQL regression test 'cluster': Write the SELECT query (example 50).

SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY c;

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

SELECT count(*) FROM (SELECT a,b,c,substring(d for 30), length(d) from clstr_tst ORDER BY c) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'foreign_data' (example 66).

CREATE SERVER s8 FOREIGN DATA WRAPPER postgresql OPTIONS (foo '1'); -- ERROR
CREATE SERVER s8 FOREIGN DATA WRAPPER postgresql OPTIONS (host 'localhost', dbname 's8db');

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


Question: Show a query using PostgreSQL contrib extension 'dblink' (example 15).

INSERT INTO foo VALUES (9,'j','{"a9","b9","c9"}');

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


Question: PostgreSQL regression test 'int8': Write the SELECT query (example 137).


Question: PL/pgSQL test: Pltcl Queries (example 45).

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


Question: Write the DML statement from PostgreSQL regression test 'window' (example 2).

Explanation: DML from PostgreSQL core regression test for Window.


Question: PostgreSQL regression test 'date': Write the SELECT query (example 212).

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

SELECT count(*) FROM (SELECT make_date(-2147483648, 1, 1)) AS _sub;


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

SELECT * FROM gin_metapage_info(get_raw_page('test1', 0));


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

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

SELECT count(*) FROM (SELECT 'N A N'::float8) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'create_operator' (example 71).

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


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

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


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

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

SELECT count(*) FROM (SELECT to_regoper('||/')) AS _sub;


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

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


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

SELECT * FROM test_oid WHERE i>3::oid ORDER BY i;

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


Question: Write the DML statement from PostgreSQL regression test 'cluster' (example 26).

INSERT INTO clstr_tst (b, c) VALUES (27, 'veintisiete');

Explanation: DML from PostgreSQL core regression test for Cluster.


Question: PL/pgSQL test: Plpython Types (example 37).

CREATE FUNCTION test_type_conversion_float4(x float4) RETURNS float4 AS $$
plpy.info(x, type(x))
return x
$$ LANGUAGE plpython3u;

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


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 746).

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

SELECT count(*) FROM (SELECT to_number('viv', 'RN')) AS _sub;


Question: PostgreSQL Textsearch: show example 20.

ALTER TEXT SEARCH CONFIGURATION astro_en ADD MAPPING FOR asciiword WITH astrosyn, english_ispell, english_stem;

Explanation: Example from PostgreSQL documentation on Textsearch.


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

update rtest_v1 set b = 88 where b < 50;

Explanation: DML from PostgreSQL core regression test for Rules.


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

CREATE INDEX tbl_gist_idx ON tbl_gist using gist (c4) INCLUDE (c1,c2,c3);

Explanation: DDL from PostgreSQL core regression test for Index Including Gist.


Question: pgTAP test for Resultset (assertion 308).

DECLARE chave CURSOR FOR SELECT id, name from annames ORDER BY id;

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT id FROM test_tablesample_v1 TABLESAMPLE BERNOULLI (1);

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

SELECT count(*) FROM (SELECT id FROM test_tablesample_v1 TABLESAMPLE BERNOULLI (1)) AS _sub;


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

SELECT jsonb_path_match('{}', 'strict $.a', silent => false);

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

SELECT count(*) FROM (SELECT jsonb_path_match('{}', 'strict $.a', silent => false)) AS _sub;


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

CREATE TABLE default_expr_non_column (a int DEFAULT (avg(non_existent)));

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


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

SELECT * FROM test_money WHERE i='1'::money ORDER BY i;


Question: PostgreSQL regression test 'tsdicts': Write the SELECT query (example 13).

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

SELECT count(*) FROM (SELECT ts_lexize('ispell', 'footklubber')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'matview' (example 16).

CREATE MATERIALIZED VIEW mvtest_tmm AS SELECT sum(totamt) AS grandtot FROM mvtest_tm;

Explanation: DDL from PostgreSQL core regression test for Matview.


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

SELECT regexp_match('foobarbequebazmorebarbequetoo'::citext, '(BAR)(BEQUE)'::citext, 'g') AS "error";

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


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

create view id_ordered as select * from id order by id;

Explanation: DDL from PostgreSQL core regression test for Rules.


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

SELECT '1,1'::cube < '1,2'::cube AS bool;

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


Question: Show a SQL definition from the pglogical project (conflict_secondary_unique, item 1).

SELECT * FROM pglogical_regress_variables()
\gset

\c :provider_dsn

-- Test conflicts where a secondary unique constraint with a predicate exits,
-- ensuring we don't generate false conflicts.
SELECT pglogical.replicate_ddl_command($$
CREATE TABLE public.secondary_unique_pred (
    a integer PRIMARY KEY,
    b integer NOT NULL,
    check_unique boolean NOT NULL
);

CREATE UNIQUE INDEX ON public.secondary_unique_pred (b) WHERE (check_unique);
$$);

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


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

Explanation: DDL from PostgreSQL core regression test for Maintain Every.


Question: Show a query using PostgreSQL contrib extension 'dblink' (example 8).

INSERT INTO foo VALUES (2,'c','{"a2","b2","c2"}');

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


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

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

SELECT count(*) FROM (SELECT to_regtype('ng_catalog.int4')) AS _sub;


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

CREATE FUNCTION isnge(isbn13, isbn)
	RETURNS boolean
	AS 'int8ge'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;

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


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

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


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

SELECT * FROM test_ne WHERE a <> '2009-01-01' AND b <> 10.7;

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


Question: Write the DDL statement from PostgreSQL regression test 'create_table_like' (example 91).

Explanation: DDL from PostgreSQL core regression test for Create Table Like.


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

select ten, grouping(ten) from onek
group by cube(ten) having grouping(ten) > 0
order by 2,1;

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

SELECT count(*) FROM (select ten, grouping(ten) from onek
group by cube(ten) having grouping(ten) > 0
order by 2,1) AS _sub;


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

insert into dropcol(key, keep1, keep2) values(1, '4', 4) on conflict(key)
    do update set keep1 = excluded.keep1, keep2 = excluded.keep2
    where excluded.keep1 is not null and excluded.keep2 is not null
          and dropcol.keep1 is not null and dropcol.keep2 is not null
    returning *;

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


Question: Show a SQL definition from the pglogical project (pglogical--2.2.1, item 29).

CREATE FUNCTION pglogical.replication_set_remove_table(set_name name, relation regclass)
RETURNS boolean STRICT VOLATILE LANGUAGE c AS 'MODULE_PATHNAME', 'pglogical_replication_set_remove_table';


Question: Write the DDL statement from PostgreSQL regression test 'alter_table' (example 246).

create function non_strict(text) returns text as
    'select coalesce($1, ''got passed a null'');'
    language sql called on null input;

Explanation: DDL from PostgreSQL core regression test for Alter Table.


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

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

SELECT count(*) FROM (SELECT xpath('/nosuchtag', '<root/>')) AS _sub;


Question: PostgreSQL Perform: show example 3.

SELECT * FROM zipcodes WHERE city = 'San Francisco' AND zip = '94105';

Explanation: Example from PostgreSQL documentation on Perform.


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

INSERT INTO shoelace_data VALUES ('sl6', 0, 'brown', 0.9 , 'm');

Explanation: DML from PostgreSQL core regression test for Rules.


Question: PostgreSQL regression test 'rowsecurity': Write the SELECT query (example 634).

SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(abc);

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

SELECT count(*) FROM (SELECT * FROM y2 JOIN test_qual_pushdown ON (b = abc) WHERE f_leak(abc)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'misc' (example 8).

UPDATE tmp
   SET stringu1 = reverse_name(onek.stringu1)
   FROM onek
   WHERE onek.stringu1 = 'JBAAAA' and
	  onek.stringu1 = tmp.stringu1;

Explanation: DML from PostgreSQL core regression test for Misc.


Question: PostgreSQL regression test 'money': Write the SELECT query (example 36).

SELECT cashsmaller(m, '$124.00') FROM money_data;

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

SELECT count(*) FROM (SELECT cashsmaller(m, '$124.00') FROM money_data) AS _sub;


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

SELECT to_timestamp('  2000 +JUN', 'YYYY/MON');

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

SELECT count(*) FROM (SELECT to_timestamp('  2000 +JUN', 'YYYY/MON')) AS _sub;


Question: PostgreSQL regression test 'create_index': Write the SELECT query (example 127).

SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno;

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

SELECT count(*) FROM (SELECT * FROM array_index_op_test WHERE i @> '{32}' ORDER BY seqno) AS _sub;


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

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

SELECT count(*) FROM (SELECT to_number('.-01', 'S99.99')) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_path_query('{"a": {"b": 1}}', 'lax $.**{1 to last}.b ? (@ > 0)')) AS _sub;


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

CREATE INDEX iprt1_e_p2_ab2 on prt1_e_p2(((a+b)/2));

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


Question: Write the DDL statement from PostgreSQL regression test 'roleattributes' (example 43).

CREATE USER regress_test_user_canlogin WITH NOLOGIN;

Explanation: DDL from PostgreSQL core regression test for Roleattributes.


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

-- single argument jsonb functions as jsonb_function(jsonb) and jsonb.jsonb_function
select jsonb_typeof('{"a":1}'::jsonb);

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


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

SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": 123}') q;

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

SELECT count(*) FROM (SELECT reca FROM jsonb_populate_record(NULL::jsbrec, '{"reca": 123}') q) AS _sub;


Question: PostgreSQL regression test 'numerology': Write the SELECT query (example 84).

SELECT f1 AS two, (max(f3) + 1) AS max_plus_1, (min(f3) - 1) AS min_minus_1
  FROM TEMP_GROUP
  GROUP BY f1
  ORDER BY two, min_minus_1;

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

SELECT count(*) FROM (SELECT f1 AS two, (max(f3) + 1) AS max_plus_1, (min(f3) - 1) AS min_minus_1
  FROM TEMP_GROUP
  GROUP BY f1
  ORDER BY two, min_minus_1) AS _sub;


Question: PostgreSQL regression test 'brin_multi': Write the SELECT query (example 100).

SELECT COUNT(*) FROM brin_test_multi_1 WHERE a >= 63;

Explanation: Regression test for Brin Multi in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT COUNT(*) FROM brin_test_multi_1 WHERE a >= 63) AS _sub;


Question: Show a SQL definition from the pg_partman project (pg_partman--4.5.1--4.6.0, item 24).

CREATE OR REPLACE FUNCTION @extschema@.create_partition_id(p_parent_table text, p_partition_ids bigint[], p_analyze boolean DEFAULT true, p_start_partition text DEFAULT NULL) RETURNS boolean
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context              text;
ex_detail               text;
ex_hint                 text;
ex_message              text;
v_all                   text[] := ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE', 'REFERENCES', 'TRIGGER'];
v_analyze               boolean := FALSE;
v_control               text;
v_control_type          text;
v_exists                text;
v_grantees              text[];
v_hasoids               boolean;
v_id                    bigint;
v_inherit_fk            boolean;
v_inherit_privileges    boolean;
v_job_id                bigint;
v_jobmon                boolean;
v_jobmon_schema         text;
v_new_search_path       text := '@extschema@,pg_temp';
v_old_search_path       text;
v_parent_grant          record;
v_parent_schema         text;
v_parent_tablename      text;
v_parent_tablespace     text;
v_partition_interval    bigint;
v_partition_created     boolean := false;
v_partition_name        text;
v_partition_type        text;
v_publications          text[];
v_revoke                text;
v_row                   record;
v_sql                   text;
v_step_id               bigint;
v_sub_control           text;
v_sub_partition_type    text;
v_sub_id_max            bigint;
v_sub_id_min            bigint;
v_template_table        text;
v_unlogged              char;

BEGIN
/*
 * Function to create id partitions
 */

SELECT control
    , partition_type
    , partition_interval
    , inherit_fk
    , jobmon
    , template_table
    , publications
    , inherit_privileges
INTO v_control
    , v_partition_type
    , v_partition_interval
    , v_inherit_fk
    , v_jobmon
    , v_template_table
    , v_publications
    , v_inherit_privileges
FROM @extschema@.part_config
WHERE parent_table = p_parent_table;

IF NOT FOUND THEN
    RAISE EXCEPTION 'ERROR: no config found for %', p_parent_table;
END IF;

SELECT n.nspname, c.relname, t.spcname
INTO v_parent_schema, v_parent_tablename, v_parent_tablespace
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
LEFT OUTER JOIN pg_catalog.pg_tablespace t ON c.reltablespace = t.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name

AND c.relname = split_part(p_parent_table, '.', 2)::name;

SELECT general_type INTO v_control_type FROM @extschema@.check_control_type(v_parent_schema, v_parent_tablename, v_control);
IF v_control_type <> 'id' THEN
    RAISE EXCEPTION 'ERROR: Given parent table is not set up for id/serial partitioning';
END IF;

SELECT current_setting('search_path') INTO v_old_search_path;
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'::name AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        v_new_search_path := '@extschema@,'||v_jobmon_schema||',pg_temp';
    END IF;
END IF;
EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');

-- Determine if this table is a child of a subpartition parent. If so, get limits of what child tables can be created based on parent suffix
SELECT sub_min::bigint, sub_max::bigint INTO v_sub_id_min, v_sub_id_max FROM @extschema@.check_subpartition_limits(p_parent_table, 'id');

IF v_jobmon_schema IS NOT NULL THEN
    v_job_id := add_job(format('PARTMAN CREATE TABLE: %s', p_parent_table));
END IF;

FOREACH v_id IN ARRAY p_partition_ids LOOP
-- Do not create the child table if it's outside the bounds of the top parent.
    IF v_sub_id_min IS NOT NULL THEN
        IF v_id < v_sub_id_min OR v_id >= v_sub_id_max THEN
            CONTINUE;
        END IF;
    END IF;

    v_partition_name := @extschema@.check_name_length(v_parent_tablename, v_id::text, TRUE);
    -- If child table already exists, skip creation
    -- Have to check pg_class because if subpartitioned, table will not be in pg_tables
    SELECT c.relname INTO v_exists
    FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE n.nspname = v_parent_schema::name AND c.relname = v_partition_name::name;
    IF v_exists IS NOT NULL THEN
        CONTINUE;
    END IF;

    -- Ensure analyze is run if a new partition is created. Otherwise if one isn't, will be false and analyze will be skipped
    v_analyze := TRUE;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Creating new partition '||v_partition_name||' with interval from '||v_id||' to '||(v_id + v_partition_interval)-1);
    END IF;

    v_sql := 'CREATE';

    -- As of PG12, the unlogged/logged status of a native parent table cannot be changed via an ALTER TABLE in order to affect its children.
    -- As of v4.2x, the unlogged state will be managed via the template table
    SELECT relpersistence INTO v_unlogged
    FROM pg_catalog.pg_class c
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE c.relname = v_parent_tablename::name
    AND n.nspname = v_parent_schema::name;
    IF v_unlogged = 'u' and v_partition_type != 'native'  THEN
        v_sql := v_sql || ' UNLOGGED';
    END IF;

    -- Close parentheses on LIKE are below due to differing requirements of native subpartitioning
    -- Same INCLUDING list is used in create_parent()
    v_sql := v_sql || format(' TABLE %I.%I (LIKE %I.%I INCLUDING DEFAULTS INCLUDING CONSTRAINTS INCLUDING STORAGE INCLUDING COMMENTS '
            , v_parent_schema
            , v_partition_name
            , v_parent_schema
            , v_parent_tablename);

    IF current_setting('server_version_num')::int >= 120000 THEN
        v_sql := v_sql || ' INCLUDING GENERATED ';
    END IF;

    SELECT sub_partition_type, sub_control INTO v_sub_partition_type, v_sub_control
    FROM @extschema@.part_config_sub
    WHERE sub_parent = p_parent_table;
    IF v_sub_partition_type = 'native' THEN
        -- INCLUDING INDEXES isn't necessary for native partitioning. It isn't supported in v10 and
	    --   for v11+ index inheritance is automatically handled when the partition is attached
        v_sql := v_sql || format(') PARTITION BY RANGE (%I) ', v_sub_control);
    ELSE
        v_sql := v_sql || format(' INCLUDING INDEXES) ', v_sub_control);
    END IF;

    IF current_setting('server_version_num')::int < 120000 THEN
        -- column removed from pgclass in pg12
        SELECT relhasoids INTO v_hasoids
        FROM pg_catalog.pg_class c
        JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
        WHERE c.relname = v_parent_tablename::name
        AND n.nspname = v_parent_schema::name;
        IF v_hasoids IS TRUE THEN
            v_sql := v_sql || ' WITH (OIDS)';
        END IF;
    END IF;

    RAISE DEBUG 'create_partition_id v_sql: %', v_sql;
    EXECUTE v_sql;

    IF v_partition_type = 'native' THEN

        IF current_setting('server_version_num')::int >= 120000 THEN
            -- PG12 fixed tablespace marking on the parent of a native partition set
            -- Versions older than 12 handle tablespace setting via inherit_template_properties() call below
            IF v_parent_tablespace IS NOT NULL THEN
                EXECUTE format('ALTER TABLE %I.%I SET TABLESPACE %I', v_parent_schema, v_partition_name, v_parent_tablespace);
            END IF;
        END IF;

        IF v_template_table IS NOT NULL THEN
            PERFORM @extschema@.inherit_template_properties(p_parent_table, v_parent_schema, v_partition_name);
        END IF;

        EXECUTE format('ALTER TABLE %I.%I ATTACH PARTITION %I.%I FOR VALUES FROM (%L) TO (%L)'
            , v_parent_schema
            , v_parent_tablename
            , v_parent_schema
            , v_partition_name
            , v_id
            , v_id + v_partition_interval);

    ELSE -- non-native

        IF v_parent_tablespace IS NOT NULL THEN
            EXECUTE format('ALTER TABLE %I.%I SET TABLESPACE %I', v_parent_schema, v_partition_name, v_parent_tablespace);
        END IF;

        EXECUTE format('ALTER TABLE %I.%I ADD CONSTRAINT %I CHECK (%I >= %s AND %I < %s )'
            , v_parent_schema
            , v_partition_name
            , v_partition_name||'_partition_check'
            , v_control
            , v_id
            , v_control
            , v_id + v_partition_interval);

        EXECUTE format('ALTER TABLE %I.%I INHERIT %I.%I', v_parent_schema, v_partition_name, v_parent_schema, v_parent_tablename);

        -- Indexes cannot be created on the parent, so clustering cannot be used for native yet.
        PERFORM @extschema@.apply_cluster(v_parent_schema, v_parent_tablename, v_parent_schema, v_partition_name);

        -- Foreign keys to other tables not supported on native parent tables
        IF v_inherit_fk THEN
            PERFORM @extschema@.apply_foreign_keys(p_parent_table, v_parent_schema||'.'||v_partition_name, v_job_id);
        END IF;

    END IF;

    -- NOTE: Privileges not automatically inherited for native. Only do so if config flag is set
    IF v_partition_type != 'native' OR (v_partition_type = 'native' AND v_inherit_privileges = TRUE) THEN
        PERFORM @extschema@.apply_privileges(v_parent_schema, v_parent_tablename, v_parent_schema, v_partition_name, v_job_id);
    END IF;

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

    -- Will only loop once and only if sub_partitioning is actually configured
    -- This seemed easier than assigning a bunch of variables then doing an IF condition
    -- This column list must be kept consistent between:
    --   create_parent, check_subpart_sameconfig, create_partition_id, create_partition_time, dump_partitioned_table_definition, and table definition
    FOR v_row IN
        SELECT sub_parent
            , sub_partition_type
            , sub_control
            , sub_partition_interval
            , sub_constraint_cols
            , sub_premake
            , sub_optimize_trigger
            , sub_optimize_constraint
            , sub_epoch
            , sub_inherit_fk
            , sub_retention
            , sub_retention_schema
            , sub_retention_keep_table
            , sub_retention_keep_index
            , sub_infinite_time_partitions
            , sub_automatic_maintenance
            , sub_jobmon
            , sub_trigger_exception_handling
            , sub_upsert
            , sub_trigger_return_null
            , sub_template_table
            , sub_inherit_privileges
            , sub_constraint_valid
            , sub_subscription_refresh
            , sub_date_trunc_interval
        FROM @extschema@.part_config_sub
        WHERE sub_parent = p_parent_table
    LOOP
        IF v_jobmon_schema IS NOT NULL THEN
            v_step_id := add_step(v_job_id, 'Subpartitioning '||v_partition_name);
        END IF;
        v_sql := format('SELECT @extschema@.create_parent(
                 p_parent_table := %L
                , p_control := %L
                , p_type := %L
                , p_interval := %L
                , p_constraint_cols := %L
                , p_premake := %L
                , p_automatic_maintenance := %L
                , p_inherit_fk := %L
                , p_epoch := %L
                , p_template_table := %L
                , p_jobmon := %L
                , p_start_partition := %L
                , p_date_trunc_interval := %L )'
            , v_parent_schema||'.'||v_partition_name
            , v_row.sub_control
            , v_row.sub_partition_type
            , v_row.sub_partition_interval
            , v_row.sub_constraint_cols
            , v_row.sub_premake
            , v_row.sub_automatic_maintenance
            , v_row.sub_inherit_fk
            , v_row.sub_epoch
            , v_row.sub_template_table
            , v_row.sub_jobmon
            , p_start_partition
            , v_row.sub_date_trunc_interval);
        RAISE DEBUG 'create_partition_id (create_parent loop): %', v_sql;
        EXECUTE v_sql;

        UPDATE @extschema@.part_config SET
            retention_schema = v_row.sub_retention_schema
            , retention_keep_table = v_row.sub_retention_keep_table
            , retention_keep_index = v_row.sub_retention_keep_index
            , optimize_trigger = v_row.sub_optimize_trigger
            , optimize_constraint = v_row.sub_optimize_constraint
            , infinite_time_partitions = v_row.sub_infinite_time_partitions
            , trigger_exception_handling = v_row.sub_trigger_exception_handling
            , upsert = v_row.sub_upsert
            , inherit_privileges = v_row.sub_inherit_privileges
            , trigger_return_null = v_row.sub_trigger_return_null
            , constraint_valid = v_row.sub_constraint_valid
            , subscription_refresh = v_row.sub_subscription_refresh
        WHERE parent_table = v_parent_schema||'.'||v_partition_name;

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

    END LOOP; -- end sub partitioning LOOP

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

    IF v_publications IS NOT NULL THEN
        -- NOTE: Publications currently not supported on parent table, but are supported on the table partitions if individually assigned.
        PERFORM @extschema@.apply_publications(p_parent_table, v_parent_schema, v_partition_name);
    END IF;

    v_partition_created := true;

END LOOP;

-- v_analyze is a local check if a new table is made.
-- p_analyze is a parameter to say whether to run the analyze at all. Used by create_parent() to avoid long exclusive lock or run_maintenence() to avoid long creation runs.
IF v_analyze AND p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Analyzing partition set: %s', p_parent_table));
    END IF;

    EXECUTE format('ANALYZE %I.%I', v_parent_schema, v_parent_tablename);

    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
    IF v_partition_created = false THEN
        v_step_id := add_step(v_job_id, format('No partitions created for partition set: %s', p_parent_table));
        PERFORM update_step(v_step_id, 'OK', 'Done');
    END IF;

    PERFORM close_job(v_job_id);
END IF;

EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');

RETURN v_partition_created;

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 CREATE TABLE: %s'')', v_jobmon_schema, p_parent_table) 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 'sqljson_jsontable': Write the SELECT query (example 25).

SELECT * FROM JSON_TABLE(jsonb '{"d1": "foo"}', '$'
    COLUMNS (js1 jsonb_test_domain PATH '$.d1' DEFAULT 'foo2'::jsonb_test_domain ON ERROR));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '{"d1": "foo"}', '$'
    COLUMNS (js1 jsonb_test_domain PATH '$.d1' DEFAULT 'foo2'::jsonb_test_domain ON ERROR))) AS _sub;


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

select numrange(1.0, 2.0) + numrange(1.5, 3.0);

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

SELECT count(*) FROM (select numrange(1.0, 2.0) + numrange(1.5, 3.0)) AS _sub;


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

-- hasnt_materialized_view( materialized_view, description )
CREATE OR REPLACE FUNCTION hasnt_materialized_view ( NAME, TEXT )
RETURNS TEXT AS $$
    SELECT ok( NOT _rexists( 'm', $1 ), $2 );
$$ LANGUAGE SQL;

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


Question: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 272).

SELECT nummultirange(numrange(1,2)) -|- nummultirange();

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

SELECT count(*) FROM (SELECT nummultirange(numrange(1,2)) -|- nummultirange()) AS _sub;


Question: pgTAP test for Hastap (assertion 24).

SELECT * FROM check_test(
    has_schema( 'someschema', 'lol' ),
    true,
    'has_schema(schema, desc)',
    'lol',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

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

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


Question: PostgreSQL regression test 'numeric': Write the SELECT query (example 933).

select * from generate_series(1::numeric, 3::numeric) i, generate_series(1,5,i) j;

SELECT count(*) FROM (select * from generate_series(1::numeric, 3::numeric) i, generate_series(1,5,i) j) AS _sub;


Question: Rank employees by salary within each department.

CREATE TABLE employees (id serial PRIMARY KEY, name text, department text, salary numeric(10,2));

SELECT name, department, salary, RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank FROM employees;

Explanation: RANK() window function partitioned by department, ordered by salary descending. Ties get the same rank.

SELECT department, count(*) FROM employees GROUP BY department;


Question: PostgreSQL regression test 'sqljson': Write the SELECT query (example 171).

SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL)
OVER (ORDER BY k RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v);

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

SELECT count(*) FROM (SELECT to_json(a) AS a, JSON_OBJECTAGG(k : v ABSENT ON NULL)
OVER (ORDER BY k RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM (VALUES (1,1), (1,null), (2,2)) a(k,v)) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'without_overlaps' (example 310).

INSERT INTO temporal_mltrng (id, valid_at) VALUES ('[1,2)', datemultirange(daterange('2010-01-01', '2020-01-01'))) ON CONFLICT DO NOTHING;

Explanation: DML from PostgreSQL core regression test for Without Overlaps.


Question: Write the DDL statement from PostgreSQL regression test 'create_table' (example 188).

CREATE TABLE h2part_3 PARTITION OF hash_parted2 FOR VALUES WITH (MODULUS 8, REMAINDER 4);

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


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

CREATE FUNCTION cube_inter(cube, cube)
RETURNS cube
AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT PARALLEL SAFE;

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


Question: Write the DDL statement from PostgreSQL regression test 'join' (example 195).

Explanation: DDL from PostgreSQL core regression test for Join.


Question: Write the DML statement from PostgreSQL regression test 'identity' (example 78).

INSERT INTO itestv11 OVERRIDING SYSTEM VALUE VALUES (11, 'xyz');

Explanation: DML from PostgreSQL core regression test for Identity.


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

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


Question: Show a SQL definition from the timescaledb project (plan_hypertable_inline, item 10).

-- test with CTE
-- these cases are just to make sure we're everything is alright with
-- the way we identify hypertables to prune chunks - we abuse ctename
-- for this purpose. So double-check if we're not breaking plans
-- with CTEs here.
CREATE OR REPLACE FUNCTION test_f(_ts bigint)
RETURNS SETOF test LANGUAGE SQL STABLE
as $f$
   WITH ct AS MATERIALIZED (
      SELECT DISTINCT ON (a) * FROM test WHERE b >= _ts AND b <= _ts + 2
   )
   SELECT * FROM ct
$f$;

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


Question: Show an example of PostgreSQL ALTER PROCEDURE (example 4).

ALTER PROCEDURE insert_data(integer, integer) DEPENDS ON EXTENSION myext;

Explanation: PostgreSQL ALTER PROCEDURE command.


Question: PostgreSQL regression test 'strings': Write the SELECT query (example 419).

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

SELECT count(*) FROM (select to_oct(-1234) AS "37777775456") AS _sub;


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

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


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

insert into arr_pk_tbl values (1, '{1,2,3}');

Explanation: DML from PostgreSQL core regression test for Arrays.


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

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

SELECT count(*) FROM (SELECT timestamp '1995-08-06 infinity') AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'with' (example 25).

INSERT INTO department VALUES (6, 4, 'F');

Explanation: DML from PostgreSQL core regression test for With.


Question: Show a SQL definition from the timescaledb project (time_bucket, item 8).

CREATE OR REPLACE FUNCTION @extschema@.time_bucket(bucket_width INTERVAL, ts UUID, origin TIMESTAMPTZ) RETURNS TIMESTAMPTZ
  AS '@MODULE_PATHNAME@', 'ts_uuid_bucket' LANGUAGE C IMMUTABLE PARALLEL SAFE STRICT;


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


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

SELECT jsonb_exists('{"a":"null", "b":"qq"}', 'a');

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

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


Question: PostgreSQL regression test 'collate.utf8': Write the SELECT query (example 23).

SELECT 'xAb' !~* '[c-d]' COLLATE PG_C_UTF8;

Explanation: Regression test for Collate.Utf8 in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT 'xAb' !~* '[c-d]' COLLATE PG_C_UTF8) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'without_overlaps' (example 246).

INSERT INTO temporal_rng (id, valid_at) VALUES ('[1,2)', daterange('2000-01-01', '2010-01-01'));


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

CREATE OR REPLACE FUNCTION _timescaledb_functions.hypertable_local_size(
	schema_name_in name,
	table_name_in name)
RETURNS TABLE (
	table_bytes BIGINT,
	index_bytes BIGINT,
	toast_bytes BIGINT,
	total_bytes BIGINT)
LANGUAGE SQL VOLATILE STRICT AS
$BODY$
    /* get the main hypertable id and sizes */
    WITH _hypertable_sizes AS (
        SELECT
            id,
            COALESCE((relsize).total_size, 0) AS total_bytes,
            COALESCE((relsize).heap_size, 0) AS heap_bytes,
            COALESCE((relsize).index_size, 0) AS index_bytes,
            COALESCE((relsize).toast_size, 0) AS toast_bytes,
            0::BIGINT AS compressed_total_size,
            0::BIGINT AS compressed_index_size,
            0::BIGINT AS compressed_toast_size,
            0::BIGINT AS compressed_heap_size
        FROM
            _timescaledb_catalog.hypertable ht
            JOIN pg_class c ON relname = ht.table_name AND c.relkind = 'r'
            JOIN pg_namespace n ON n.oid = c.relnamespace
            AND n.nspname = ht.schema_name
            JOIN LATERAL _timescaledb_functions.relation_size(c.oid) AS relsize ON TRUE
        WHERE
            schema_name = schema_name_in
            AND table_name = table_name_in
    ),
    /* calculate the size of the hypertable chunks */
    _chunk_sizes AS (
        SELECT
            chunk_id,
            COALESCE(ch.total_bytes, 0) AS total_bytes,
            COALESCE(ch.heap_bytes, 0) AS heap_bytes,
            COALESCE(ch.index_bytes, 0) AS index_bytes,
            COALESCE(ch.toast_bytes, 0) AS toast_bytes,
            COALESCE(ch.compressed_total_size, 0) AS compressed_total_size,
            COALESCE(ch.compressed_index_size, 0) AS compressed_index_size,
            COALESCE(ch.compressed_toast_size, 0) AS compressed_toast_size,
            COALESCE(ch.compressed_heap_size, 0) AS compressed_heap_size
        FROM
            _timescaledb_internal.hypertable_chunk_local_size ch
            JOIN _hypertable_sizes ht ON ht.id = ch.hypertable_id
        WHERE hypertable_schema = schema_name_in
          AND hypertable_name = table_name_in
    )
    /* calculate the SUM of the hypertable and chunk sizes */
	SELECT
		(SUM(heap_bytes)  + SUM(compressed_heap_size))::BIGINT AS heap_bytes,
		(SUM(index_bytes) + SUM(compressed_index_size))::BIGINT AS index_bytes,
		(SUM(toast_bytes) + SUM(compressed_toast_size))::BIGINT AS toast_bytes,
		(SUM(total_bytes) + SUM(compressed_total_size))::BIGINT AS total_bytes
	FROM
		(SELECT * FROM _hypertable_sizes
         UNION ALL
         SELECT * FROM _chunk_sizes) AS sizes;


Question: Show a query using PostgreSQL contrib extension 'intarray' (example 173).

SELECT count(*) from more__int WHERE a @> '{20,23}' or a @> '{50,68}';

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


Question: Show a SQL definition from the citus project (issue_5099, item 3).

CREATE TYPE comp_type AS (
    int_field_1 BIGINT,
    int_field_2 BIGINT
);

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


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

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


Question: Write the DDL statement from PostgreSQL regression test 'indirect_toast' (example 17).

CREATE TRIGGER indtoasttest_update_indirect
        BEFORE INSERT OR UPDATE
        ON indtoasttest
        FOR EACH ROW
        EXECUTE PROCEDURE update_using_indirect();

Explanation: DDL from PostgreSQL core regression test for Indirect Toast.


Question: Show a SQL definition from the pglogical project (preseed, item 23).

\c :provider1_dsn
CREATE OR REPLACE FUNCTION public.pglogical_regress_variables(
    OUT orig_provider_dsn text,
    OUT provider_dsn text,
    OUT provider1_dsn text,
    OUT subscriber_dsn text
    ) RETURNS record LANGUAGE SQL AS $f$
SELECT
    current_setting('pglogical.orig_provider_dsn'),
    current_setting('pglogical.provider_dsn'),
    current_setting('pglogical.provider1_dsn'),
    current_setting('pglogical.subscriber_dsn')
$f$;

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


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


Question: PostgreSQL regression test 'create_am': Write the SELECT query (example 72).

SELECT amname FROM pg_class c, pg_am am
  WHERE c.relam = am.oid AND c.oid = 'heapmv'::regclass;

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

SELECT count(*) FROM (SELECT amname FROM pg_class c, pg_am am
  WHERE c.relam = am.oid AND c.oid = 'heapmv'::regclass) AS _sub;


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

select ('[{"name": "alice"}, {"name": "bob"}]'::jsonb)::name;

SELECT count(*) FROM (select ('[{"name": "alice"}, {"name": "bob"}]'::jsonb)::name) AS _sub;


Question: PL/pgSQL test: Plperl Call (example 3).

CREATE PROCEDURE test_proc2()
LANGUAGE plperl
AS $$
return 5
$$;

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Call.


Question: PostgreSQL Ddl: show example 27.

CREATE TABLE products ( product_no integer UNIQUE NULLS NOT DISTINCT , name text, price numeric );

Explanation: Example from PostgreSQL documentation on Ddl.


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

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

SELECT count(*) FROM (SELECT '0/16AE7F7'::pg_lsn - '0/16AE7F8'::pg_lsn) AS _sub;


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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'merge' (example 443).

CREATE TABLE pa_source (sid integer, delta float)
  WITH (autovacuum_enabled=off);

Explanation: DDL from PostgreSQL core regression test for Merge.


Question: PostgreSQL regression test 'domain': Write the SELECT query (example 103).

select row(0,1)::dcomptype;  -- fail

alter type comptype alter attribute r type varchar;  -- fail
alter type comptype alter attribute r type bigint;

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

SELECT count(*) FROM (select row(0,1)::dcomptype;  -- fail

alter type comptype alter attribute r type varchar;  -- fail
alter type comptype alter attribute r type bigint) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'stats_ext' (example 243).

CREATE STATISTICS s12 (ndistinct) ON c, d, (c * 10), (d - 1) FROM ndistinct;

Explanation: DDL from PostgreSQL core regression test for Stats Ext.


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

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

SELECT count(*) FROM (select '{(a,a)}'::textmultirange) AS _sub;


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

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

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

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


Question: Write the DDL statement from PostgreSQL regression test 'subselect' (example 140).

create temp table tb (id int primary key, aval int);

Explanation: DDL from PostgreSQL core regression test for Subselect.


Question: Write the DML statement from PostgreSQL regression test 'oid' (example 15).

INSERT INTO OID_TBL(f1) VALUES ('    5d');

Explanation: DML from PostgreSQL core regression test for Oid.


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

-- ALL (should not benefit from functional dependencies)
SELECT * FROM check_estimated_rows('SELECT * FROM functional_dependencies WHERE a IN (1, 51) AND b = ALL (ARRAY[''1''])');

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


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

SELECT * FROM pg_input_error_info('[(1,2),(3)]', 'path');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[(1,2),(3)]', 'path')) AS _sub;


Question: PL/pgSQL test: Plpython Types (example 21).

SELECT * FROM test_type_conversion_int4(-100);

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


Question: Write the DDL statement from PostgreSQL regression test 'update' (example 48).

CREATE TABLE upsert_test_2 (b TEXT, a INT PRIMARY KEY);

Explanation: DDL from PostgreSQL core regression test for Update.


Question: PL/pgSQL test: Plperl Plperlu (example 15).

-- make sure our overloaded require op gets restored/set correctly
select use_plperlu();

Explanation: PL/pgSQL example from PostgreSQL source test for Plperl Plperlu.


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

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