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

CREATE OR REPLACE FUNCTION _runner( text[], text[], text[], text[], text[] )
RETURNS SETOF TEXT AS $$
DECLARE
    startup  ALIAS FOR $1;
    shutdown ALIAS FOR $2;
    setup    ALIAS FOR $3;
    teardown ALIAS FOR $4;
    tests    ALIAS FOR $5;
    tap      TEXT;
    tfaild   INTEGER := 0;
    ffaild   INTEGER := 0;
    tnumb    INTEGER := 0;
    fnumb    INTEGER := 0;
    tok      BOOLEAN := TRUE;
BEGIN
    BEGIN
        -- No plan support.
        PERFORM * FROM no_plan();
        FOR tap IN SELECT * FROM _runem(startup, false) LOOP RETURN NEXT tap; END LOOP;
    EXCEPTION
        -- Catch all exceptions and simply rethrow custom exceptions. This
        -- will roll back everything in the above block.
        WHEN raise_exception THEN RAISE EXCEPTION '%', SQLERRM;
    END;

    -- Record how startup tests have failed.
    tfaild := num_failed();

    FOR i IN 1..COALESCE(array_upper(tests, 1), 0) LOOP

        -- What subtest are we running?
        RETURN NEXT diag_test_name('Subtest: ' || tests[i]);

        -- Reset the results.
        tok := TRUE;
        tnumb := COALESCE(_get('curr_test'), 0);

        IF tnumb > 0 THEN
            EXECUTE 'ALTER SEQUENCE __tresults___numb_seq RESTART WITH 1';
            PERFORM _set('curr_test', 0);
            PERFORM _set('failed', 0);
        END IF;

        DECLARE
            errstate text;
            errmsg   text;
            detail   text;
            hint     text;
            context  text;
            schname  text;
            tabname  text;
            colname  text;
            chkname  text;
            typname  text;
        BEGIN
            BEGIN
                -- Run the setup functions.
                FOR tap IN SELECT * FROM _runem(setup, false) LOOP
                    RETURN NEXT regexp_replace(tap, '^', '    ', 'gn');
                END LOOP;

                -- Run the actual test function.
                FOR tap IN EXECUTE 'SELECT * FROM ' || tests[i] || '()' LOOP
                    RETURN NEXT regexp_replace(tap, '^', '    ', 'gn');
                END LOOP;

                -- Run the teardown functions.
                FOR tap IN SELECT * FROM _runem(teardown, false) LOOP
                    RETURN NEXT regexp_replace(tap, '^', '    ', 'gn');
                END LOOP;

                -- Emit the plan.
                fnumb := COALESCE(_get('curr_test'), 0);
                RETURN NEXT '    1..' || fnumb;

                -- Emit any error messages.
                IF fnumb = 0 THEN
                    RETURN NEXT '    # No tests run!';
                    tok = false;
                ELSE
                    -- Report failures.
                    ffaild := num_failed();
                    IF ffaild > 0 THEN
                        tok := FALSE;
                        RETURN NEXT '    ' || diag(
                            'Looks like you failed ' || ffaild || ' test' ||
                             CASE ffaild WHEN 1 THEN '' ELSE 's' END
                             || ' of ' || fnumb
                        );
                    END IF;
                END IF;

            EXCEPTION WHEN OTHERS THEN
                -- Something went wrong. Record that fact.
                errstate := SQLSTATE;
                errmsg := SQLERRM;
                GET STACKED DIAGNOSTICS
                    detail  = PG_EXCEPTION_DETAIL,
                    hint    = PG_EXCEPTION_HINT,
                    context = PG_EXCEPTION_CONTEXT,
                    schname = SCHEMA_NAME,
                    tabname = TABLE_NAME,
                    colname = COLUMN_NAME,
                    chkname = CONSTRAINT_NAME,
                    typname = PG_DATATYPE_NAME;
            END;

            -- Always raise an exception to rollback any changes.
            RAISE EXCEPTION '__TAP_ROLLBACK__';

        EXCEPTION WHEN raise_exception THEN
            IF errmsg IS NOT NULL THEN
                -- Something went wrong. Emit the error message.
                tok := FALSE;
               RETURN NEXT regexp_replace( diag('Test died: ' || _error_diag(
                   errstate, errmsg, detail, hint, context, schname, tabname, colname, chkname, typname
               )), '^', '    ', 'gn');
                errmsg := NULL;
            END IF;
        END;

        -- Restore the sequence.
        EXECUTE 'ALTER SEQUENCE __tresults___numb_seq RESTART WITH ' || tnumb + 1;
        PERFORM _set('curr_test', tnumb);
        PERFORM _set('failed', tfaild);

        -- Record this test.
        RETURN NEXT ok(tok, tests[i]);
        IF NOT tok THEN tfaild := tfaild + 1; END IF;

    END LOOP;

    -- Run the shutdown functions.
    FOR tap IN SELECT * FROM _runem(shutdown, false) LOOP RETURN NEXT tap; END LOOP;

    -- Finish up.
    FOR tap IN SELECT * FROM _finish( COALESCE(_get('curr_test'), 0), 0, tfaild ) LOOP
        RETURN NEXT tap;
    END LOOP;

    -- Clean up and return.
    PERFORM _cleanup();
    RETURN;
END;
$$ LANGUAGE plpgsql;

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


Question: pgTAP test for Policy (assertion 62).

SELECT * FROM check_test(
    policy_cmd_is( 'passwd', 'user_mod', 'all' ),
    false,
    'policy_cmd_is(table, policy, command) for UPDATE should fail',
    'Policy user_mod for table passwd should apply to ALL command',
    '        have: UPDATE
        want: ALL'
);

Explanation: SQL assertion from pgTAP test suite for Policy.


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

SELECT count(*) FROM numerictmp WHERE a >  -1890.0;

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


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

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

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


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

SELECT JSON_QUERY(jsonb '"[3,4]"', '$[*]' RETURNING bigint[] EMPTY OBJECT ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY(jsonb '"[3,4]"', '$[*]' RETURNING bigint[] EMPTY OBJECT ON ERROR)) AS _sub;


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

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

ex_context                      text;
ex_detail                       text;
ex_hint                         text;
ex_message                      text;
v_child_exists                  text;
v_child_tablename               text;
v_col                           text;
v_constraint_cols               text[];
v_constraint_col_type           text;
v_constraint_name               text;
v_constraint_values             record;
v_control                       text;
v_datetime_string               text;
v_existing_constraint_name      text;
v_job_id                        bigint;
v_jobmon                        boolean;
v_jobmon_schema                 text;
v_last_partition                text;
v_last_partition_id             bigint;
v_last_partition_timestamp      timestamp;
v_max_id                        bigint;
v_max_timestamp                 timestamp;
v_old_search_path               text;
v_optimize_constraint           int;
v_parent_schema                 text;
v_parent_table                  text;
v_parent_tablename              text;
v_partition_interval            text;
v_partition_suffix              text;
v_premake                       int;
v_sql                           text;
v_step_id                       bigint;
v_suffix_position               int;
v_type                          text;

BEGIN

SELECT parent_table
    , partition_type
    , control
    , premake
    , partition_interval
    , optimize_constraint
    , datetime_string
    , constraint_cols
    , jobmon
INTO v_parent_table
    , v_type
    , v_control
    , v_premake
    , v_partition_interval
    , v_optimize_constraint
    , v_datetime_string
    , v_constraint_cols
    , v_jobmon
FROM @extschema@.part_config
WHERE parent_table = p_parent_table
AND constraint_cols IS NOT NULL;

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

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

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

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN CREATE CONSTRAINT: %s', v_parent_table));
    ELSE
        v_job_id = p_job_id;
    END IF;
END IF;

-- If p_child_table is null, figure out the partition that is the one right before the optimize_constraint value backwards.
IF p_child_table IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, 'Applying additional constraints: Automatically determining most recent child on which to apply constraints');
    END IF;

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

    IF v_type IN ('time', 'time-custom') THEN
        SELECT child_start_time INTO v_last_partition_timestamp FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_partition_interval, v_parent_table);
        v_partition_suffix := to_char(v_last_partition_timestamp - (v_partition_interval::interval * (v_optimize_constraint + v_premake + 1) ), v_datetime_string);
    ELSIF v_type = 'id' THEN
        SELECT child_start_id INTO v_last_partition_id FROM @extschema@.show_partition_info(v_parent_schema||'.'||v_last_partition, v_partition_interval, v_parent_table);
        v_partition_suffix := (v_last_partition_id - (v_partition_interval::int * (v_optimize_constraint + v_premake + 1) ))::text;
    END IF;

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

    IF p_debug THEN
        RAISE NOTICE 'apply_constraint: v_parent_tablename: % , v_partition_suffix: %', v_parent_tablename, v_partition_suffix;
    END IF;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', format('Target child table: %s.%s', v_parent_schema, v_child_tablename));
    END IF;
ELSE
    v_child_tablename = split_part(p_child_table, '.', 2);
END IF;

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

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

FOREACH v_col IN ARRAY v_constraint_cols
LOOP
    SELECT con.conname
    INTO v_existing_constraint_name
    FROM pg_catalog.pg_constraint con
    JOIN pg_class c ON c.oid = con.conrelid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    JOIN pg_catalog.pg_attribute a ON con.conrelid = a.attrelid
    WHERE c.relname = v_child_tablename
        AND n.nspname = v_parent_schema
        AND con.conname LIKE 'partmanconstr_%'
        AND con.contype = 'c'
        AND a.attname = v_col
        AND ARRAY[a.attnum] OPERATOR(pg_catalog.<@) con.conkey
        AND a.attisdropped = false;

    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Applying additional constraints: Applying new constraint on column: %s', v_col));
    END IF;

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

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

    EXECUTE format('SELECT min(%I)::text AS min, max(%I)::text AS max FROM %I.%I', v_col, v_col, v_parent_schema, v_child_tablename) INTO v_constraint_values;

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

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

END LOOP;

IF p_analyze THEN
    IF v_jobmon_schema IS NOT NULL THEN
        v_step_id := add_step(v_job_id, format('Applying additional constraints: Running analyze on partition set: %s', v_parent_table));
    END IF;
    IF p_debug THEN
        RAISE NOTICE 'Running analyze on partition set: %', v_parent_table;
    END IF;

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

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

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

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

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


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

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

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


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

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


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

CREATE TABLE clstr_tst_inh () INHERITS (clstr_tst);

Explanation: DDL from PostgreSQL core regression test for Cluster.


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

SELECT 'ltree.awdfg'::ltree @ '!tree & aWdf@*'::ltxtquery;

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


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

SELECT xmlserialize(document 'bad' as text);

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

SELECT count(*) FROM (SELECT xmlserialize(document 'bad' as text)) AS _sub;


Question: pgTAP test for Hastap (assertion 204).

SELECT * FROM check_test(
  has_leftop( '+', 'int8' ),
  true,
  'has_leftop( name, right )',
  'Left operator +(NONE,int8) should exist',
  ''
);

Explanation: SQL assertion from pgTAP test suite for Hastap.


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

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

SELECT count(*) FROM (select 'null'::jsonb::bool) AS _sub;


Question: PostgreSQL Xfunc: show example 1.

Explanation: Example from PostgreSQL documentation on Xfunc.


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

SELECT * FROM test_int2 WHERE i<=32768::int4 ORDER BY i;

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


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

SELECT t1.c1, t2.c1 FROM ft1 t1 JOIN ft2 t2 ON (t1.c1 = t2.c1) ORDER BY t1.c3, t1.c1 OFFSET 100 LIMIT 10 FOR UPDATE;

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


Question: PL/pgSQL test: Plperl Trigger (example 4).

CREATE TABLE trigger_test_generated (
    i int,
    j int GENERATED ALWAYS AS (i * 2) STORED,
    k int GENERATED ALWAYS AS (i * 3) VIRTUAL
);

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


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

SELECT xmlelement(name foo, xmlattributes('<>&"''' as funny, xml 'b<a/>r' as funnier));

SELECT count(*) FROM (SELECT xmlelement(name foo, xmlattributes('<>&"''' as funny, xml 'b<a/>r' as funnier))) AS _sub;


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

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


Question: PostgreSQL regression test 'foreign_data': Write the SELECT query (example 243).

SELECT * FROM information_schema.user_mapping_options ORDER BY lower(authorization_identifier), 2, 3, 4;

Explanation: Regression test for Foreign Data in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT * FROM information_schema.user_mapping_options ORDER BY lower(authorization_identifier), 2, 3, 4) AS _sub;


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

CREATE OR REPLACE VIEW lock_view2 AS SELECT * from lock_view3;

Explanation: DDL from PostgreSQL core regression test for Lock.


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

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

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


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

-- Check that all combine functions have signature
-- combine(transtype, transtype) returns transtype

SELECT a.aggfnoid, p.proname
FROM pg_aggregate as a, pg_proc as p
WHERE a.aggcombinefn = p.oid AND
    (p.pronargs != 2 OR
     p.prorettype != p.proargtypes[0] OR
     p.prorettype != p.proargtypes[1] OR
     NOT binary_coercible(a.aggtranstype, p.proargtypes[0]));

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


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

CREATE TYPE box; CREATE FUNCTION my_box_in_function(cstring) RETURNS box AS ... ; CREATE FUNCTION my_box_out_function(box) RETURNS cstring AS ... ; CREATE TYPE box ( INTERNALLENGTH = 16, INPUT = my_box_in_function, OUTPUT = my_box_out_function ); CREATE TABLE myboxes ( id integer, description box );

Explanation: PostgreSQL CREATE TYPE command.


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

CREATE POLICY blog_1 ON blog USING (id % 2 = 0);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

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

SELECT count(*) FROM (select 1,2 into x, y) AS _sub;


Question: Write the DML statement from PostgreSQL regression test 'sequence' (example 35).

INSERT INTO serialTest2 (f1, f3)
  VALUES ('bogus', 32768);

Explanation: DML from PostgreSQL core regression test for Sequence.


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

SELECT citext_larger( 'ab'::citext, 'ac'::citext ) = 'ac' AS t;

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


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

select * from pg_input_error_info('[1,2147483647]', 'int4range');

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

SELECT count(*) FROM (select * from pg_input_error_info('[1,2147483647]', 'int4range')) AS _sub;


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

INSERT INTO itest5 OVERRIDING USER VALUE VALUES (DEFAULT, 'ddd'), (-4, 'eee');

Explanation: DML from PostgreSQL core regression test for Identity.


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

Explanation: DML from PostgreSQL core regression test for Update.


Question: pgTAP test for Resultset (assertion 432).

-- Now when the last row is missing.
SELECT * FROM check_test(
    results_ne(
        'SELECT id, name FROM annames WHERE name <> ''Antonio''',
        'nenames_ord'
    ),
    true,
    'results_ne(select, prepared) missing last row',
    '',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Resultset.


Question: PL/pgSQL test: Plpgsql Trap (example 35).

select trap_foreign_key_2();  -- detects FK violation
commit;				-- still fails

drop function trap_foreign_key(int);

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


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

SELECT regexp_matches('foobarbequebaz'::citext, '(BAR)(BEQUE)'::citext, ''::citext) = ARRAY[ 'bar', 'beque' ] AS t;


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

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


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

-- access to call stack from exception
create function inner_func(int)
returns int as $$
declare
  _context text;
  sx int := 5;
begin
  begin
    perform sx / 0;
  exception
    when division_by_zero then
      get diagnostics _context = pg_context;
      raise notice '***%***', _context;
  end;

  -- lets do it again, just for fun..
  get diagnostics _context = pg_context;
  raise notice '***%***', _context;
  raise notice 'lets make sure we didnt break anything';
  return 2 * $1;
end;
$$ language plpgsql;

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


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

INSERT INTO TIMESTAMPTZ_TBL VALUES ('Feb 16 17:32:01 1697');

Explanation: DML from PostgreSQL core regression test for Timestamptz.


Question: Write the DML statement from PostgreSQL regression test 'compression_lz4' (example 39).

INSERT INTO cmpart VALUES (repeat('123456789', 1004));

Explanation: DML from PostgreSQL core regression test for Compression Lz4.


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

Explanation: DML from PostgreSQL core regression test for Cluster.


Question: pgTAP test for Pktap (assertion 37).

SELECT * FROM check_test(
    col_isnt_pk( 'sometab', 'id' ),
    false,
    'col_isnt_pk( table, column )',
    'Column sometab(id) should not be a primary key',
    '        have: {id}
        want: anything else'
);

Explanation: SQL assertion from pgTAP test suite for Pktap.


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

-- Time can be represented in a hypertable as an int* (bigint/integer/smallint) or as a timestamp type (
-- with or without timezones). In metatables and other internal systems all time values are stored as bigint.
-- Converting from int* columns to internal representation is a cast to bigint.
-- Converting from timestamps to internal representation is conversion to epoch (in microseconds).

CREATE OR REPLACE FUNCTION _timescaledb_functions.interval_to_usec(
       chunk_interval INTERVAL
)
RETURNS BIGINT LANGUAGE SQL IMMUTABLE PARALLEL SAFE AS
$BODY$
    SELECT (int_sec * 1000000)::bigint from extract(epoch from chunk_interval) as int_sec;

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


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

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

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


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

SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a float4 EXISTS PATH '$.a'));

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

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"a"', '$' COLUMNS (a float4 EXISTS PATH '$.a'))) AS _sub;


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

Explanation: PostgreSQL DROP TSTEMPLATE command.


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

select count(*) from test_multirange_gist where mr = '{}'::int4multirange;

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

SELECT count(*) FROM (select count(*) from test_multirange_gist where mr = '{}'::int4multirange) AS _sub;


Question: PostgreSQL regression test 'largeobject': Write the SELECT query (example 108).

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

SELECT count(*) FROM (SELECT lo_import(:'filename')) AS _sub;


Question: pgTAP test for Index (assertion 27).

SELECT * FROM check_test(
    has_index( 'public', 'sometab', 'idx_baz'::name ),
    true,
    'has_index() no cols no desc',
    'Index idx_baz should exist',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Index.


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

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

SELECT count(*) FROM (select '0.0010'::jsonpath) AS _sub;


Question: Show an example of PostgreSQL ALTER ROLE (example 1).

ALTER ROLE davide WITH PASSWORD 'hu8jmn3';

Explanation: PostgreSQL ALTER ROLE command.


Question: Write the DDL statement from PostgreSQL regression test 'hash_part' (example 24).

create table text_hashp1 partition of text_hashp for values with (modulus 2, remainder 1);

Explanation: DDL from PostgreSQL core regression test for Hash Part.


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

-- proretset should only be set for normal functions
SELECT p1.oid, p1.proname
FROM pg_proc AS p1
WHERE proretset AND prokind != 'f';

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


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

SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing NULLS FIRST OFFSET 20000 - 4;

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

SELECT count(*) FROM (SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_decreasing NULLS FIRST OFFSET 20000 - 4) AS _sub;


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

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


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

SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text PATH '$' OMIT QUOTES ON SCALAR STRING));

SELECT count(*) FROM (SELECT * FROM JSON_TABLE(jsonb '"world"', '$' COLUMNS (item text PATH '$' OMIT QUOTES ON SCALAR STRING))) AS _sub;


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

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


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

create table insertconflicttest(key int4, fruit text);

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


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

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


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

CREATE TRIGGER view_insert INSTEAD OF INSERT ON my_view FOR EACH ROW EXECUTE FUNCTION view_insert_row();

Explanation: PostgreSQL CREATE TRIGGER command.


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

INSERT INTO TIMESTAMP_TBL VALUES ('Feb 10 17:32:01 1997');

Explanation: DML from PostgreSQL core regression test for Timestamp.


Question: pgTAP test for Throwtap (assertion 35).

/****************************************************************************/
-- Test ASSERTs
SELECT lives_ok(
    CASE WHEN pg_version_num() < 90500 THEN $exec$
CREATE FUNCTION check_assert(b boolean) RETURNS void LANGUAGE plpgsql AS $body$
BEGIN
    RAISE EXCEPTION 'this code should never be called!';

Explanation: SQL assertion from pgTAP test suite for Throwtap.


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

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


Question: Write the DDL statement from PostgreSQL regression test 'gist' (example 4).

create index gist_pointidx3 on gist_point_tbl using gist(p) with (buffering = off);

Explanation: DDL from PostgreSQL core regression test for Gist.


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

SELECT 'foo & bar'::tsquery || 'asd & fg';

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

SELECT count(*) FROM (SELECT 'foo & bar'::tsquery || 'asd & fg') AS _sub;


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

CREATE TABLE plt1_e_p2 PARTITION OF plt1_e FOR VALUES IN ('0001', '0005', '0002', '0009');

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


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

CREATE POLICY p2 ON x1 FOR INSERT WITH CHECK (a % 2 = 1);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


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

-- plain sort not triggering abbreviated abort
SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY noabort_increasing OFFSET 20000 - 4;

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


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

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

SELECT count(*) FROM (SELECT power(float8 '1', float8 'NaN')) AS _sub;


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

SELECT count(*) FROM (SELECT round(5e-16383, 16382) = 1e-16382) AS _sub;


Question: Show a query using PostgreSQL contrib extension 'pg_logicalinspect' (example 3).

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


Question: Show a SQL definition from the citus project (coordinator_evaluation, item 7).

CREATE TABLE coordinator_evaluation_table (key int, value int);

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


Question: Write the DDL statement from PostgreSQL regression test 'tid' (example 24).

CREATE VIEW tid_view_with_ctid AS SELECT ctid, a FROM tid_tab;

Explanation: DDL from PostgreSQL core regression test for Tid.


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

select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3');

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

SELECT count(*) FROM (select jsonb_path_query('{"a": [1, 2]}', 'lax $.a * 3')) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Arrays.


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

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

SELECT count(*) FROM (select interval 'PT2562047789') AS _sub;


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

SELECT nummultirange() &> nummultirange(numrange(1,2));

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

SELECT count(*) FROM (SELECT nummultirange() &> nummultirange(numrange(1,2))) AS _sub;


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

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

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


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

select v, v is null as "is null" from string_to_table('1,2,3,4,,6', ',', '') g(v);

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

SELECT count(*) FROM (select v, v is null as "is null" from string_to_table('1,2,3,4,,6', ',', '') g(v)) AS _sub;


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

select max(unique2) from tenk1 order by 1;

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

SELECT count(*) FROM (select max(unique2) from tenk1 order by 1) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'transactions' (example 54).

Explanation: DDL from PostgreSQL core regression test for Transactions.


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

SELECT count(*) FROM (select jsonb_path_query('"12:34"', '$.datetime("HH24:MI")')) AS _sub;


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

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

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


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

Explanation: DML from PostgreSQL core regression test for Rules.


Question: PostgreSQL regression test 'timetz': Write the SELECT query (example 19).

SELECT f1 AS "Seven" FROM TIMETZ_TBL WHERE f1 > '05:06:07-07';

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

SELECT count(*) FROM (SELECT f1 AS "Seven" FROM TIMETZ_TBL WHERE f1 > '05:06:07-07') AS _sub;


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

CREATE FUNCTION uuid_generate_v4()
RETURNS uuid
AS 'MODULE_PATHNAME', 'uuid_generate_v4'
VOLATILE STRICT LANGUAGE C PARALLEL SAFE;

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


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

SELECT * FROM test_table_record_as('obj', null, null, true);

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


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

SELECT qq, unique1
  FROM
  ( SELECT COALESCE(q1, 0) AS qq FROM int8_tbl a ) AS ss1
  FULL OUTER JOIN
  ( SELECT COALESCE(q2, -1) AS qq FROM int8_tbl b ) AS ss2
  USING (qq)
  INNER JOIN tenk1 c ON qq = unique2;

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

SELECT count(*) FROM (SELECT qq, unique1
  FROM
  ( SELECT COALESCE(q1, 0) AS qq FROM int8_tbl a ) AS ss1
  FULL OUTER JOIN
  ( SELECT COALESCE(q2, -1) AS qq FROM int8_tbl b ) AS ss2
  USING (qq)
  INNER JOIN tenk1 c ON qq = unique2) AS _sub;


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

UPDATE hash_i4_heap
   SET seqno = 20000
   WHERE hash_i4_heap.random = 1492795354;

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


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

SELECT '4714-11-24 BC'::date::timestamptz;  -- fail

SELECT '4714-11-24 BC'::date < '2020-10-05'::timestamptz as t;

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

SELECT count(*) FROM (SELECT '4714-11-24 BC'::date::timestamptz;  -- fail

SELECT '4714-11-24 BC'::date < '2020-10-05'::timestamptz as t) AS _sub;


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

INSERT INTO FLOAT8_TBL(f1) VALUES ('   -34.84');

Explanation: DML from PostgreSQL core regression test for Float8.


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

SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "dependency": 4, "degree": 1.000, "degree": 1.000}]', 'pg_dependencies');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('[{"attributes" : [2,3], "dependency": 4, "degree": 1.000, "degree": 1.000}]', 'pg_dependencies')) AS _sub;


Question: pgTAP test for Resultset (assertion 411).

INSERT INTO nord (id, name ) VALUES(183, 'Antonio');

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

select encode(decrypt(encrypt('Lets try a longer message.', '0123456789', 'aes-cfb'), '0123456789', 'aes-cfb'), 'escape');

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


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

SELECT master_create_empty_shard('lineitem') as lineitem_shardid1 \gset
SELECT master_create_empty_shard('lineitem') as lineitem_shardid2 \gset

CREATE TABLE orders (LIKE public.orders);

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


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

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


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

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

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


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

CREATE FUNCTION _int_contains_joinsel(internal, oid, internal, smallint, internal)
RETURNS float8
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT STABLE;


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

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

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


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

SELECT '23:59:59.9999999'::time;  -- rounds up
SELECT '23:59:60'::time;  -- rounds up
SELECT '24:00:00'::time;  -- allowed
SELECT '24:00:00.01'::time;  -- not allowed
SELECT '23:59:60.01'::time;  -- not allowed
SELECT '24:01:00'::time;  -- not allowed
SELECT '25:00:00'::time;  -- not allowed

-- Test non-error-throwing API
SELECT pg_input_is_valid('12:00:00', 'time');

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

SELECT count(*) FROM (SELECT '23:59:59.9999999'::time;  -- rounds up
SELECT '23:59:60'::time;  -- rounds up
SELECT '24:00:00'::time;  -- allowed
SELECT '24:00:00.01'::time;  -- not allowed
SELECT '23:59:60.01'::time;  -- not allowed
SELECT '24:01:00'::time;  -- not allowed
SELECT '25:00:00'::time;  -- not allowed

-- Test non-error-throwing API
SELECT pg_input_is_valid('12:00:00', 'time')) AS _sub;


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

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


Question: PostgreSQL Indices: show example 39.

SELECT * FROM test1c WHERE content > constant ;

Explanation: Example from PostgreSQL documentation on Indices.


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

-- behave reasonably if someone tries to modify a transition table
CREATE FUNCTION transition_table_level2_bad_usage_func()
  RETURNS TRIGGER
  LANGUAGE plpgsql
AS $$
  BEGIN
    INSERT INTO dx VALUES (1000000, 1000000, 'x');
    RETURN NULL;
  END;
$$;

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


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

--
-- bt_page_items_bytea()
--
CREATE FUNCTION bt_page_items(IN page bytea,
    OUT itemoffset smallint,
    OUT ctid tid,
    OUT itemlen smallint,
    OUT nulls bool,
    OUT vars bool,
    OUT data text)
RETURNS SETOF record
AS 'MODULE_PATHNAME', 'bt_page_items_bytea'
LANGUAGE C STRICT PARALLEL SAFE;

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


Question: pgTAP test for Policy (assertion 73).

SELECT * FROM check_test(
    policy_cmd_is( 'passwd', 'root_all', 'all', 'whatever' ),
    true,
    'policy_cmd_is(table, policy, command, desc) for ALL',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Policy.


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

CREATE TABLE beta_neg_p1 PARTITION OF beta_neg FOR VALUES FROM (100) TO (150);

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


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

SELECT * FROM multiout_record_as('obj', null, null, false);

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


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

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

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


Question: Show a SQL definition from the citus project (columnar_data_types, item 4).

-- Test array types
CREATE TABLE test_array_types (int_array int[], bigint_array bigint[],
	text_array text[]) USING columnar;


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

INSERT INTO PKTABLE VALUES (3, 6, 'Test3');

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


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

-- Create the operator class
CREATE OPERATOR CLASS gist_enum_ops
DEFAULT FOR TYPE anyenum USING gist
AS
	OPERATOR	1	<  ,
	OPERATOR	2	<= ,
	OPERATOR	3	=  ,
	OPERATOR	4	>= ,
	OPERATOR	5	>  ,
	FUNCTION	1	gbt_enum_consistent (internal, anyenum, int2, oid, internal),
	FUNCTION	2	gbt_enum_union (internal, internal),
	FUNCTION	3	gbt_enum_compress (internal),
	FUNCTION	4	gbt_decompress (internal),
	FUNCTION	5	gbt_enum_penalty (internal, internal, internal),
	FUNCTION	6	gbt_enum_picksplit (internal, internal),
	FUNCTION	7	gbt_enum_same (gbtreekey8, gbtreekey8, internal),
	STORAGE		gbtreekey8;


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

SELECT b.* FROM b LEFT JOIN a ON (b.a_id = a.id) WHERE (a.id IS NULL OR a.id > 0);

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

SELECT count(*) FROM (SELECT b.* FROM b LEFT JOIN a ON (b.a_id = a.id) WHERE (a.id IS NULL OR a.id > 0)) AS _sub;


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

CREATE TABLE temporal_rng2 (
  CONSTRAINT temporal_rng_pk PRIMARY KEY (id, valid_at WITHOUT OVERLAPS)
) INHERITS (temporal_rng);

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


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


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

SELECT 'a'::citext = 'A'::text AS f;        -- text wins the discussion
SELECT 'a'::citext = 'b'::citext AS f;

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


Question: Write the DDL statement from PostgreSQL regression test 'bit' (example 30).

CREATE TABLE varbit_table (a BIT VARYING(16), b BIT VARYING(16));

Explanation: DDL from PostgreSQL core regression test for Bit.


Question: PostgreSQL regression test 'alter_table': Write the SELECT query (example 648).

SELECT attinhcount, attislocal FROM pg_attribute WHERE attrelid = 'part_3_4'::regclass AND attnum > 0;

Explanation: Regression test for Alter Table in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT attinhcount, attislocal FROM pg_attribute WHERE attrelid = 'part_3_4'::regclass AND attnum > 0) AS _sub;


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

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

SELECT count(*) FROM (SELECT unistr('wrong: \U0000db99\U00000061')) AS _sub;


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

insert into rtest_view3 select * from rtest_vview1 where a < 7;

Explanation: DML from PostgreSQL core regression test for Rules.


Question: Write the DDL statement from PostgreSQL regression test 'drop_if_exists' (example 75).

CREATE OPERATOR @#@
        (leftarg = int8, rightarg = int8, procedure = int8xor);

Explanation: DDL from PostgreSQL core regression test for Drop If Exists.


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

SELECT * FROM test_squash WHERE id IN (1, 2, 3);

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


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

SELECT * FROM sales_central WHERE sales_state = 'Warsaw';

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

SELECT count(*) FROM (SELECT * FROM sales_central WHERE sales_state = 'Warsaw') AS _sub;


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

CREATE TABLE prt (a int) PARTITION BY RANGE(a);

Explanation: DDL from PostgreSQL core regression test for Memoize.


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

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


Question: PostgreSQL Plpgsql: show example 23.

Explanation: Example from PostgreSQL documentation on Plpgsql.


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

SELECT unique1, unique2 FROM onek_with_null
  ORDER BY unique2 DESC LIMIT 5;

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

SELECT count(*) FROM (SELECT unique1, unique2 FROM onek_with_null
  ORDER BY unique2 DESC LIMIT 5) AS _sub;


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

CREATE SEQUENCE sequence_test9 AS integer INCREMENT BY -1;

Explanation: DDL from PostgreSQL core regression test for Sequence.


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

ALTER EXTENSION pgtap ADD FUNCTION fail ( text );

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


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

select pg_typeof(array['11 22 33'::oidvector]);

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

SELECT count(*) FROM (select pg_typeof(array['11 22 33'::oidvector])) AS _sub;


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

INSERT INTO vac_truncate_test VALUES (1, NULL), (NULL, NULL);

Explanation: DML from PostgreSQL core regression test for Vacuum.


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

CREATE POLICY p3 ON rls_part USING (a < 0);

Explanation: DDL from PostgreSQL core regression test for Rowsecurity.


Question: PostgreSQL Ddl: show example 53.

ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;

Explanation: Example from PostgreSQL documentation on Ddl.


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

INSERT INTO caster (text)          VALUES ('((0,0),2)'::circle);

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


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

Explanation: DML from PostgreSQL core regression test for Transactions.


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

SELECT JSON_SERIALIZE('{ "a" : 1 } ' RETURNING varchar);

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

SELECT count(*) FROM (SELECT JSON_SERIALIZE('{ "a" : 1 } ' RETURNING varchar)) AS _sub;


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


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

-- check that function dropped in a subtransaction leaves no stats behind
BEGIN;

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


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

SELECT * FROM pg_input_error_info('[{"attributes" : [2,2], "dependency" : 4, "degree": 0.500}]', 'pg_dependencies');

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

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


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

SELECT ft5, ft5.c1, ft5.c2, ft5.c3, ft4.c1, ft4.c2 FROM ft5 left join ft4 on ft5.c1 = ft4.c1 WHERE ft4.c1 BETWEEN 10 and 30 ORDER BY ft5.c1, ft4.c1;

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


Question: Write the DML statement from PostgreSQL regression test 'spgist' (example 7).

insert into spgist_point_tbl (id, p)
select g+100000, point(g*10+1, g*10+1) from generate_series(1, 10000) g;

Explanation: DML from PostgreSQL core regression test for Spgist.


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

select '"a"'::jsonb #- '{a}'; -- error
select '{}'::jsonb #- '{a}';

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

SELECT count(*) FROM (select '"a"'::jsonb #- '{a}'; -- error
select '{}'::jsonb #- '{a}') AS _sub;


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

ALTER EXTENSION pgtap ADD FUNCTION roles_are( NAME[] );


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

}
spi_exec {select replaceme('foe') as inner}
return "fee $1 $inner"
$p$ language pltcl;

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


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

SELECT * FROM part_document_satire ORDER by did;

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

SELECT count(*) FROM (SELECT * FROM part_document_satire ORDER by did) AS _sub;


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

CREATE FUNCTION seg_upper(seg)
RETURNS float4
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

Explanation: DML from PostgreSQL core regression test for Domain.


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

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

SELECT count(*) FROM (SELECT regclass('pg_catalog.pg_class')) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'insert' (example 121).

create table part_xx_yy partition of list_parted for values in ('xx', 'yy') partition by list (a);

Explanation: DDL from PostgreSQL core regression test for Insert.


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

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: PostgreSQL regression test 'multirangetypes': Write the SELECT query (example 115).

SELECT * FROM nummultirange_test WHERE multirange_contains_range(nmr, numrange(4.0, 4.2));

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

SELECT count(*) FROM (SELECT * FROM nummultirange_test WHERE multirange_contains_range(nmr, numrange(4.0, 4.2))) AS _sub;


Question: PostgreSQL regression test 'partition_merge': Write the SELECT query (example 227).

SELECT tablename, indexname, tablespace FROM pg_indexes
  WHERE tablename IN ('t', 'tp_0_2') AND schemaname = 'partitions_merge_schema'
  ORDER BY tablename COLLATE "C", indexname COLLATE "C", tablespace COLLATE "C";

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

SELECT count(*) FROM (SELECT tablename, indexname, tablespace FROM pg_indexes
  WHERE tablename IN ('t', 'tp_0_2') AND schemaname = 'partitions_merge_schema'
  ORDER BY tablename COLLATE "C", indexname COLLATE "C", tablespace COLLATE "C") AS _sub;


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

SELECT * FROM test_type_conversion_int4(null);

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


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

create table minmaxtest2() inherits (minmaxtest);

Explanation: DDL from PostgreSQL core regression test for Aggregates.


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

CREATE TYPE gbtreekey_var (
	INTERNALLENGTH = VARIABLE,
	INPUT  = gbtreekey_var_in,
	OUTPUT = gbtreekey_var_out,
	STORAGE = EXTENDED
);


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

select * from inttest where a not in (1::myint,2::myint,3::myint,4::myint,5::myint, null);

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

SELECT count(*) FROM (select * from inttest where a not in (1::myint,2::myint,3::myint,4::myint,5::myint, null)) AS _sub;


Question: Write the DDL statement from PostgreSQL regression test 'collate' (example 101).

CREATE TABLE collate_test23 (f1 text collate mycoll2);

Explanation: DDL from PostgreSQL core regression test for Collate.


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

CREATE VIEW lock_view4 AS SELECT (select a from lock_tbl1a limit 1) from lock_tbl1;

Explanation: DDL from PostgreSQL core regression test for Lock.


Question: Show a SQL definition from the citus project (citus_local_table_triggers, item 37).

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


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

Explanation: DML from PostgreSQL core regression test for Numeric.


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

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

SELECT count(*) FROM (select jsonb_path_match('[[1, true], [2, false]]', 'strict $[*] ? (@[0] < $x) [1]', '{"x": 2}')) AS _sub;


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

select ts_headline('{}'::jsonb, tsquery('aaa & bbb'));

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

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


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

-- 3-) Attaching non distributed table to a distributed table
CREATE TABLE partitioning_test_2012(id int, time date);


Question: pgTAP test for Coltap (assertion 24).

SELECT * FROM check_test(
    col_type_is( 'public', 'sometab', 'ctstz', 'pg_catalog'::name, 'timestamptz' ),
    true,
    'col_type_is( sch, tab, col, sch, type, desc )',
    'Column public.sometab.ctstz should be type pg_catalog.timestamptz',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Coltap.


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

CREATE TABLE ATACC1 (a int, NOT NULL a NO INHERIT) PARTITION BY LIST (a);

Explanation: DDL from PostgreSQL core regression test for Constraints.


Question: Write the DDL statement from PostgreSQL regression test 'copy2' (example 193).

Explanation: DDL from PostgreSQL core regression test for Copy2.


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

SELECT JSON_VALUE(jsonb '1234', '$' RETURNING queryfuncs_d_varbit3  DEFAULT '111111' ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_VALUE(jsonb '1234', '$' RETURNING queryfuncs_d_varbit3  DEFAULT '111111' ON ERROR)) AS _sub;


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

SELECT * FROM test_int2 WHERE i>1::int8 ORDER BY i;

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


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

INSERT INTO origin_tbl(data) VALUES ('no_lsn, commit');

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


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

INSERT INTO plt2_adv SELECT i, i, to_char(i % 10, 'FM0000') FROM generate_series(1, 299) i WHERE i % 10 IN (7, 9);

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


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

INSERT INTO bttest_multi SELECT i, i%2  FROM generate_series(1, 100000) as i;

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


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

-- gist key
CREATE FUNCTION gtrgm_in(cstring)
RETURNS gtrgm
AS 'MODULE_PATHNAME'
LANGUAGE C STRICT IMMUTABLE PARALLEL SAFE;

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


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

SELECT * FROM pg_input_error_info('6874898-01-01', 'date');

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

SELECT count(*) FROM (SELECT * FROM pg_input_error_info('6874898-01-01', 'date')) AS _sub;


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

INSERT INTO func_index_heap VALUES('AB','CDEFG');

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


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

$$ LANGUAGE plpgsql;

\set ON_ERROR_ROLLBACK on
\echo '# ON_ERROR_ROLLBACK:' :ON_ERROR_ROLLBACK
\echo '# AUTOCOMMIT:' :AUTOCOMMIT

BEGIN;
CREATE TABLE bla(s NO_SUCH_TYPE);               -- fails
CREATE TABLE bla(s TEXT);                       -- succeeds
SELECT psql_error('oops!');                     -- fails
INSERT INTO bla VALUES ('Calvin'), ('Hobbes');
COMMIT;

SELECT * FROM bla ORDER BY 1;

BEGIN;
INSERT INTO bla VALUES ('Susie');         -- succeeds
-- now with combined queries
INSERT INTO bla VALUES ('Rosalyn') \;     -- will rollback
SELECT 'before error' AS show \;          -- will show nevertheless!
  SELECT psql_error('boum!') \;           -- failure
  SELECT 'after error' AS noshow;         -- hidden by preceding error
INSERT INTO bla(s) VALUES ('Moe') \;      -- will rollback
  SELECT psql_error('bam!');
INSERT INTO bla VALUES ('Miss Wormwood'); -- succeeds
COMMIT;
SELECT * FROM bla ORDER BY 1;

-- some with autocommit off
\set AUTOCOMMIT off
\echo '# AUTOCOMMIT:' :AUTOCOMMIT

-- implicit BEGIN
INSERT INTO bla VALUES ('Dad');           -- succeeds
SELECT psql_error('bad!');                -- implicit partial rollback

INSERT INTO bla VALUES ('Mum') \;         -- will rollback
SELECT COUNT(*) AS "#mum"
FROM bla WHERE s = 'Mum' \;               -- but be counted here
SELECT psql_error('bad!');                -- implicit partial rollback
COMMIT;

SELECT COUNT(*) AS "#mum"
FROM bla WHERE s = 'Mum' \;               -- no mum here
SELECT * FROM bla ORDER BY 1;
COMMIT;

-- reset all
\set AUTOCOMMIT on
\set ON_ERROR_ROLLBACK off
\echo '# final ON_ERROR_ROLLBACK:' :ON_ERROR_ROLLBACK
DROP TABLE bla;
DROP FUNCTION psql_error;

-- check describing invalid multipart names
\dA regression.heap
\dA nonesuch.heap
\dt host.regression.pg_catalog.pg_class
\dt |.pg_catalog.pg_class
\dt nonesuch.pg_catalog.pg_class
\da host.regression.pg_catalog.sum
\da +.pg_catalog.sum
\da nonesuch.pg_catalog.sum
\dAc nonesuch.brin
\dAc regression.brin
\dAf nonesuch.brin
\dAf regression.brin
\dAo nonesuch.brin
\dAo regression.brin
\dAp nonesuch.brin
\dAp regression.brin
\db nonesuch.pg_default
\db regression.pg_default
\dc host.regression.public.conversion
\dc (.public.conversion
\dc nonesuch.public.conversion
\dC host.regression.pg_catalog.int8
\dC ).pg_catalog.int8
\dC nonesuch.pg_catalog.int8
\dd host.regression.pg_catalog.pg_class
\dd [.pg_catalog.pg_class
\dd nonesuch.pg_catalog.pg_class
\dD host.regression.public.gtestdomain1
\dD ].public.gtestdomain1
\dD nonesuch.public.gtestdomain1
\ddp host.regression.pg_catalog.pg_class
\ddp {.pg_catalog.pg_class
\ddp nonesuch.pg_catalog.pg_class
\dE host.regression.public.ft
\dE }.public.ft
\dE nonesuch.public.ft
\di host.regression.public.tenk1_hundred
\di ..public.tenk1_hundred
\di nonesuch.public.tenk1_hundred
\dm host.regression.public.mvtest_bb
\dm ^.public.mvtest_bb
\dm nonesuch.public.mvtest_bb
\ds host.regression.public.check_seq
\ds regression|mydb.public.check_seq
\ds nonesuch.public.check_seq
\dt host.regression.public.b_star
\dt regres+ion.public.b_star
\dt nonesuch.public.b_star
\dv host.regression.public.shoe
\dv regress(ion).public.shoe
\dv nonesuch.public.shoe
\des nonesuch.server
\des regression.server
\des nonesuch.server
\des regression.server
\des nonesuch.username
\des regression.username
\dew nonesuch.fdw
\dew regression.fdw
\df host.regression.public.namelen
\df regres[qrstuv]ion.public.namelen
\df nonesuch.public.namelen
\dF host.regression.pg_catalog.arabic
\dF regres{1,2}ion.pg_catalog.arabic
\dF nonesuch.pg_catalog.arabic
\dFd host.regression.pg_catalog.arabic_stem
\dFd regres?ion.pg_catalog.arabic_stem
\dFd nonesuch.pg_catalog.arabic_stem
\dFp host.regression.pg_catalog.default
\dFp ^regression.pg_catalog.default
\dFp nonesuch.pg_catalog.default
\dFt host.regression.pg_catalog.ispell
\dFt regression$.pg_catalog.ispell
\dFt nonesuch.pg_catalog.ispell
\dg nonesuch.pg_database_owner
\dg regression.pg_database_owner
\dL host.regression.plpgsql
\dL *.plpgsql
\dL nonesuch.plpgsql
\dn host.regression.public
\dn """".public
\dn nonesuch.public
\do host.regression.public.!=-
\do "regression|mydb".public.!=-
\do nonesuch.public.!=-
\dO host.regression.pg_catalog.POSIX
\dO .pg_catalog.POSIX
\dO nonesuch.pg_catalog.POSIX
\dp host.regression.public.a_star
\dp "regres+ion".public.a_star
\dp nonesuch.public.a_star
\dP host.regression.public.mlparted
\dP "regres(sion)".public.mlparted
\dP nonesuch.public.mlparted
\drds nonesuch.lc_messages
\drds regression.lc_messages
\dRp public.mypub
\dRp regression.mypub
\dRs public.mysub
\dRs regression.mysub
\dT host.regression.public.widget
\dT "regression{1,2}".public.widget
\dT nonesuch.public.widget
\dx regression.plpgsql
\dx nonesuch.plpgsql
\dX host.regression.public.func_deps_stat
\dX "^regression$".public.func_deps_stat
\dX nonesuch.public.func_deps_stat
\dy regression.myevt
\dy nonesuch.myevt

-- check that dots within quoted name segments are not counted
\dA "no.such.access.method"
\dt "no.such.table.relation"
\da "no.such.aggregate.function"
\dAc "no.such.operator.class"
\dAf "no.such.operator.family"
\dAo "no.such.operator.of.operator.family"
\dAp "no.such.operator.support.function.of.operator.family"
\db "no.such.tablespace"
\dc "no.such.conversion"
\dC "no.such.cast"
\dd "no.such.object.description"
\dD "no.such.domain"
\ddp "no.such.default.access.privilege"
\di "no.such.index.relation"
\dm "no.such.materialized.view"
\ds "no.such.relation"
\dt "no.such.relation"
\dv "no.such.relation"
\des "no.such.foreign.server"
\dew "no.such.foreign.data.wrapper"
\df "no.such.function"
\dF "no.such.text.search.configuration"
\dFd "no.such.text.search.dictionary"
\dFp "no.such.text.search.parser"
\dFt "no.such.text.search.template"
\dg "no.such.role"
\dL "no.such.language"
\dn "no.such.schema"
\do "no.such.operator"
\dO "no.such.collation"
\dp "no.such.access.privilege"
\dP "no.such.partitioned.relation"
\drds "no.such.setting"
\dRp "no.such.publication"
\dRs "no.such.subscription"
\dT "no.such.data.type"
\dx "no.such.installed.extension"
\dX "no.such.extended.statistics"
\dy "no.such.event.trigger"

-- again, but with dotted schema qualifications.
\dA "no.such.schema"."no.such.access.method"
\dt "no.such.schema"."no.such.table.relation"
\da "no.such.schema"."no.such.aggregate.function"
\dAc "no.such.schema"."no.such.operator.class"
\dAf "no.such.schema"."no.such.operator.family"
\dAo "no.such.schema"."no.such.operator.of.operator.family"
\dAp "no.such.schema"."no.such.operator.support.function.of.operator.family"
\db "no.such.schema"."no.such.tablespace"
\dc "no.such.schema"."no.such.conversion"
\dC "no.such.schema"."no.such.cast"
\dd "no.such.schema"."no.such.object.description"
\dD "no.such.schema"."no.such.domain"
\ddp "no.such.schema"."no.such.default.access.privilege"
\di "no.such.schema"."no.such.index.relation"
\dm "no.such.schema"."no.such.materialized.view"
\ds "no.such.schema"."no.such.relation"
\dt "no.such.schema"."no.such.relation"
\dv "no.such.schema"."no.such.relation"
\des "no.such.schema"."no.such.foreign.server"
\dew "no.such.schema"."no.such.foreign.data.wrapper"
\df "no.such.schema"."no.such.function"
\dF "no.such.schema"."no.such.text.search.configuration"
\dFd "no.such.schema"."no.such.text.search.dictionary"
\dFp "no.such.schema"."no.such.text.search.parser"
\dFt "no.such.schema"."no.such.text.search.template"
\dg "no.such.schema"."no.such.role"
\dL "no.such.schema"."no.such.language"
\do "no.such.schema"."no.such.operator"
\dO "no.such.schema"."no.such.collation"
\dp "no.such.schema"."no.such.access.privilege"
\dP "no.such.schema"."no.such.partitioned.relation"
\drds "no.such.schema"."no.such.setting"
\dRp "no.such.schema"."no.such.publication"
\dRs "no.such.schema"."no.such.subscription"
\dT "no.such.schema"."no.such.data.type"
\dx "no.such.schema"."no.such.installed.extension"
\dX "no.such.schema"."no.such.extended.statistics"
\dy "no.such.schema"."no.such.event.trigger"

-- again, but with current database and dotted schema qualifications.
\dt regression."no.such.schema"."no.such.table.relation"
\da regression."no.such.schema"."no.such.aggregate.function"
\dc regression."no.such.schema"."no.such.conversion"
\dC regression."no.such.schema"."no.such.cast"
\dd regression."no.such.schema"."no.such.object.description"
\dD regression."no.such.schema"."no.such.domain"
\di regression."no.such.schema"."no.such.index.relation"
\dm regression."no.such.schema"."no.such.materialized.view"
\ds regression."no.such.schema"."no.such.relation"
\dt regression."no.such.schema"."no.such.relation"
\dv regression."no.such.schema"."no.such.relation"
\df regression."no.such.schema"."no.such.function"
\dF regression."no.such.schema"."no.such.text.search.configuration"
\dFd regression."no.such.schema"."no.such.text.search.dictionary"
\dFp regression."no.such.schema"."no.such.text.search.parser"
\dFt regression."no.such.schema"."no.such.text.search.template"
\do regression."no.such.schema"."no.such.operator"
\dO regression."no.such.schema"."no.such.collation"
\dp regression."no.such.schema"."no.such.access.privilege"
\dP regression."no.such.schema"."no.such.partitioned.relation"
\dT regression."no.such.schema"."no.such.data.type"
\dX regression."no.such.schema"."no.such.extended.statistics"

-- again, but with dotted database and dotted schema qualifications.
\dt "no.such.database"."no.such.schema"."no.such.table.relation"
\da "no.such.database"."no.such.schema"."no.such.aggregate.function"
\dc "no.such.database"."no.such.schema"."no.such.conversion"
\dC "no.such.database"."no.such.schema"."no.such.cast"
\dd "no.such.database"."no.such.schema"."no.such.object.description"
\dD "no.such.database"."no.such.schema"."no.such.domain"
\ddp "no.such.database"."no.such.schema"."no.such.default.access.privilege"
\di "no.such.database"."no.such.schema"."no.such.index.relation"
\dm "no.such.database"."no.such.schema"."no.such.materialized.view"
\ds "no.such.database"."no.such.schema"."no.such.relation"
\dt "no.such.database"."no.such.schema"."no.such.relation"
\dv "no.such.database"."no.such.schema"."no.such.relation"
\df "no.such.database"."no.such.schema"."no.such.function"
\dF "no.such.database"."no.such.schema"."no.such.text.search.configuration"
\dFd "no.such.database"."no.such.schema"."no.such.text.search.dictionary"
\dFp "no.such.database"."no.such.schema"."no.such.text.search.parser"
\dFt "no.such.database"."no.such.schema"."no.such.text.search.template"
\do "no.such.database"."no.such.schema"."no.such.operator"
\dO "no.such.database"."no.such.schema"."no.such.collation"
\dp "no.such.database"."no.such.schema"."no.such.access.privilege"
\dP "no.such.database"."no.such.schema"."no.such.partitioned.relation"
\dT "no.such.database"."no.such.schema"."no.such.data.type"
\dX "no.such.database"."no.such.schema"."no.such.extended.statistics"

-- check \drg and \du
CREATE ROLE regress_du_role0;
CREATE ROLE regress_du_role1;
CREATE ROLE regress_du_role2;
CREATE ROLE regress_du_admin;

GRANT regress_du_role0 TO regress_du_admin WITH ADMIN TRUE;
GRANT regress_du_role1 TO regress_du_admin WITH ADMIN TRUE;
GRANT regress_du_role2 TO regress_du_admin WITH ADMIN TRUE;

GRANT regress_du_role0 TO regress_du_role1 WITH ADMIN TRUE,  INHERIT TRUE,  SET TRUE  GRANTED BY regress_du_admin;
GRANT regress_du_role0 TO regress_du_role2 WITH ADMIN TRUE,  INHERIT FALSE, SET FALSE GRANTED BY regress_du_admin;
GRANT regress_du_role1 TO regress_du_role2 WITH ADMIN TRUE , INHERIT FALSE, SET TRUE  GRANTED BY regress_du_admin;
GRANT regress_du_role0 TO regress_du_role1 WITH ADMIN FALSE, INHERIT TRUE,  SET FALSE GRANTED BY regress_du_role1;
GRANT regress_du_role0 TO regress_du_role2 WITH ADMIN FALSE, INHERIT TRUE , SET TRUE  GRANTED BY regress_du_role1;
GRANT regress_du_role0 TO regress_du_role1 WITH ADMIN FALSE, INHERIT FALSE, SET TRUE  GRANTED BY regress_du_role2;
GRANT regress_du_role0 TO regress_du_role2 WITH ADMIN FALSE, INHERIT FALSE, SET FALSE GRANTED BY regress_du_role2;

\drg regress_du_role*
\du regress_du_role*

DROP ROLE regress_du_role0;
DROP ROLE regress_du_role1;
DROP ROLE regress_du_role2;
DROP ROLE regress_du_admin;

-- Test display of empty privileges.
BEGIN;
-- Create an owner for tested objects because output contains owner name.
CREATE ROLE regress_zeropriv_owner;
SET LOCAL ROLE regress_zeropriv_owner;

CREATE DOMAIN regress_zeropriv_domain AS int;
REVOKE ALL ON DOMAIN regress_zeropriv_domain FROM CURRENT_USER, PUBLIC;
\dD+ regress_zeropriv_domain

CREATE PROCEDURE regress_zeropriv_proc() LANGUAGE sql AS '';
REVOKE ALL ON PROCEDURE regress_zeropriv_proc() FROM CURRENT_USER, PUBLIC;
\df+ regress_zeropriv_proc

CREATE TABLE regress_zeropriv_tbl (a int);
REVOKE ALL ON TABLE regress_zeropriv_tbl FROM CURRENT_USER;
\dp regress_zeropriv_tbl

CREATE TYPE regress_zeropriv_type AS (a int);
REVOKE ALL ON TYPE regress_zeropriv_type FROM CURRENT_USER, PUBLIC;
\dT+ regress_zeropriv_type

ROLLBACK;

-- Test display of default privileges with \pset null.
CREATE TABLE defprivs (a int);
\pset null '(default)'
\z defprivs
\zx defprivs
\pset null ''
DROP TABLE defprivs;

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


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

SELECT to_char(d1, 'YYYY A.D. YYYY a.d. YYYY bc HH:MI:SS P.M. HH:MI:SS p.m. HH:MI:SS pm')
   FROM TIMESTAMPTZ_TBL;

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

SELECT count(*) FROM (SELECT to_char(d1, 'YYYY A.D. YYYY a.d. YYYY bc HH:MI:SS P.M. HH:MI:SS p.m. HH:MI:SS pm')
   FROM TIMESTAMPTZ_TBL) AS _sub;


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

$$;

delete from parent where aid = 1;
select * from parent; select * from child;

drop table parent, child;

drop function parent_upd_func();
drop function parent_del_func();
drop function child_ins_func();
drop function child_del_func();

-- similar case, but with a self-referencing FK so that parent and child
-- rows can be affected by a single operation

create temp table self_ref_trigger (
    id int primary key,
    parent int references self_ref_trigger,
    data text,
    nchildren int not null default 0
);

create function self_ref_trigger_ins_func()
  returns trigger language plpgsql as
$$
begin
  if new.parent is not null then
    update self_ref_trigger set nchildren = nchildren + 1
      where id = new.parent;

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


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

-- these are obsolete/deprecated:
CREATE OPERATOR @ (
	LEFTARG = cube, RIGHTARG = cube, PROCEDURE = cube_contains,
	COMMUTATOR = '~',
	RESTRICT = contsel, JOIN = contjoinsel
);


Question: Write the DDL statement from PostgreSQL regression test 'brin' (example 84).

CREATE INDEX brin_test_toast_idx ON brintest_3 USING brin (b, c);

Explanation: DDL from PostgreSQL core regression test for Brin.


Question: pgTAP test for Functap (assertion 80).

SELECT * FROM check_test(
    function_lang_is( 'someproc', 'sql', 'whatever' ),
    true,
    'function_lang_is(schema, proc, desc)',
    'whatever',
    ''
);

Explanation: SQL assertion from pgTAP test suite for Functap.


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

INSERT INTO prt1 SELECT i, i % 25, to_char(i, 'FM0000') FROM generate_series(0, 599) i WHERE i % 2 = 0;


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

ALTER EXTENSION pgtap ADD FUNCTION diag( VARIADIC text[] );

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


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

create domain dependenttypetest domaindroptest;

Explanation: DDL from PostgreSQL core regression test for Domain.


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

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


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

CREATE TABLE ptif_test2 PARTITION OF ptif_test
  FOR VALUES FROM (100) TO (200);

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


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

create temporary view vw_ord as select * from (values (1)) v(n) join rows from(rngfunct(1),rngfunct(2)) with ordinality as z(a,b,c,d,ord) on (n=ord);

Explanation: DDL from PostgreSQL core regression test for Rangefuncs.


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

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


Question: pgTAP test for Aretap (assertion 129).

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

Explanation: SQL assertion from pgTAP test suite for Aretap.


Question: Write the DML statement from PostgreSQL regression test 'matview' (example 82).

Explanation: DML from PostgreSQL core regression test for Matview.


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

INSERT INTO INET_TBL (c, i) VALUES ('10', '9.1.2.3/8');

Explanation: DML from PostgreSQL core regression test for Inet.


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

Explanation: DML from PostgreSQL core regression test for Rules.


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

update domnotnull set col1 = null;		-- fails
select conname, pg_get_constraintdef(oid) from pg_constraint
 where contypid = 'dnotnulltest'::regtype;

Explanation: DML from PostgreSQL core regression test for Domain.


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

SELECT i.* FROM INT2_TBL i WHERE i.f1 <= int2 '0';

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

SELECT count(*) FROM (SELECT i.* FROM INT2_TBL i WHERE i.f1 <= int2 '0') AS _sub;


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

CREATE TRIGGER users_update_trig BEFORE UPDATE ON users FOR EACH ROW
	EXECUTE PROCEDURE users_update ('willem');

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


Question: PostgreSQL regression test 'foreign_data': Write the SELECT query (example 268).

SELECT has_server_privilege(
    (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), 's8', 'USAGE');

Explanation: Regression test for Foreign Data in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT has_server_privilege(
    (SELECT oid FROM pg_roles WHERE rolname='regress_test_role'), 's8', 'USAGE')) AS _sub;


Question: PostgreSQL regression test 'inet': Write the SELECT query (example 63).

SELECT * FROM inet_tbl WHERE i >= '192.168.1.0/24'::cidr ORDER BY i;

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

SELECT count(*) FROM (SELECT * FROM inet_tbl WHERE i >= '192.168.1.0/24'::cidr ORDER BY i) AS _sub;


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

CREATE OR REPLACE FUNCTION identity_returner(x anyelement)
RETURNS anyelement
AS $$
BEGIN
	RETURN x;
END;
$$ language plpgsql;

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


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

SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, rolpassword, rolvaliduntil FROM pg_authid WHERE rolname = 'regress_test_user_canlogin';

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

SELECT count(*) FROM (SELECT rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb, rolcanlogin, rolreplication, rolbypassrls, rolconnlimit, rolpassword, rolvaliduntil FROM pg_authid WHERE rolname = 'regress_test_user_canlogin') AS _sub;


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

INSERT INTO caster (uuid)          VALUES ('a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11'::citext);

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


Question: pgTAP test for Resultset (assertion 182).

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

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

SELECT * FROM test_date WHERE i<'2004-10-26'::date ORDER BY i;

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


Question: PostgreSQL Indices: show example 1.

CREATE TABLE test1 ( id integer, content varchar );

Explanation: Example from PostgreSQL documentation on Indices.


Question: Show a SQL definition from the pg_partman project (pg_partman--4.6.1--4.6.2, item 12).

CREATE OR REPLACE FUNCTION @extschema@.apply_foreign_keys(p_parent_table text, p_child_table text, p_job_id bigint DEFAULT NULL, p_debug boolean DEFAULT false) RETURNS void
    LANGUAGE plpgsql
    AS $$
DECLARE

ex_context          text;
ex_detail           text;
ex_hint             text;
ex_message          text;
v_count             int := 0;
v_job_id            bigint;
v_jobmon            text;
v_jobmon_schema     text;
v_new_search_path   text;
v_old_search_path   text;
v_parent_schema     text;
v_parent_tablename  text;
v_ref_schema        text;
v_ref_table         text;
v_relkind           char;
v_row               record;
v_schemaname        text;
v_sql               text;
v_step_id           bigint;
v_tablename         text;

BEGIN
/*
 * Apply foreign keys that exist on the given parent to the given child table
 */

SELECT jobmon INTO v_jobmon FROM @extschema@.part_config WHERE parent_table = p_parent_table;

IF v_jobmon THEN
    SELECT nspname INTO v_jobmon_schema FROM pg_catalog.pg_namespace n, pg_catalog.pg_extension e WHERE e.extname = 'pg_jobmon' AND e.extnamespace = n.oid;
    IF v_jobmon_schema IS NOT NULL THEN
        SELECT current_setting('search_path') INTO v_old_search_path;
        IF length(v_old_search_path) > 0 THEN
           v_new_search_path := '@extschema@,pg_temp,'||v_old_search_path;
        ELSE
            v_new_search_path := '@extschema@,pg_temp';
        END IF;
        v_new_search_path := format('%s,%s',v_jobmon_schema, v_new_search_path);
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_new_search_path, 'false');
    END IF;
END IF;

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;

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

IF v_jobmon_schema IS NOT NULL THEN
    IF p_job_id IS NULL THEN
        v_job_id := add_job(format('PARTMAN APPLYING FOREIGN KEYS: %s', p_parent_table));
    ELSE -- Don't create a new job, add steps into given job
        v_job_id := p_job_id;
    END IF;
END IF;

IF v_jobmon_schema IS NOT NULL THEN
    v_step_id := add_step(v_job_id, format('Applying foreign keys to %s if they exist on parent', p_child_table));
END IF;

IF v_tablename IS NULL THEN
    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'CRITICAL', format('Target child table (%s) does not exist.', p_child_table));
        PERFORM fail_job(v_job_id);
        EXECUTE format('SELECT set_config(%L, %L, %L)', 'search_path', v_old_search_path, 'false');
    END IF;
    RAISE EXCEPTION 'Target child table (%) does not exist.', p_child_table;
    RETURN;
END IF;

FOR v_row IN
    SELECT pg_get_constraintdef(con.oid) AS constraint_def
    FROM pg_catalog.pg_constraint con
    JOIN pg_catalog.pg_class c ON con.conrelid = c.oid
    JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid
    WHERE c.relname = v_parent_tablename
    AND n.nspname = v_parent_schema
    AND contype = 'f'
LOOP
    v_sql := format('ALTER TABLE %I.%I ADD %s'
                    , v_schemaname
                    , v_tablename
                    , v_row.constraint_def);

    IF p_debug THEN
        RAISE NOTICE 'Constraint creation query: %', v_sql;
    END IF;

    EXECUTE v_sql;

    IF v_jobmon_schema IS NOT NULL THEN
        PERFORM update_step(v_step_id, 'OK', 'FK applied');
    END IF;
    v_count := v_count + 1;

END LOOP;

IF v_count = 0 AND v_jobmon_schema IS NOT NULL THEN
    PERFORM update_step(v_step_id, 'OK', 'No FKs found on parent');
END IF;

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

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

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


Question: PostgreSQL Ddl: show example 41.

CREATE TABLE products ( product_no integer, price numeric, valid_at daterange );

Explanation: Example from PostgreSQL documentation on Ddl.


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

CREATE FUNCTION y_trigger() RETURNS trigger AS $$
begin
  raise notice 'y_trigger: a = %', new.a;
  return new;
end;
$$ LANGUAGE plpgsql;

Explanation: DDL from PostgreSQL core regression test for With.


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

SELECT (string_to_array(polqual, ':'))[7] AS inputcollid FROM pg_policy WHERE polrelid = 'coll_t'::regclass;

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

SELECT count(*) FROM (SELECT (string_to_array(polqual, ':'))[7] AS inputcollid FROM pg_policy WHERE polrelid = 'coll_t'::regclass) AS _sub;


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

Explanation: DML from PostgreSQL core regression test for Constraints.


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

SELECT table_name, is_insertable_into
  FROM information_schema.tables
 WHERE table_name LIKE 'rw_view%'
 ORDER BY table_name;

Explanation: Regression test for Updatable Views in PostgreSQL core test suite.

SELECT count(*) FROM (SELECT table_name, is_insertable_into
  FROM information_schema.tables
 WHERE table_name LIKE 'rw_view%'
 ORDER BY table_name) AS _sub;


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

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

SELECT count(*) FROM (SELECT interval 'infinity' * 'nan') AS _sub;


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

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


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

SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 >= timestamp with time zone '1997-01-02';

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

SELECT count(*) FROM (SELECT d1 FROM TIMESTAMPTZ_TBL
   WHERE d1 >= timestamp with time zone '1997-01-02') AS _sub;


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

CREATE TABLE fail_part (LIKE list_parted);

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


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

-- dblink_connect_u allows non-superusers to use
-- non-password authenticated connections, but initially
-- privileges are revoked from public
CREATE FUNCTION dblink_connect_u (text)
RETURNS text
AS 'MODULE_PATHNAME','dblink_connect'
LANGUAGE C STRICT PARALLEL RESTRICTED SECURITY DEFINER;

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


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

SELECT count(*) FROM (SELECT INTERVAL '2 minutes ago 5 days') AS _sub;


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

select * from pg_input_error_info('12:16:14,13', 'pg_snapshot');

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

SELECT count(*) FROM (select * from pg_input_error_info('12:16:14,13', 'pg_snapshot')) AS _sub;


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

select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum
  from gstest2 group by cube (a,b) order by rsum, a, b;

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

SELECT count(*) FROM (select a, b, sum(c), sum(sum(c)) over (order by a,b) as rsum
  from gstest2 group by cube (a,b) order by rsum, a, b) AS _sub;


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

SELECT JSON_QUERY('"a"', '$.a' RETURNING queryfuncs_test_domain DEFAULT (select '"1"')::queryfuncs_test_domain ON ERROR);

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

SELECT count(*) FROM (SELECT JSON_QUERY('"a"', '$.a' RETURNING queryfuncs_test_domain DEFAULT (select '"1"')::queryfuncs_test_domain ON ERROR)) AS _sub;


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

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

SELECT count(*) FROM (select scale(numeric 'inf')) AS _sub;


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

$$ language plpgsql parallel safe;

set debug_parallel_query to on;

explain (verbose, costs off) select error_trap_test();
select error_trap_test();

reset debug_parallel_query;

drop function error_trap_test();
drop function zero_divide();

-- check cases where implicit SQLSTATE variable could be confused with
-- SQLSTATE as a keyword, cf bug #5524
create or replace function raise_test() returns void as $$
begin
  perform 1/0;

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


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

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


Question: PostgreSQL Query: show example 2.

CREATE TABLE cities ( name varchar(80), location point );

Explanation: Example from PostgreSQL documentation on Query.


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

$$;
create trigger depth_b_tr before insert on depth_b
  for each row execute procedure depth_b_tf();

create function depth_c_tf() returns trigger
  language plpgsql as $$
begin
  raise notice '%: depth = %', tg_name, pg_trigger_depth();

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


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

create temp table t (a int unique, b int);

Explanation: DDL from PostgreSQL core regression test for Join.


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

SELECT CASE
  (CASE vol('bar')
    WHEN 'foo' THEN 'it was foo!'
    WHEN vol(null) THEN 'null input'
    WHEN 'bar' THEN 'it was bar!' END
  )
  WHEN 'it was foo!' THEN 'foo recognized'
  WHEN 'it was bar!' THEN 'bar recognized'
  ELSE 'unrecognized' END;

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

SELECT count(*) FROM (SELECT CASE
  (CASE vol('bar')
    WHEN 'foo' THEN 'it was foo!'
    WHEN vol(null) THEN 'null input'
    WHEN 'bar' THEN 'it was bar!' END
  )
  WHEN 'it was foo!' THEN 'foo recognized'
  WHEN 'it was bar!' THEN 'bar recognized'
  ELSE 'unrecognized' END) AS _sub;


Question: PL/pgSQL test: Plperl Util (example 5).

-- test quote_ident

create or replace function perl_quote_ident() returns setof text language plperl as $$
	return_next "undef: ".quote_ident(undef); # generates undef warning if warnings enabled
	return_next "$_: ".quote_ident($_)
		for q{foo}, q{a'b}, q{a"b}, q{c''d}, q{e\f}, q{g.h}, q{};
	return undef;
$$;

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


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

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


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

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


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

select encode(decrypt(encrypt('foo', '0123456', 'aes') || '\x00'::bytea, '0123456', 'aes'), 'escape');

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


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

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

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


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

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

SELECT count(*) FROM (SELECT 'indio' LIKE 'in_o' AS "false") AS _sub;


Question: pgTAP test for Do Tap (assertion 10).

SELECT is(
    findfuncs('foo'),
    CASE WHEN pg_version_num() < 80300 THEN NULL ELSE '{}'::text[] END,
    'findfuncs(unknown) should find no tests'
);

Explanation: SQL assertion from pgTAP test suite for Do Tap.


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

select 'abc abd abc' ~ '^(\w+)( \1)+$' as f;

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

SELECT count(*) FROM (select 'abc abd abc' ~ '^(\w+)( \1)+$' as f) AS _sub;


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

INSERT INTO notnull_tbl1_upg VALUES (NULL, 1), (NULL, 2), (300, 3);

Explanation: DML from PostgreSQL core regression test for Constraints.


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

create table fkest (x integer, x10 integer, x10b integer, x100 integer);


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

SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['a','b']);

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

SELECT count(*) FROM (SELECT jsonb_exists_all('{"a":null, "b":"qq"}', ARRAY['a','b'])) AS _sub;


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

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

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


Question: pgTAP test for Resultset (assertion 293).

CREATE table dubs (pk SERIAL PRIMARY KEY, id int, name text);

Explanation: SQL assertion from pgTAP test suite for Resultset.


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

CREATE INDEX unlogged_hash_index ON unlogged_hash_table USING hash (id int4_ops);

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


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

SELECT count(*) FROM (select * from jsonb_to_record('{"ia2": [[[1], [2], [3]]]}') as x(ia2 int4[][])) AS _sub;