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

SELECT a, coalesce(b, 'foo') FROM collate_test3 ORDER BY 2;

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

SELECT count(*) FROM (SELECT a, coalesce(b, 'foo') FROM collate_test3 ORDER BY 2) AS _sub;


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

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

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

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


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

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


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

SELECT * FROM pg_buffercache_evict_relation('temp_pg_buffercache');

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


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

INSERT INTO PKTABLE VALUES (2, 3, 4, 'test3');

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


Question: pgTAP test for Enumtap (assertion 6).

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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


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

CREATE TYPE test_type2 AS (a int, b text);

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


Question: Write the DDL statement from PostgreSQL regression test 'index_including' (example 111).

CREATE INDEX on tbl USING btree(c1, c2) INCLUDE (c3, c4);

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


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

--
--
--
-- numeric ops
--
--
--
-- define the GiST support methods
CREATE FUNCTION gbt_numeric_consistent(internal,numeric,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 'box': Write the SELECT query (example 49).

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

SELECT count(*) FROM (SELECT * FROM box_temp WHERE f1 |&> '(49.99,49.99),(49.99,49.99)') AS _sub;


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

create trigger convslot_test_parent_update
    after update on convslot_test_parent
    referencing old table as old_rows new table as new_rows
    for each statement execute procedure convslot_trig4();

Explanation: DDL from PostgreSQL core regression test for Triggers.


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

SELECT $1 AS a \parse p1
SET plan_cache_mode TO force_generic_plan;

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


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

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


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

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

SELECT count(*) FROM (SELECT a, b, c FROM test_like_4d) AS _sub;


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

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


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

INSERT INTO pitest1_p2 (f1, f2, f3) VALUES ('2016-08-2', 'before attaching', 100);

Explanation: DML from PostgreSQL core regression test for Identity.


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

CREATE USER MAPPING FOR current_user SERVER s9;

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


Question: Show an example of PostgreSQL CREATE TABLE (example 9).

CREATE TABLE distributors ( did integer CONSTRAINT no_null NOT NULL, name varchar(40) NOT NULL );

Explanation: PostgreSQL CREATE TABLE command.


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

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


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

SELECT split_part('abcTdefTghi', 't'::citext, 2) = 'def' AS t;

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


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

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

SELECT count(*) FROM (SELECT '2011-03-27 01:59:59 MSK'::timestamptz) AS _sub;


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

CREATE TABLE fk_partitioned_fk_3_1 PARTITION OF fk_partitioned_fk_3 FOR VALUES WITH (MODULUS 5, REMAINDER 1);

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


Question: PostgreSQL regression test 'tstypes': Write the SELECT query (example 4).

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

SELECT count(*) FROM (SELECT ' 1'::tsvector) AS _sub;


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

SELECT regr_avgx(b, a), regr_avgy(b, a) FROM aggtest;

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

SELECT count(*) FROM (SELECT regr_avgx(b, a), regr_avgy(b, a) FROM aggtest) AS _sub;


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

CREATE FUNCTION gin_extract_value_int4(int4, internal)
RETURNS internal
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE;


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

UPDATE temporal_partitioned_mltrng SET valid_at = datemultirange(daterange('2016-01-01', '2016-02-01'))
  WHERE id = '[5,6)' AND valid_at = datemultirange(daterange('2018-01-01', '2018-02-01'));

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


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

INSERT INTO macaddr8_data VALUES (19, '0800.2b01.0203.0405');

Explanation: DML from PostgreSQL core regression test for Macaddr8.


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

select v||'a', case when grouping(v||'a') = 1 then 1 else 0 end, count(*)
  from unnest(array[1,1], array['a','b']) u(i,v)
 group by rollup(i, v||'a') order by 1,3;

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

SELECT count(*) FROM (select v||'a', case when grouping(v||'a') = 1 then 1 else 0 end, count(*)
  from unnest(array[1,1], array['a','b']) u(i,v)
 group by rollup(i, v||'a') order by 1,3) AS _sub;


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

SELECT *
  FROM J1_TBL t1 (a, b, c), J2_TBL t2 (d, e);

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

SELECT count(*) FROM (SELECT *
  FROM J1_TBL t1 (a, b, c), J2_TBL t2 (d, e)) AS _sub;


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

SELECT * FROM multiout_record_as('tuple', 'three', 3, false);

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


Question: pgTAP test for Policy (assertion 51).

SELECT * FROM check_test(
    policy_cmd_is( 'public', 'passwd', 'daemon_insert', 'delete', 'whatever' ),
    false,
    'policy_cmd_is(schema, table, policy, command, desc) for INSERT should fail',
    'whatever',
    '        have: INSERT
        want: DELETE'
);

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: PostgreSQL Queries: show example 22.

SELECT product_id, p.name, (sum(s.units) * (p.price - p.cost)) AS profit FROM products p LEFT JOIN sales s USING (product_id) WHERE s.date > CURRENT_DATE - INTERVAL '4 weeks' GROUP BY product_id, p.name, p.price, p.cost HAVING sum(p.price * s.units) > 5000;

Explanation: Example from PostgreSQL documentation on Queries.


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

SELECT * FROM INT8_TBL WHERE q2 > '456'::int2;

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

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE q2 > '456'::int2) AS _sub;


Question: pgTAP test for Ownership (assertion 77).

SELECT * FROM check_test(
    composite_owner_is('public', '__not__sometype', current_user, 'mumble'),
	false,
    'composite_owner_is(sch, non-composite, user)',
    'mumble',
    '    Composite type public.__not__sometype does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

INSERT INTO num_exp_div VALUES (9,0,'NaN');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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


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

SELECT timestamptz '-infinity infinity';

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

SELECT count(*) FROM (SELECT timestamptz '-infinity infinity') AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 35).

SELECT crypt('a very much longer text to encrypt.  This one even stretches over more'
                 'than one line.', '$6$rounds=1400$anotherlongsaltstring')
           = '$6$rounds=1400$anotherlongsalts$POfYwTEok97VWcjxIiSOjiykti.o/pQs.wPvMxQ6Fm7I6IoYN3CmLs66x9t0oSwbtEW7o7UmJEiDwGqd8p4ur1' AS result;

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


Question: pgTAP test for Coltap (assertion 86).

SELECT * FROM check_test(
    col_default_is( 'public', 'sometab', 'myat', 'now()', 'desc'::text ),
    true,
    'col_default_is( schema, tab, col, expression, desc )',
    'desc',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

CREATE TABLE ctlt10 (LIKE ctlseq1);  -- fail

CREATE VIEW ctlv1 AS SELECT * FROM ctlt4;

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


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

CREATE TABLE prt2_m_p2 PARTITION OF prt2_m FOR VALUES FROM (250, 250) TO (500, 500);

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


Question: PostgreSQL regression test 'partition_prune': Write the SELECT query (example 134).

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

SELECT count(*) FROM (select * from boolpart where a = false) AS _sub;


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

SELECT hmac(
'Hi There',
'\x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'::bytea,
'sha1');


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

CREATE INDEX tbspace_reindex_part_index_0 ON ONLY tbspace_reindex_part_0 (c1);

Explanation: DDL from PostgreSQL core regression test for Tablespace.


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

SELECT o.* FROM OID_TBL o WHERE o.f1 > '1234';

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

SELECT count(*) FROM (SELECT o.* FROM OID_TBL o WHERE o.f1 > '1234') AS _sub;


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

-- create function to filter unstable results of EXPLAIN
CREATE FUNCTION explain_filter(text) RETURNS setof text
LANGUAGE plpgsql AS
$$
declare
    ln text;
begin
    for ln in execute $1
    loop
        -- Remove the path portion of foreign file names
        ln := regexp_replace(ln, 'Foreign File: .*/([a-z.]+)$', 'Foreign File: .../\1');
        return next ln;
    end loop;
end;
$$;

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


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

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

SELECT count(*) FROM (select ('[1, "2", null]'::jsonb)[1.0]) AS _sub;


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

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

SELECT count(*) FROM (select jsonb_path_query('{"g": [{"x": 2}, {"y": 3}]}', 'lax $.g ? (exists (@.x))')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'generated_virtual' (example 20).

CREATE TABLE gtest_err_7b (a int PRIMARY KEY, b int GENERATED ALWAYS AS (row_number() OVER (ORDER BY a)) VIRTUAL);

Explanation: DDL from PostgreSQL core regression test for Generated Virtual.


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

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


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

CREATE TABLE unbounded_range_part PARTITION OF range_parted4 FOR VALUES FROM (MINVALUE, MINVALUE, MINVALUE) TO (MAXVALUE, MAXVALUE, MAXVALUE);

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


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

insert into inserttest (f3.if2[1], f3.if2[2]) select 'bear', 'beer';

Explanation: DML from PostgreSQL core regression test for Insert.


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

INSERT INTO caster (text)          VALUES ('12.42'::float4);

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


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

INSERT INTO textrange_test VALUES('["a",]');

Explanation: DML from PostgreSQL core regression test for Rangetypes.


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

Explanation: DML from PostgreSQL core regression test for Create Type.


Question: Write the DML statement from PostgreSQL regression test 'collate.utf8' (example 28).

INSERT INTO test_pg_unicode_fast VALUES
  ('abc DEF 123abc'),
  ('ábc sßs ßss DÉF'),
  ('ǄxxǄ ǆxxǅ ǅxxǆ'),
  (U&'Λλ 1a \FF11a'),
  ('ȺȺȺ'),
  ('ⱥⱥⱥ'),
  ('ⱥȺ');

Explanation: DML from PostgreSQL core regression test for Collate.Utf8.


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

INSERT INTO PG_LSN_TBL VALUES ('FFFFFFFF/FFFFFFFF');

Explanation: DML from PostgreSQL core regression test for Pg Lsn.


Question: Show a SQL definition from the pg_partman project (pg_partman--1.3.0--1.4.0, item 9).

/*
 * Function to manage pre-creation of the next partitions in a time-based partition set.
 * Also manages dropping old partitions if the retention option is set.
 */
CREATE OR REPLACE FUNCTION run_maintenance() RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_adv_lock                      boolean;
v_create_count                  int := 0;
v_current_partition_timestamp   timestamp;
v_datetime_string               text;
v_drop_count                    int := 0;
v_job_id                        bigint;
v_jobmon_schema                 text;
v_last_partition_timestamp      timestamp;
v_old_search_path               text;
v_premade_count                 int;
v_quarter                       text;
v_step_id                       bigint;
v_row                           record;
v_time_position                 int;
v_year                          text;

BEGIN

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

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

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;

FOR v_row IN
SELECT parent_table
    , type
    , part_interval::interval
    , control
    , premake
    , datetime_string
    , last_partition
    , undo_in_progress
FROM @extschema@.part_config WHERE type = 'time-static' OR type = 'time-dynamic'
LOOP

    CONTINUE WHEN v_row.undo_in_progress;

    CASE
        WHEN v_row.part_interval = '15 mins' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                '15min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 15.0);
        WHEN v_row.part_interval = '30 mins' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP) +
                '30min'::interval * floor(date_part('minute', CURRENT_TIMESTAMP) / 30.0);
        WHEN v_row.part_interval = '1 hour' THEN
            v_current_partition_timestamp := date_trunc('hour', CURRENT_TIMESTAMP);
         WHEN v_row.part_interval = '1 day' THEN
            v_current_partition_timestamp := date_trunc('day', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '1 week' THEN
            v_current_partition_timestamp := date_trunc('week', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '1 month' THEN
            v_current_partition_timestamp := date_trunc('month', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '3 months' THEN
            v_current_partition_timestamp := date_trunc('quarter', CURRENT_TIMESTAMP);
        WHEN v_row.part_interval = '1 year' THEN
            v_current_partition_timestamp := date_trunc('year', CURRENT_TIMESTAMP);
    END CASE;

    -- Get position of last occurance of '_p' in child partition name
    v_time_position := (length(v_row.last_partition) - position('p_' in reverse(v_row.last_partition))) + 2;
    IF v_row.part_interval != '3 months' THEN
       v_last_partition_timestamp := to_timestamp(substring(v_row.last_partition from v_time_position), v_row.datetime_string);
    ELSE
        -- to_timestamp doesn't recognize 'Q' date string formater. Handle it
        v_year := split_part(substring(v_row.last_partition from v_time_position), 'q', 1);
        v_quarter := split_part(substring(v_row.last_partition from v_time_position), 'q', 2);
        CASE
            WHEN v_quarter = '1' THEN
                v_last_partition_timestamp := to_timestamp(v_year || '-01-01', 'YYYY-MM-DD');
            WHEN v_quarter = '2' THEN
                v_last_partition_timestamp := to_timestamp(v_year || '-04-01', 'YYYY-MM-DD');
            WHEN v_quarter = '3' THEN
                v_last_partition_timestamp := to_timestamp(v_year || '-07-01', 'YYYY-MM-DD');
            WHEN v_quarter = '4' THEN
                v_last_partition_timestamp := to_timestamp(v_year || '-10-01', 'YYYY-MM-DD');
        END CASE;
    END IF;

    -- 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.part_interval::interval));
    -- 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
        EXECUTE 'SELECT @extschema@.create_next_time_partition('||quote_literal(v_row.parent_table)||')';
        v_create_count := v_create_count + 1;
        IF v_row.type = 'time-static' THEN
            EXECUTE 'SELECT @extschema@.create_time_function('||quote_literal(v_row.parent_table)||')';
        END IF;
        v_last_partition_timestamp := v_last_partition_timestamp + v_row.part_interval;
        v_premade_count = round(EXTRACT('epoch' FROM age(v_last_partition_timestamp, v_current_partition_timestamp)) / EXTRACT('epoch' FROM v_row.part_interval::interval));
    END LOOP;

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 (type = 'time-static' OR type = 'time-dynamic')
LOOP
    v_drop_count := v_drop_count + @extschema@.drop_partition_time(v_row.parent_table);
END LOOP;
FOR v_row IN
    SELECT parent_table FROM @extschema@.part_config WHERE retention IS NOT NULL AND undo_in_progress = false AND (type = 'id-static' OR type = 'id-dynamic')
LOOP
    v_drop_count := v_drop_count + @extschema@.drop_partition_id(v_row.parent_table);
END LOOP;

IF v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', 'Partition maintenance finished. '||v_create_count||' partitions made. '||v_drop_count||' partitions dropped.');
    PERFORM close_job(v_job_id);
    EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
END IF;

PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));

EXCEPTION
    WHEN QUERY_CANCELED THEN
        PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));
        RAISE EXCEPTION '%', SQLERRM;
    WHEN OTHERS THEN
        IF v_jobmon_schema IS NOT NULL THEN
            EXECUTE 'SELECT set_config(''search_path'',''@extschema@,'||v_jobmon_schema||''',''false'')';
            IF v_job_id IS NULL THEN
                v_job_id := add_job('PARTMAN RUN MAINTENANCE');
                v_step_id := add_step(v_job_id, 'EXCEPTION before job logging started');
            END IF;
            IF v_step_id IS NULL THEN
                v_step_id := add_step(v_job_id, 'EXCEPTION before first step logged');
            END IF;
            PERFORM update_step(v_step_id, 'CRITICAL', 'ERROR: '||coalesce(SQLERRM,'unknown'));
            PERFORM fail_job(v_job_id);
            EXECUTE 'SELECT set_config(''search_path'','''||v_old_search_path||''',''false'')';
        END IF;
        PERFORM pg_advisory_unlock(hashtext('pg_partman run_maintenance'));
        RAISE EXCEPTION '%', SQLERRM;
END
$$;

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


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

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

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


Question: PL/pgSQL test: Plperl (example 80).

CREATE OR REPLACE FUNCTION foo_ordered() RETURNS orderedfootype AS $$
    return {x => 5, y => 4};
$$ LANGUAGE plperl;

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


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


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

INSERT INTO fk_notpartitioned_fk VALUES(100,100), (1000,1000);

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


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

CREATE TABLE concur_reindex_tab2 (c1 int REFERENCES concur_reindex_tab);

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


Question: Show a query using PostgreSQL contrib extension 'sepgsql' (example 2).

INSERT INTO t1 (SELECT x, md5(x::text) FROM generate_series(1,100) x);

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


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

select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb;

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

SELECT count(*) FROM (select * from nestjsonb where j @> '{"a":[[{"x":2}]]}'::jsonb) AS _sub;


Question: pgTAP test for Pgtap--0.91.0--0.92.0 (assertion 2).

CREATE OR REPLACE FUNCTION _cexists ( NAME, NAME )
RETURNS BOOLEAN AS $$
    SELECT EXISTS(
        SELECT true
          FROM pg_catalog.pg_class c
          JOIN pg_catalog.pg_attribute a ON c.oid = a.attrelid
         WHERE c.relname = $1
           AND pg_catalog.pg_table_is_visible(c.oid)
           AND a.attnum > 0
           AND NOT a.attisdropped
           AND a.attname = $2
    );
$$ LANGUAGE SQL;

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


Question: pgTAP test for Ownership (assertion 113).

SELECT * FROM check_test(
    index_owner_is('sometab', 'idx_hey', '__no-one', 'mumble'),
	false,
    'index_owner_is(table, index, non-user)',
    'mumble',
    '        have: ' || current_user || '
        want: __no-one'
);

Explanation: SQL assertion from pgTAP test suite for Ownership.


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

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

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


Question: Write the DML statement from PostgreSQL regression test 'portals' (example 210).

Explanation: DML from PostgreSQL core regression test for Portals.


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

select sum(c) from gstest2
  group by grouping sets(grouping sets(a, grouping sets(a), a))
  order by 1 desc;

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

SELECT count(*) FROM (select sum(c) from gstest2
  group by grouping sets(grouping sets(a, grouping sets(a), a))
  order by 1 desc) AS _sub;


Question: pgTAP test for Resultset (assertion 21).

INSERT INTO names (name) VALUES ('Samantha');

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

INSERT INTO entry (accession, txid) VALUES ('A00003', '1') ;

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


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

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

SELECT count(*) FROM (SELECT '-10e400'::float8) AS _sub;


Question: PostgreSQL regression test 'copy2': Write the SELECT query (example 158).

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

SELECT count(*) FROM (SELECT c, d FROM forcetest WHERE a = 2) AS _sub;


Question: pgTAP test for Fktap (assertion 19).

SELECT * FROM check_test(
    has_fk( 'fk' ),
    true,
    'has_fk( table )',
    'Table fk should have a foreign key constraint'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

select textmultirange(textrange('a', 'c'), textrange('f', 'g'));

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

SELECT count(*) FROM (select textmultirange(textrange('a', 'c'), textrange('f', 'g'))) AS _sub;


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

INSERT INTO num_result SELECT id, 0, POWER(numeric '10', LN(ABS(round(val,200))))
    FROM num_data
    WHERE val != '0.0';

Explanation: DML from PostgreSQL core regression test for Numeric.


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


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

SELECT to_timestamp('2011-12-18 11:38 JUNK', 'YYYY-MM-DD HH12:MI TZ');  -- error
SELECT to_timestamp('2011-12-18 11:38 ...', 'YYYY-MM-DD HH12:MI TZ');  -- error

SELECT to_timestamp('2011-12-18 11:38 -05', 'YYYY-MM-DD HH12:MI OF');

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

SELECT count(*) FROM (SELECT to_timestamp('2011-12-18 11:38 JUNK', 'YYYY-MM-DD HH12:MI TZ');  -- error
SELECT to_timestamp('2011-12-18 11:38 ...', 'YYYY-MM-DD HH12:MI TZ');  -- error

SELECT to_timestamp('2011-12-18 11:38 -05', 'YYYY-MM-DD HH12:MI OF')) AS _sub;


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

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

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


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

--
--
--
-- uuid ops
--
--
--
-- define the GiST support methods
CREATE FUNCTION gbt_uuid_consistent(internal,uuid,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 803).

SELECT jsonb_path_match('1', '$', silent => false);

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

SELECT count(*) FROM (SELECT jsonb_path_match('1', '$', silent => false)) AS _sub;


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

SELECT 'bıt' ILIKE 'BIT' COLLATE "en_US" AS "false";

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

SELECT count(*) FROM (SELECT 'bıt' ILIKE 'BIT' COLLATE "en_US" AS "false") AS _sub;


Question: PL/pgSQL test: Plpgsql Control (example 56).

$$ language plpgsql immutable;

select case_test(1);
select case_test(2);
select case_test(12);
select case_test(13);

-- test line comment between WHEN and THEN
create or replace function case_comment(int) returns text as $$
begin
  case $1
    when 1 -- comment before THEN
      then return 'one';

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


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

CREATE TRIGGER show_trigger_data_trig_before
BEFORE INSERT OR UPDATE OR DELETE ON trigger_test
FOR EACH ROW EXECUTE PROCEDURE trigger_data(23,'skidoo');

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


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

SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 OR b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl t
 WHERE a <<< 0 AND (b <<< 0 OR t.* <<< (1, 1) IS NOT NULL); -- Should not leak
DELETE FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak

-- Create plain inheritance parent table with no access permissions
RESET SESSION AUTHORIZATION;

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

SELECT count(*) FROM (SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl WHERE a <<< 0 OR b <<< 0; -- Should not leak
SELECT * FROM tststats.priv_test_tbl t
 WHERE a <<< 0 AND (b <<< 0 OR t.* <<< (1, 1) IS NOT NULL); -- Should not leak
DELETE FROM tststats.priv_test_tbl WHERE a <<< 0 AND b <<< 0; -- Should not leak

-- Create plain inheritance parent table with no access permissions
RESET SESSION AUTHORIZATION) AS _sub;


Question: PostgreSQL regression test 'misc_functions': Write the SELECT query (example 14).

SELECT num_nulls(1, 2, NULL::text, NULL::point, '', int8 '9', 1.0 / NULL);

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

SELECT count(*) FROM (SELECT num_nulls(1, 2, NULL::text, NULL::point, '', int8 '9', 1.0 / NULL)) AS _sub;


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


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

--
-- brin_metapage_info()
--
CREATE FUNCTION brin_metapage_info(IN page bytea, OUT magic text,
	OUT version integer, OUT pagesperrange integer, OUT lastrevmappage bigint)
AS 'MODULE_PATHNAME', 'brin_metapage_info'
LANGUAGE C STRICT PARALLEL SAFE;


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

select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2)
on (x1 = xx1 and y2 is not null);

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

SELECT count(*) FROM (select * from (x left join y on (x1 = y1)) left join x xx(xx1,xx2)
on (x1 = xx1 and y2 is not null)) AS _sub;


Question: PostgreSQL regression test 'dbsize': Write the SELECT query (example 24).

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

SELECT count(*) FROM (SELECT pg_size_bytes('++123 kB')) AS _sub;


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

CREATE PUBLICATION testpub_xxx WITH (publish_generated_columns = foo);

Explanation: DDL from PostgreSQL core regression test for Publication.


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

-- has_opclass( name, description )
CREATE OR REPLACE FUNCTION has_opclass( NAME, TEXT )
RETURNS TEXT AS $$
    SELECT ok( _opc_exists( $1 ), $2)
$$ LANGUAGE SQL;

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


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

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

SELECT count(*) FROM (select '1?(2>3)'::jsonpath) AS _sub;


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

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

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


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

---------------------------------------------------
-- ISMN:
CREATE FUNCTION btismncmp(ismn, ismn)
	RETURNS int4
	AS 'btint8cmp'
	LANGUAGE 'internal'
	IMMUTABLE STRICT
	PARALLEL SAFE;


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

UPDATE range_parted set d = d - 10 WHERE d > 10;

Explanation: DML from PostgreSQL core regression test for Update.


Question: PostgreSQL regression test 'without_overlaps': Write the SELECT query (example 234).

SELECT * FROM tp2 ORDER BY id, valid_at;

Explanation: Regression test for Without Overlaps in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM tp2 ORDER BY id, valid_at) AS _sub;


Question: Show a SQL definition from the pg_partman project (pg_partman--2.5.1--2.6.0, item 10).

/*
 * Function to ensure a column is dropped in all child tables, no matter when it was created
 */
CREATE FUNCTION drop_partition_column(p_parent_table text, p_column text) RETURNS void
    LANGUAGE plpgsql SECURITY DEFINER
    AS $$
DECLARE

v_child_oid         oid;
v_parent_oid        oid;
v_parent_schema     text;
v_parent_tablename  text;
v_row               record;

BEGIN

SELECT c.oid, n.nspname, c.relname INTO v_parent_oid, v_parent_schema, v_parent_tablename
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name
AND c.relname = split_part(p_parent_table, '.', 2)::name;

IF v_parent_oid IS NULL THEN
    RAISE EXCEPTION 'Given parent table does not exist: %', p_parent_table;
END IF;

EXECUTE format('ALTER TABLE %I.%I DROP COLUMN IF EXISTS %I', v_parent_schema, v_parent_tablename, p_column);

FOR v_row IN
    SELECT n.nspname AS child_schema, c.relname AS child_table
    FROM pg_catalog.pg_inherits h
    JOIN pg_catalog.pg_class c ON h.inhrelid = c.oid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE inhparent = v_parent_oid
LOOP

    EXECUTE format('ALTER TABLE %I.%I DROP COLUMN IF EXISTS %I', v_row.child_schema, v_row.child_table, p_column);

END LOOP;

END
$$;

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


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

SELECT * FROM test_table_record_as('list', 'three', 3, false);

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


Question: pgTAP test for Aretap (assertion 125).

SELECT * FROM check_test(
    rules_are( 'public', 'fou', ARRAY['ins_me', 'del_me'] ),
    false,
    'rules_are(schema, table, rules) + extra & missing',
    'Relation public.fou should have the correct rules',
    '    Extra rules:
        upd_me
    Missing rules:
        del_me'
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: pgTAP test for Functap (assertion 270).

-- is_window ( NAME, NAME, NAME[] )
-- isnt_window ( NAME, NAME, NAME[] )
SELECT * FROM check_test(
    is_window( 'pg_catalog', 'ntile', ARRAY['int'] ),
    true,
    'is_window(schema, win, arg)',
    'Function pg_catalog.ntile(int) should be a window function',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

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

SELECT count(*) FROM (SELECT EXTRACT(HOUR        FROM TIME '2020-05-26 13:30:25.575401')) AS _sub;


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

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


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

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

SELECT count(*) FROM (SELECT pg_input_is_valid('1234.567', 'numeric(7,4)')) AS _sub;


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

SELECT to_timestamp('  20050302', 'YYYYMMDD');

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

SELECT count(*) FROM (SELECT to_timestamp('  20050302', 'YYYYMMDD')) AS _sub;


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

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

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


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

SELECT count(*) FROM quad_point_tbl WHERE p |>> '(5000, 4000)';

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

SELECT count(*) FROM (SELECT count(*) FROM quad_point_tbl WHERE p |>> '(5000, 4000)') AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'triggers' (example 344).

Explanation: DML from PostgreSQL core regression test for Triggers.


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

INSERT INTO num_exp_ln VALUES (0,'NaN');

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

SELECT count(*) FROM (SELECT nextval('sequence_test2')) AS _sub;


Question: PostgreSQL regression test 'partition_info': Write the SELECT query (example 59).

SELECT * FROM pg_partition_tree('ptif_test_view');

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

SELECT count(*) FROM (SELECT * FROM pg_partition_tree('ptif_test_view')) AS _sub;


Question: pgTAP test for Pgtap--0.91.0--0.92.0 (assertion 111).

-- any_column_privs_are ( table, user, privileges[], description )
CREATE OR REPLACE FUNCTION any_column_privs_are ( NAME, NAME, NAME[], TEXT )
RETURNS TEXT AS $$
DECLARE
    grants TEXT[] := _get_ac_privs( $2, quote_ident($1) );
BEGIN
    IF grants[1] = 'undefined_table' THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            '    Table ' || quote_ident($1) || '.' || quote_ident($2) || ' does not exist'
        );
    ELSIF grants[1] = 'undefined_role' THEN
        RETURN ok(FALSE, $4) || E'\n' || diag(
            '    Role ' || quote_ident($2) || ' does not exist'
        );
    END IF;
    RETURN _assets_are('privileges', grants, $3, $4);
END;
$$ LANGUAGE plpgsql;

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


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

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

SELECT count(*) FROM (select return_int_input(1) in (10, 9, 2, 8, 3, 7, 4, 6, 5, 1)) AS _sub;


Question: pgTAP test for Functap (assertion 302).

-- Test diagnostics
SELECT * FROM check_test(
    is_window( 'nada', ARRAY['int'], 'whatever' ),
    false,
    'is_window(nowin, arg, desc)',
    'whatever',
    '    Function nada(int) does not exist'
);


Question: Show an example of PostgreSQL CREATE SCHEMA (example 5).

CREATE SCHEMA hollywood; CREATE TABLE hollywood.films (title text, release date, awards text[]); CREATE VIEW hollywood.winners AS SELECT title, release FROM hollywood.films WHERE awards IS NOT NULL;

Explanation: PostgreSQL CREATE SCHEMA command.


Question: Write the DML statement from PostgreSQL regression test 'memoize' (example 16).

INSERT INTO expr_key (x, t)
SELECT d1::numeric, d1::text FROM (
    SELECT round((d / pi())::numeric, 7) AS d1 FROM generate_series(1, 20) AS d
) t;

Explanation: DML from PostgreSQL core regression test for Memoize.


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

INSERT INTO INSERT_TBL(x,y) VALUES (5, 'check failed');

Explanation: DML from PostgreSQL core regression test for Constraints.


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

end$$ language plpgsql parallel safe;
CREATE TABLE fooarr(f1 text, f2 int[], f3 text);
INSERT INTO fooarr VALUES('1', ARRAY[1,2], 'one');

PREPARE pstmt(text, int[]) AS SELECT * FROM fooarr WHERE f1 = $1 AND f2 = $2;
EXPLAIN (COSTS OFF) EXECUTE pstmt('1', make_some_array(1,2));
EXECUTE pstmt('1', make_some_array(1,2));
DEALLOCATE pstmt;

-- test interaction between subquery and partial_paths
CREATE VIEW tenk1_vw_sec WITH (security_barrier) AS SELECT * FROM tenk1;
EXPLAIN (COSTS OFF)
SELECT 1 FROM tenk1_vw_sec
  WHERE (SELECT sum(f1) FROM int4_tbl WHERE f1 < unique1) < 100;

rollback;

-- test that a newly-created session role propagates to workers.
begin;
create role regress_parallel_worker;
set session authorization regress_parallel_worker;
select current_setting('session_authorization');
set debug_parallel_query = 1;
select current_setting('session_authorization');
rollback;

-- test that function option SET ROLE works in parallel workers.
create role regress_parallel_worker;

create function set_and_report_role() returns text as
  $$ select current_setting('role') $$ language sql parallel safe
  set role = regress_parallel_worker;

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


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


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

CREATE DOMAIN uint2 AS int2 CHECK (VALUE >= 0);

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


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

SELECT count(*) FROM timestamptztmp WHERE a <= '2018-12-18 10:59:54 GMT+3';

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


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

CREATE INDEX clstr_tst_b ON clstr_tst (b);

Explanation: DDL from PostgreSQL core regression test for Cluster.


Question: Show a query using PostgreSQL contrib extension 'fuzzystrmatch' (example 6).

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


Question: pgTAP test for Functap (assertion 10).

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

Explanation: SQL assertion from pgTAP test suite for Functap.


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

SELECT '4.0'::citext::numeric = 4.0 AS t;

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


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

SELECT pg_get_constraintdef(oid), conname, conkey FROM pg_constraint WHERE conrelid = 'sales_apr2022'::regclass::oid ORDER BY conname COLLATE "C";

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

SELECT count(*) FROM (SELECT pg_get_constraintdef(oid), conname, conkey FROM pg_constraint WHERE conrelid = 'sales_apr2022'::regclass::oid ORDER BY conname COLLATE "C") AS _sub;


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

SELECT numrange(1,2) <@ nummultirange(numrange(null,null));

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

SELECT count(*) FROM (SELECT numrange(1,2) <@ nummultirange(numrange(null,null))) AS _sub;


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

CREATE FUNCTION tfnp(int[],int) RETURNS int[] AS
'select $1 || $2' LANGUAGE SQL;

Explanation: DDL from PostgreSQL core regression test for Polymorphism.


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

-- Create the operator class
CREATE OPERATOR CLASS gist_float4_ops
DEFAULT FOR TYPE float4 USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	OPERATOR	6	<> ,
	OPERATOR	15	<-> FOR ORDER BY pg_catalog.float_ops ,
	FUNCTION	1	gbt_float4_consistent (internal, float4, int2, oid, internal),
	FUNCTION	2	gbt_float4_union (internal, internal),
	FUNCTION	3	gbt_float4_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_float4_penalty (internal, internal, internal),
	FUNCTION	6	gbt_float4_picksplit (internal, internal),
	FUNCTION	7	gbt_float4_same (gbtreekey8, gbtreekey8, internal),
	FUNCTION	8	gbt_float4_distance (internal, float4, int2, oid, internal),
	FUNCTION	9	gbt_float4_fetch (internal),
	FUNCTION	11	gbt_float4_sortsupport (internal),
	FUNCTION	12 ("any", "any") gist_translate_cmptype_btree (int),
	STORAGE		gbtreekey8;

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


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

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


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

INSERT INTO notnull_tbl1 VALUES (NULL, 1), (300, 3);


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

SELECT '1'::seg && '0 .. 1'::seg AS bool;

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


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

INSERT INTO timetzcmp (r_id,a) SELECT 14,count(*) FROM timetztmp WHERE a >= '07:46:45 GMT+2';


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

SELECT cume_dist() OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10;

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

SELECT count(*) FROM (SELECT cume_dist() OVER (PARTITION BY four ORDER BY ten), ten, four FROM tenk1 WHERE unique2 < 10) AS _sub;


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

-- should fail, event triggers cannot have declared arguments
create function test_event_trigger_arg(name text)
returns event_trigger as $$ BEGIN RETURN 1; END $$ language plpgsql;

-- should fail, SQL functions cannot be event triggers
create function test_event_trigger_sql() returns event_trigger as $$
SELECT 1 $$ language sql;

-- should fail, no elephant_bootstrap entry point
create event trigger regress_event_trigger on elephant_bootstrap
   execute procedure test_event_trigger();

-- OK
create event trigger regress_event_trigger on ddl_command_start
   execute procedure test_event_trigger();

-- OK
create event trigger regress_event_trigger_end on ddl_command_end
   execute function test_event_trigger();

-- should fail, food is not a valid filter variable
create event trigger regress_event_trigger2 on ddl_command_start
   when food in ('sandwich')
   execute procedure test_event_trigger();

-- should fail, sandwich is not a valid command tag
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('sandwich')
   execute procedure test_event_trigger();

-- should fail, create skunkcabbage is not a valid command tag
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('create table', 'create skunkcabbage')
   execute procedure test_event_trigger();

-- should fail, can't have event triggers on event triggers
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('DROP EVENT TRIGGER')
   execute procedure test_event_trigger();

-- should fail, can't have event triggers on global objects
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('CREATE ROLE')
   execute procedure test_event_trigger();

-- should fail, can't have event triggers on global objects
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('CREATE DATABASE')
   execute procedure test_event_trigger();

-- should fail, can't have event triggers on global objects
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('CREATE TABLESPACE')
   execute procedure test_event_trigger();

-- should fail, can't have same filter variable twice
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('create table') and tag in ('CREATE FUNCTION')
   execute procedure test_event_trigger();

-- should fail, can't have arguments
create event trigger regress_event_trigger2 on ddl_command_start
   execute procedure test_event_trigger('argument not allowed');

-- OK
create event trigger regress_event_trigger2 on ddl_command_start
   when tag in ('create table', 'CREATE FUNCTION')
   execute procedure test_event_trigger();

-- OK
comment on event trigger regress_event_trigger is 'test comment';

-- drop as non-superuser should fail
create role regress_evt_user;
set role regress_evt_user;
create event trigger regress_event_trigger_noperms on ddl_command_start
   execute procedure test_event_trigger();
reset role;

-- test enabling and disabling
alter event trigger regress_event_trigger disable;
-- fires _trigger2 and _trigger_end should fire, but not _trigger
create table event_trigger_fire1 (a int);
alter event trigger regress_event_trigger enable;
set session_replication_role = replica;
-- fires nothing
create table event_trigger_fire2 (a int);
alter event trigger regress_event_trigger enable replica;
-- fires only _trigger
create table event_trigger_fire3 (a int);
alter event trigger regress_event_trigger enable always;
-- fires only _trigger
create table event_trigger_fire4 (a int);
reset session_replication_role;
-- fires all three
create table event_trigger_fire5 (a int);
-- non-top-level command
create function f1() returns int
language plpgsql
as $$
begin
  create table event_trigger_fire6 (a int);

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


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

CREATE OPERATOR CLASS alt_opc2 FOR TYPE macaddr USING hash AS STORAGE macaddr;

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


Question: Write the DDL statement from PostgreSQL regression test 'gin' (example 20).

create index on t_gin_test_tbl using gin (i, j);

Explanation: DDL from PostgreSQL core regression test for Gin.


Question: Write the DDL statement from PostgreSQL regression test 'jsonb' (example 468).

CREATE INDEX jidx ON testjsonb USING gin (j);

Explanation: DDL from PostgreSQL core regression test for Jsonb.


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

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

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

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


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

select pgp_pub_decrypt(dearmor(data), dearmor(seckey))
from keytbl, encdata where keytbl.id=6 and encdata.id=4;

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


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

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


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

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


Question: Show an example of PostgreSQL VALUES (example 4).

SELECT f.* FROM films f, (VALUES('MGM', 'Horror'), ('UA', 'Sci-Fi')) AS t (studio, kind) WHERE f.studio = t.studio AND f.kind = t.kind; UPDATE employees SET salary = salary * v.increase FROM (VALUES(1, 200000, 1.2), (2, 400000, 1.4)) AS v (depno, target, increase) WHERE employees.depno = v.depno AND employees.sales >= v.target;

Explanation: PostgreSQL VALUES command.


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

CREATE OR REPLACE FUNCTION @extschema@.check_name_length (p_object_name text, p_suffix text DEFAULT NULL, p_table_partition boolean DEFAULT FALSE) RETURNS text
    LANGUAGE plpgsql IMMUTABLE SECURITY DEFINER
    SET search_path TO pg_catalog, pg_temp
    AS $$
DECLARE
    v_new_length    int;
    v_new_name      text;
BEGIN
/*
 * Truncate the name of the given object if it is greater than the postgres default max (63 characters).
 * Also appends given suffix and schema if given and truncates the name so that the entire suffix will fit.
 * Returns original name (with suffix if given) if it doesn't require truncation
 * Retains SECURITY DEFINER since it is called by trigger functions and did not want to break installations prior to 4.0.0
 */

IF p_table_partition IS TRUE AND (p_suffix IS NULL) THEN
    RAISE EXCEPTION 'Table partition name requires a suffix value';
END IF;

IF p_table_partition THEN  -- 61 characters to account for _p in partition name
    IF char_length(p_object_name) + char_length(p_suffix) >= 61 THEN
        v_new_length := 61 - char_length(p_suffix);
        v_new_name := substring(p_object_name from 1 for v_new_length) || '_p' || p_suffix;
    ELSE
        v_new_name := p_object_name||'_p'||p_suffix;
    END IF;
ELSE
    IF char_length(p_object_name) + char_length(COALESCE(p_suffix, '')) >= 63 THEN
        v_new_length := 63 - char_length(COALESCE(p_suffix, ''));
        v_new_name := substring(p_object_name from 1 for v_new_length) || COALESCE(p_suffix, '');
    ELSE
        v_new_name := p_object_name||COALESCE(p_suffix, '');
    END IF;
END IF;

RETURN v_new_name;

END
$$;

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


Question: Show a SQL definition from the zombodb project (zombodb--3000.0.7--3000.0.8, item 2).

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.0.8 (c11743812075d06c3caa219343ae7f0ca6c1ee27)'
$$;

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


Question: pgTAP test for Aretap (assertion 96).

SELECT * FROM check_test(
    users_are( ___myusers(current_user), 'whatever' ),
    false,
    'users_are(users, desc) extras',
    'whatever',
    '    Extra users:
        ' || quote_ident(current_user)
);

Explanation: SQL assertion from pgTAP test suite for Aretap.


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

SELECT JSON_QUERY(jsonb '"123.1"', '$' RETURNING int8 error on error);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '"123.1"', '$' RETURNING int8 error on error)) AS _sub;


Question: pgTAP test for Resultset (assertion 126).

INSERT INTO names (name) VALUES ('Landon');

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

Explanation: DML from PostgreSQL core regression test for Arrays.


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

SELECT '-1 .. 1'::seg <@ '0'::seg AS bool;


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

--
-- bt_index_parent_check()
--
CREATE FUNCTION bt_index_parent_check(index regclass)
RETURNS VOID
AS 'MODULE_PATHNAME', 'bt_index_parent_check'
LANGUAGE C STRICT PARALLEL RESTRICTED;

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


Question: pgTAP test for Pgtap--1.1.0--1.2.0 (assertion 73).

-- is_window( schema, function, args[] )
CREATE OR REPLACE FUNCTION is_window( NAME, NAME, NAME[] )
RETURNS TEXT AS $$
    SELECT _func_compare(
        $1, $2, $3, _type_func('w', $1, $2, $3),
        'Function ' || quote_ident($1) || '.' || quote_ident($2) || '(' ||
        array_to_string($3, ', ') || ') should be a window function'
    );
$$ LANGUAGE sql;

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


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

CREATE FUNCTION autoprewarm_dump_now()
RETURNS pg_catalog.int8 STRICT
AS 'MODULE_PATHNAME', 'autoprewarm_dump_now'
LANGUAGE C;


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

SELECT * FROM test_bpchar WHERE i>'abc' ORDER BY i;

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


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

SELECT d1 AS european_postgres FROM TIMESTAMP_TBL;

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

SELECT count(*) FROM (SELECT d1 AS european_postgres FROM TIMESTAMP_TBL) AS _sub;


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

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

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


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

Explanation: DML from PostgreSQL core regression test for Domain.


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

CREATE INDEX macaddr_data_btree ON macaddr_data USING btree (b);

Explanation: DDL from PostgreSQL core regression test for Macaddr.


Question: PL/pgSQL test: Plpython Record (example 38).

SELECT * FROM test_type_record_as('list', null, null, false);

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


Question: Write the DDL statement from PostgreSQL regression test 'create_type' (example 14).

CREATE FUNCTION text_w_default_in(cstring)
   RETURNS text_w_default
   AS 'textin'
   LANGUAGE internal STRICT IMMUTABLE;

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


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

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

SELECT count(*) FROM (SELECT ts_lexize('hunspell_long', 'ex-machina')) AS _sub;


Question: Show a SQL definition from the pg_partman project (test-id-1-bigint-list, item 6).

CREATE TABLE partman_test.id_taptest_table
    (col1 bigint
        , col2 bigint NOT NULL
        , col3 timestamptz DEFAULT now()
        , col4 text)
    PARTITION BY LIST (col2);


Question: pgTAP test for Inheritance (assertion 57).

SELECT * FROM check_test(
    is_ancestor_of( 'parent', 'nope', 1 ),
    false,
    'is_ancestor_of(ptab, nope, 1)',
    'Table parent should be ancestor 1 of nope',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


Question: pgTAP test for Fktap (assertion 58).

SELECT * FROM check_test(
    fk_ok( 'fk', 'pk_id', 'pk', 'id', 'WHATEVER' ),
    true,
    'basic fk_ok noschema',
    'WHATEVER'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


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

SELECT * FROM test_date WHERE i <= '2004-10-25 00:00:01'::timestamptz ORDER BY i;


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

SELECT * FROM test_float4 WHERE i > 1e-300::float8 ORDER BY i;


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

select generate_series(timestamp '1995-08-06 12:12:12', timestamp '1996-08-06 12:12:12', interval 'infinity');

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

SELECT count(*) FROM (select generate_series(timestamp '1995-08-06 12:12:12', timestamp '1996-08-06 12:12:12', interval 'infinity')) AS _sub;


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

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

SELECT count(*) FROM (SELECT int8 '0x8000000000000000') AS _sub;


Question: Show a query using PostgreSQL contrib extension 'sepgsql' (example 6).

INSERT INTO t1p (SELECT x, md5(x::text) FROM generate_series(0,99) x);

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


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

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

SELECT count(*) FROM (SELECT float4send('985e15'::float4)) AS _sub;


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

SELECT i, to_timestamp('2018-11-02 12:34:56.123456', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i;

SELECT count(*) FROM (SELECT i, to_timestamp('2018-11-02 12:34:56.123456', 'YYYY-MM-DD HH24:MI:SS.FF' || i) FROM generate_series(1, 6) i) AS _sub;


Question: PostgreSQL regression test 'partition_split': Write the SELECT query (example 332).

SELECT tableoid::regclass, * FROM t ORDER BY tableoid::regclass::text COLLATE "C", b;

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

SELECT count(*) FROM (SELECT tableoid::regclass, * FROM t ORDER BY tableoid::regclass::text COLLATE "C", b) AS _sub;


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

CREATE TABLE FKTABLE (ftest1 int, ftest2 inet, FOREIGN KEY(ftest1, ftest2) REFERENCES pktable(ptest2, ptest1));

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


Question: Show an example of PostgreSQL CREATE COLLATION (example 1).

CREATE COLLATION french (locale = 'fr_FR.utf8');

Explanation: PostgreSQL CREATE COLLATION command.


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

--
-- ISMN13 operators:
--
---------------------------------------------------
CREATE OPERATOR < (
	PROCEDURE = isnlt,
	LEFTARG = ismn13,
	RIGHTARG = ismn13,
	COMMUTATOR = >,
	NEGATOR = >=,
	RESTRICT = scalarltsel,
	JOIN = scalarltjoinsel);

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


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

CREATE TABLE part_m02 PARTITION OF pa_target
	FOR VALUES FROM ('2017-02-01') TO ('2017-03-01')
	PARTITION BY LIST (tid);

Explanation: DDL from PostgreSQL core regression test for Merge.


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

CREATE INDEX name_index on dist_table(name);

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


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

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

SELECT count(*) FROM (select '$ ? (@.a < -.1e+1)'::jsonpath) AS _sub;


Question: Show an example of PostgreSQL CREATE TABLE AS (example 1).

CREATE TABLE films_recent AS SELECT * FROM films WHERE date_prod >= '2002-01-01';

Explanation: PostgreSQL CREATE TABLE AS command.


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

SELECT timestamptz(date '1994-01-01', time with time zone '10:00-8') AS "Jan_01_1994_10am";

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

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


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

SELECT * FROM INT8_TBL WHERE '123'::int2 > q1;

SELECT count(*) FROM (SELECT * FROM INT8_TBL WHERE '123'::int2 > q1) AS _sub;


Question: PL/pgSQL test: Plperl Setup (example 2).

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


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

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

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


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

CREATE TABLE prt1_l_p2_p1 PARTITION OF prt1_l_p2 FOR VALUES IN ('0000', '0001');

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


Question: Show a SQL definition from the zombodb project (zombodb--3000.1.3--3000.1.4, item 16).

CREATE OR REPLACE FUNCTION dsl.link_options(options text[], query pg_catalog.zdbquery) RETURNS pg_catalog.zdbquery AS 'MODULE_PATHNAME', 'link_options_wrapper' IMMUTABLE LANGUAGE c PARALLEL SAFE;

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


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

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

SELECT count(*) FROM (SELECT regexp_count('123123123123', '123', 33)) AS _sub;


Question: pgTAP test for Functap (assertion 152).

SELECT * FROM check_test(
    is_normal_function( 'public', 'tap_accum', ARRAY[etype()], 'whatever' ),
    false,
    'is_normal_function(schema, agg, args, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

CREATE TABLE plt2_adv_p4 PARTITION OF plt2_adv FOR VALUES IN ('0004', '0005');


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

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


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

INSERT INTO TIMESTAMP_TBL VALUES ('19970710 173201 America/Does_not_exist');

Explanation: DML from PostgreSQL core regression test for Timestamp.


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

insert into parted_conflict_test (a, b) values (2, 'n') on conflict (a) do select where parted_conflict_test.b = 'x' returning *;

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


Question: Show a query using PostgreSQL contrib extension 'spi' (example 24).

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


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

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

SELECT count(*) FROM (select '"foo"'::jsonb #>> '{}') AS _sub;


Question: pgTAP test for Fktap (assertion 65).

SELECT * FROM check_test(
    fk_ok( 'fk', ARRAY['pk_id'], 'ok', ARRAY['fid'], 'WHATEVER' ),
    false,
    'fk_ok bad PK test',
    'WHATEVER',
    '        have: fk(pk_id) REFERENCES pk(id)
        want: fk(pk_id) REFERENCES ok(fid)'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


Question: PostgreSQL regression test 'opr_sanity': Write the SELECT query (example 32).

SELECT p1.oid, p1.proname
FROM pg_proc as p1
WHERE proallargtypes IS NOT NULL AND proargmodes IS NOT NULL AND
    array_length(proallargtypes,1) <> array_length(proargmodes,1);

Explanation: Regression test for Opr Sanity in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT p1.oid, p1.proname
FROM pg_proc as p1
WHERE proallargtypes IS NOT NULL AND proargmodes IS NOT NULL AND
    array_length(proallargtypes,1) <> array_length(proargmodes,1)) AS _sub;


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

select cume_dist(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4)) v(x);

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

SELECT count(*) FROM (select cume_dist(3) within group (order by x)
from (values (1),(1),(2),(2),(3),(3),(4)) v(x)) AS _sub;


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

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 29 17:32:01 1997');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


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

SELECT count(*) FROM (SELECT '-Infinity'::float8::numeric) AS _sub;


Question: pgTAP test for Enumtap (assertion 1).

\unset ECHO
\i test/setup.sql

SELECT plan(108);

Explanation: SQL assertion from pgTAP test suite for Enumtap.


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

Explanation: DML from PostgreSQL core regression test for Domain.


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

CREATE ROLE regress_password_null PASSWORD NULL;

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


Question: pgTAP test for Index (assertion 37).

SELECT * FROM check_test(
    has_index( 'sometab', 'idx_baz' ),
    true,
    'has_index() no schema or cols or desc',
    'Index idx_baz should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


Question: Write the DML statement from PostgreSQL regression test 'partition_join' (example 429).

INSERT INTO plt1_adv VALUES (-1, -1, NULL);

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


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

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


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 338).

create table idxpart3 (b int not null, a int not null);

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

update test_jsonb_subscript set test_json[0] = '1';

Explanation: DML from PostgreSQL core regression test for Jsonb.


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

CREATE INDEX comment_test_index ON comment_test(indexed_col);

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


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

create index j2_id1_idx on j2 (id1) where id1 % 1000 = 1;

Explanation: DDL from PostgreSQL core regression test for Join.


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

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

SELECT count(*) FROM (SELECT regdatabase('Nonexistent')) AS _sub;


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

INSERT INTO caster (citext)        VALUES ('1999-01-08 04:05:06'::timestamptz);

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


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

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

SELECT count(*) FROM (select jsonb_path_query('"2017-03-10T12:34:56.789Z"', '$.datetime()')) AS _sub;


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

SELECT * FROM hat_data WHERE hat_name = 'h8';

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

SELECT count(*) FROM (SELECT * FROM hat_data WHERE hat_name = 'h8') AS _sub;


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

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

SELECT count(*) FROM (select make_interval(secs := -1e18)) AS _sub;


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

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


Question: pgTAP test for Resultset (assertion 343).

INSERT INTO folk (id, name) VALUES ( 44, 'Larry' );

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

CREATE FUNCTION dblink_get_notify(
    conname TEXT,
    OUT notify_name TEXT,
    OUT be_pid INT4,
    OUT extra TEXT
)
RETURNS setof record
AS 'MODULE_PATHNAME', 'dblink_get_notify'
LANGUAGE C STRICT PARALLEL RESTRICTED;

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


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

insert into parted_conflict_test (a, b) values (1, 'a'), (2, 'a'), (4, 'a') on conflict (a) do update set b = excluded.b where excluded.b = 'b';

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


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

CREATE OPERATOR -> (
	LEFTARG = hstore,
	RIGHTARG = text[],
	PROCEDURE = slice_array
);


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

INSERT INTO temporal_rng3 (id, valid_at) VALUES ('[3,4)', daterange('2018-01-01', NULL));

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


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

CREATE UNIQUE INDEX dedup_unique ON dedup_unique_test_table (a) WITH (deduplicate_items=on);

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


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

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


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

ALTER AGGREGATE mypercentile(float8, integer) SET SCHEMA myschema;

Explanation: PostgreSQL ALTER AGGREGATE command.


Question: PostgreSQL regression test 'indexing': Write the SELECT query (example 136).

select relname, relkind from pg_class where relname like 'idxpart%' order by relname;

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

SELECT count(*) FROM (select relname, relkind from pg_class where relname like 'idxpart%' order by relname) AS _sub;


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

SELECT count(*) FROM (SELECT to_regtypemod('timestamp(4)')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'tsearch' (example 33).

create index wowidx on test_tsvector using gist (a);

Explanation: DDL from PostgreSQL core regression test for Tsearch.


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

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


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

insert into arrtest_f values(8,'cat2',1.32);

Explanation: DML from PostgreSQL core regression test for Arrays.


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

-- Triggers on leaf partition part_c_1_100
CREATE TRIGGER c1_delete_trig
  AFTER DELETE ON part_c_1_100 for each statement execute procedure trigfunc();

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


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

Explanation: DML from PostgreSQL core regression test for Subselect.


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

select * from testrngfunc(); -- fail

drop function testrngfunc();

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

SELECT count(*) FROM (select * from testrngfunc(); -- fail

drop function testrngfunc()) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

SELECT width_bucket(0, -1e100::numeric, 1, 10);

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

SELECT count(*) FROM (SELECT width_bucket(0, -1e100::numeric, 1, 10)) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'amcheck' (example 19).

INSERT INTO gin_check_text_array select array_agg(sha256(round(random()*300 + 300)::text::bytea)::text) from generate_series(1, 10000) as i group by i % 100;

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


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

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

SELECT count(*) FROM (select '{"a":1 , "b":2, "c":3}'::jsonb - '{}'::text[]) AS _sub;


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

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


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

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


Question: Show a SQL definition from the timescaledb project (partitioned_hypertable, item 17).

\set ON_ERROR_STOP 0
CREATE TABLE part_col_specified(time TIMESTAMPTZ, device TEXT) PARTITION BY RANGE (time) WITH (timescaledb.hypertable, timescaledb.partition_column='time');

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


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

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

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


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

CREATE TABLE fk_partitioned_fk_1 PARTITION OF fk_partitioned_fk FOR VALUES IN (NULL,500,501,502);

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


Question: Write the DDL statement from PostgreSQL regression test 'identity' (example 145).

CREATE TABLE pitest1_p1 PARTITION OF pitest1 FOR VALUES FROM ('2016-07-01') TO ('2016-08-01');

Explanation: DDL from PostgreSQL core regression test for Identity.


Question: pgTAP test for Ruletap (assertion 45).

SELECT * FROM check_test(
    rule_is_on( 'public', 'sometab', 'foo_me'::name, 'u' ),
    false,
    'rule_is_on(schema, table, invalid rule, u, desc)',
    'Rule foo_me should be on UPDATE to public.sometab',
    '    Rule foo_me does not exist on public.sometab'
);

Explanation: SQL assertion from pgTAP test suite for Ruletap.


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

select * from (select * from t order by a) s order by a, b limit 5;

Explanation: Regression test for Incremental Sort in PostgreSQL core test suite.

SELECT count(*) FROM (select * from (select * from t order by a) s order by a, b limit 5) AS _sub;


Question: pgTAP test for Hastap (assertion 256).

SELECT * FROM check_test(
    domain_type_is( 'public', 'us_postal_code', 'text', 'whatever'),
    true,
    'domain_type_is(schema, domain, type, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


Question: pgTAP test for Pgtap--1.2.0--1.3.0 (assertion 26).

CREATE OR REPLACE FUNCTION _types_are ( NAME, NAME[], TEXT, CHAR[] )
RETURNS TEXT AS $$
    SELECT _are(
        'types',
        ARRAY(
            SELECT t.typname
              FROM pg_catalog.pg_type t
              LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
             WHERE (
                     t.typrelid = 0
                 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)
             )
               AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)
               AND n.nspname = $1
               AND t.typtype = ANY( COALESCE($4, ARRAY['b', 'c', 'd', 'p', 'e']) )
            EXCEPT
            SELECT _typename($2[i])
              FROM generate_series(1, array_upper($2, 1)) s(i)
        ),
        ARRAY(
            SELECT _typename($2[i])
               FROM generate_series(1, array_upper($2, 1)) s(i)
            EXCEPT
            SELECT t.typname
              FROM pg_catalog.pg_type t
              LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
             WHERE (
                     t.typrelid = 0
                 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid)
             )
               AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)
               AND n.nspname = $1
               AND t.typtype = ANY( COALESCE($4, ARRAY['b', 'c', 'd', 'p', 'e']) )
        ),
        $3
    );
$$ LANGUAGE SQL;

Explanation: SQL assertion from pgTAP test suite for Pgtap--1.2.0--1.3.0.


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

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


Question: pgTAP test for Policy (assertion 14).

CREATE POLICY all_view ON public.passwd FOR SELECT TO root, bob, daemon USING (true);

Explanation: SQL assertion from pgTAP test suite for Policy.


Question: pgTAP test for Pktap (assertion 12).

SELECT * FROM check_test(
    has_pk( 'sometab', 'sometab should have a pk' ),
    true,
    'has_pk( table, description )',
    'sometab should have a pk',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


Question: Show a SQL definition from the pglogical project (infofuncs, item 7).

-- test upgrades
DO $$
BEGIN
        IF version() ~ 'Postgres-XL' THEN
                CREATE EXTENSION IF NOT EXISTS pglogical;
        ELSE
                CREATE EXTENSION IF NOT EXISTS pglogical VERSION '1.0.0';
        END IF;
END;
$$;

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


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

SELECT c0 FROM ONLY expr_stats_incompatible_test WHERE
(
  upper('x') LIKE ('x'||('[0,1]'::int4range))
  AND
  (c0 IN (0, 1) OR c1)
);

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

SELECT count(*) FROM (SELECT c0 FROM ONLY expr_stats_incompatible_test WHERE
(
  upper('x') LIKE ('x'||('[0,1]'::int4range))
  AND
  (c0 IN (0, 1) OR c1)
)) AS _sub;


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

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

SELECT count(*) FROM (SELECT bool '1' AS true) AS _sub;


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

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


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

INSERT INTO fast_emp4000 SELECT * FROM slow_emp4000;

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


Question: Show a query using PostgreSQL contrib extension 'pgcrypto' (example 6).

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


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

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

SELECT count(*) FROM (SELECT var_pop('nan'::float4), var_samp('nan'::float4)) AS _sub;


Question: pgTAP test for Pktap (assertion 24).

SELECT * FROM check_test(
    col_is_pk( 'sometab', 'id', 'sometab.id should be a pk' ),
    true,
    'col_is_pk( table, column, description )',
    'sometab.id should be a pk',
    ''
);


Question: Show an example of PostgreSQL DROP ROUTINE (example 1).

Explanation: PostgreSQL DROP ROUTINE command.


Question: Write the DDL statement from PostgreSQL regression test 'indexing' (example 33).

Explanation: DDL from PostgreSQL core regression test for Indexing.


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

SELECT numrange(6,7) <@ nummultirange(numrange(1,5), numrange(6,9));

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

SELECT count(*) FROM (SELECT numrange(6,7) <@ nummultirange(numrange(1,5), numrange(6,9))) AS _sub;


Question: pgTAP test for Inheritance (assertion 63).

SELECT * FROM check_test(
    isnt_ancestor_of( 'hide', 'h_parent', 'hide', 'h_child2', 2, 'Lookie' ),
    false,
    'isnt_ancestor_of(psch, ptab, csch, ctab, 2, desc)',
    'Lookie',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Inheritance.


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

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


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

CREATE OPERATOR ^@> (
        LEFTARG = ltree,
	RIGHTARG = _ltree,
	PROCEDURE = _ltree_r_risparent,
        COMMUTATOR = '^<@',
        RESTRICT = contsel,
	JOIN = contjoinsel
);

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


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

select true as "OK"
  from explain_filter('explain (settings) select * from int8_tbl i8') ln
  where ln ~ '^ *Settings: .*plan_cache_mode = ''force_generic_plan''';

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

SELECT count(*) FROM (select true as "OK"
  from explain_filter('explain (settings) select * from int8_tbl i8') ln
  where ln ~ '^ *Settings: .*plan_cache_mode = ''force_generic_plan''') AS _sub;


Question: Show a SQL definition from the pg_partman project (test-time-gap-fill, item 5).

CREATE TABLE partman_test.time_taptest_table (col1 int, col2 text default 'stuff', col3 timestamptz NOT NULL DEFAULT now()) PARTITION BY RANGE (col3);

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


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

CREATE OPERATOR ~ (
	LEFTARG = _int4,
	RIGHTARG = _int4,
	PROCEDURE = _int_contained,
	COMMUTATOR = '@',
	RESTRICT = _int_contained_sel,
	JOIN = _int_contained_joinsel
);


Question: pgTAP test for Functap (assertion 23).

SELECT * FROM check_test(
    has_function( '__cat__', '{numeric}'::name[] ),
    true,
    'custom numeric function',
    'Function __cat__(numeric) should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

$$ language plpgsql;

select compos();

drop function compos();

-- test: return a row expr as record.
create or replace function composrec() returns record as $$
declare
  v record;

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


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

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

SELECT count(*) FROM (select exp('-inf'::numeric)) AS _sub;


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

insert into inserttestb (f3.if1, f3.if2) values (1,'{foo}'), (2,'{bar}');

Explanation: DML from PostgreSQL core regression test for Insert.


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

SELECT 'h%wkeye' NOT LIKE 'h#%' ESCAPE '#' AS "true";

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

SELECT count(*) FROM (SELECT 'h%wkeye' NOT LIKE 'h#%' ESCAPE '#' AS "true") AS _sub;


Question: pgTAP test for Hastap (assertion 158).

SELECT * FROM check_test(
    hasnt_cast( 'int4', 'int8' ),
    false,
    'hasnt_cast( src, targ )',
    'Cast (int4 AS int8) should not exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

SELECT count(*) FROM test_tsvector WHERE a @@ '!(yh <-> pl)';

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

SELECT count(*) FROM (SELECT count(*) FROM test_tsvector WHERE a @@ '!(yh <-> pl)') AS _sub;


Question: Show a SQL definition from the pg_partman project (pg_partman--3.2.1--4.0.0, item 45).

CREATE OR REPLACE FUNCTION @extschema@.create_trigger(p_parent_table text) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

v_function_name         text;
v_new_search_path       text := '@extschema@,pg_temp';
v_old_search_path       text;
v_parent_schema         text;
v_parent_tablename      text;
v_relkind               char;
v_trig_name             text;
v_trig_sql              text;

BEGIN
/*
 * Function to create partitioning trigger on parent table
 */

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

SELECT n.nspname, c.relname, c.relkind INTO v_parent_schema, v_parent_tablename, v_relkind
FROM pg_catalog.pg_class c
JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
WHERE n.nspname = split_part(p_parent_table, '.', 1)::name
AND c.relname = split_part(p_parent_table, '.', 2)::name;

IF v_relkind = 'p' THEN
    RAISE EXCEPTION 'This function cannot run on natively partitioned tables';
ELSIF v_relkind IS NULL THEN
    RAISE EXCEPTION 'Unable to find given table in system catalogs: %.%', v_parent_schema, v_parent_tablename;
END IF;

v_trig_name := @extschema@.check_name_length(p_object_name := v_parent_tablename, p_suffix := '_part_trig');
-- Ensure function name matches the naming pattern
v_function_name := @extschema@.check_name_length(v_parent_tablename, '_part_trig_func', FALSE);
v_trig_sql := format('CREATE TRIGGER %I BEFORE INSERT ON %I.%I FOR EACH ROW EXECUTE PROCEDURE %I.%I()'
    , v_trig_name
    , v_parent_schema
    , v_parent_tablename
    , v_parent_schema
    , v_function_name);

EXECUTE v_trig_sql;

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

END
$$;


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

CREATE FUNCTION pglogical.replication_set_add_sequence(set_name name, relation regclass, synchronize_data boolean DEFAULT false, nsptarget name DEFAULT NULL, reltarget name DEFAULT NULL)
RETURNS boolean VOLATILE LANGUAGE c AS 'MODULE_PATHNAME', 'pglogical_replication_set_add_sequence';

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


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

CREATE TYPE tststats.ty AS (a int, b int, c text);

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


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

SELECT 1.1 AS two UNION (SELECT 2 UNION ALL SELECT 2) ORDER BY 1;

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

SELECT count(*) FROM (SELECT 1.1 AS two UNION (SELECT 2 UNION ALL SELECT 2) ORDER BY 1) AS _sub;


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

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


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

end$$ language plpgsql stable;

insert into users values('user1');

select sp_id_user('user1');
select sp_id_user('userx');

create function sp_add_user(a_login text) returns int as $$
declare my_id_user int;


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

SELECT t1.id1, t1.result, t2.expected
    FROM num_result t1, num_exp_sqrt t2
    WHERE t1.id1 = t2.id
    AND t1.result != t2.expected;

SELECT count(*) FROM (SELECT t1.id1, t1.result, t2.expected
    FROM num_result t1, num_exp_sqrt t2
    WHERE t1.id1 = t2.id
    AND t1.result != t2.expected) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'alter_table' (example 438).

INSERT INTO ataddindex VALUES (42), (43);

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


Question: Write the DML statement from PostgreSQL regression test 'transactions' (example 141).

Explanation: DML from PostgreSQL core regression test for Transactions.


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

insert into inserttest (f2[1], f2[2]) values (3,4), (5,6);


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

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


Question: PostgreSQL Indices: show example 5.

CREATE TABLE test2 ( major int, minor int, name varchar );

Explanation: Example from PostgreSQL documentation on Indices.


Question: pgTAP test for Fktap (assertion 22).

/****************************************************************************/
-- Test hasnt_fk().
SELECT * FROM check_test(
    hasnt_fk( 'public', 'fk', 'public.fk should not have an fk' ),
    false,
    'hasnt_fk( schema, table, description )',
    'public.fk should not have an fk'
);

Explanation: SQL assertion from pgTAP test suite for Fktap.


Question: Show a SQL definition from the postgrest project (errors, item 1).

\ir fixtures.sql

SELECT format('CREATE TABLE test.actors_%s ();', n)
FROM generate_series(1, 20000) n
\gexec

-- TODO add many function for fuzzy search (somehow this is making the loadtest start slow);

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


Question: Write the DML statement from PostgreSQL regression test 'collate.icu.utf8' (example 27).

INSERT INTO collate_test5 SELECT * FROM collate_test1;

Explanation: DML from PostgreSQL core regression test for Collate.Icu.Utf8.


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

SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, generate_series(1,3) DESC;

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

SELECT count(*) FROM (SELECT few.id, generate_series(1,3) g FROM few ORDER BY id, generate_series(1,3) DESC) AS _sub;


Question: PostgreSQL regression test 'triggers': Write the SELECT query (example 5).

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

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


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

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

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


Question: PostgreSQL regression test 'int4': Write the SELECT query (example 77).

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


Question: Show an example of PostgreSQL CREATE SEQUENCE (example 6).

BEGIN; COPY distributors FROM 'input_file'; SELECT setval('serial', max(id)) FROM distributors; END;

Explanation: PostgreSQL CREATE SEQUENCE command.


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

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

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


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

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

SELECT count(*) FROM (SELECT E'\\xDeAdBeEx'::bytea) AS _sub;


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

SELECT COUNT(*)
FROM pg_foreign_table
WHERE ftrelid = 'table30000'::regclass
AND ftoptions @> array['fetch_size=30000'];

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


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

ALTER EXTENSION pgtap ADD FUNCTION do_tap( text );


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

INSERT INTO caster (text)          VALUES ('( 1 , 1 ) , ( 2 , 2 )'::lseg);

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


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

SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1');

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

SELECT count(*) FROM (SELECT * FROM check_estimated_rows('SELECT * FROM mcv_lists WHERE a = 1 OR b = ''1'' OR c = 1')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'event_trigger' (example 56).

CREATE POLICY a_temp_pol ON a_temp_tbl USING (f2 > 0);

Explanation: DDL from PostgreSQL core regression test for Event Trigger.


Question: Show an example of PostgreSQL CREATE FUNCTION (example 4).

CREATE FUNCTION add(a integer, b integer) RETURNS integer LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT RETURN a + b;

Explanation: PostgreSQL CREATE FUNCTION command.


Question: Show a SQL definition from the zombodb project (zombodb--3000.1.23--3000.1.24, item 2).

CREATE FUNCTION zdb.schema_version() RETURNS text LANGUAGE sql AS $$
SELECT '3000.1.24 (52b86eba9286300f7b517c9cca76124431bdd12f)'
$$;

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


Question: pgTAP test for Hastap (assertion 259).

SELECT * FROM check_test(
    domain_type_is( 'public', 'zip_code', 'int', 'whatever'),
    false,
    'domain_type_is(schema, nondomain, type, desc)',
    'whatever',
    '   Domain public.zip_code does not exist'
);

Explanation: SQL assertion from pgTAP test suite for Hastap.